9 def __init__(self, room_name, fifo_path):
10 self._room_name = room_name
11 self._fifo_path = fifo_path
12 self._joined_room_id = None
14 async def run(self, client):
15 self._log(logging.INFO, "Presence running")
18 done, pending = await asyncio.wait(
19 [asyncio.create_task( self._room_joining_loop(client) ),
20 asyncio.create_task( self._message_loop(client) )],
21 return_when = asyncio.FIRST_EXCEPTION
27 self._log(logging.INFO, "Presence stopped")
30 asyncio.get_running_loop().call_soon_threadsafe(
31 Presence._do_stop, self
38 async def _room_joining_loop(self, client):
42 prior_joined_room_id = self._joined_room_id
43 self._joined_room_id = await self._get_joined_room_id(client)
45 if self._joined_room_id != None:
46 if self._joined_room_id != prior_joined_room_id:
47 self._log(logging.INFO, "Joined room")
49 if self._joined_room_id != prior_joined_room_id:
50 self._log(logging.INFO, "Got kicked out of room?")
52 self._log(logging.INFO, "Not yet a room member")
54 for room_id, room in client.invited_rooms.items():
55 if room.display_name == self._room_name:
57 self._log(logging.INFO, "Joining room")
58 await client.join(room_id)
61 self._log(logging.INFO, "Got no room invite yet")
63 await asyncio.sleep(3.0)
65 async def _message_loop(self, client):
68 async for line in self._read_fifo(self._fifo_path):
71 if self._joined_room_id != None:
73 msgB64Bytes = line.rstrip("\n").encode("UTF-8")
74 msgBytes = base64.b64decode(msgB64Bytes)
75 msgStr = msgBytes.decode("UTF-8")
77 self._log(logging.WARNING, "Error decoding message")
79 await client.room_send(
80 room_id=self._joined_room_id,
81 message_type="m.room.message",
88 self._log(logging.WARNING, "Dropping message cause no room joined")
90 def _tickle_fifo(self):
93 fifo = posix.open(self._fifo_path, posix.O_WRONLY | posix.O_NONBLOCK)
94 posix.write(fifo, "\n".encode())
96 if e.errno == errno.ENXIO:
102 async def _get_joined_room_id(self, client):
103 joined_room_ids = ( await client.joined_rooms() ).rooms
104 for room_id, room in client.rooms.items():
105 if room.display_name == self._room_name:
106 if room_id in joined_room_ids:
110 def _log(self, level, msg, *args, **kwargs):
111 logging.log(level, "P{%s}: %s" % (self._room_name, msg), *args, **kwargs)
114 async def _read_fifo(file_path):
116 async with aiofiles.open(file_path) as fifo:
117 async for line in fifo: