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)
76 self._log(logging.WARNING, "Error decoding message")
78 await client.room_send(
79 room_id=self._joined_room_id,
80 message_type="m.room.message",
83 "body": msgBytes.decode("UTF-8")
87 self._log(logging.WARNING, "Dropping message cause no room joined")
89 def _tickle_fifo(self):
92 fifo = posix.open(self._fifo_path, posix.O_WRONLY | posix.O_NONBLOCK)
93 posix.write(fifo, "\n".encode())
95 if e.errno == errno.ENXIO:
101 async def _get_joined_room_id(self, client):
102 joined_room_ids = ( await client.joined_rooms() ).rooms
103 for room_id, room in client.rooms.items():
104 if room.display_name == self._room_name:
105 if room_id in joined_room_ids:
109 def _log(self, level, msg, *args, **kwargs):
110 logging.log(level, "P{%s}: %s" % (self._room_name, msg), *args, **kwargs)
113 async def _read_fifo(file_path):
115 async with aiofiles.open(file_path) as fifo:
116 async for line in fifo: