Matridge 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- matridge/__init__.py +14 -0
- matridge/__main__.py +3 -0
- matridge/command.py +176 -0
- matridge/config.py +35 -0
- matridge/contact.py +64 -0
- matridge/gateway.py +76 -0
- matridge/group.py +154 -0
- matridge/matrix.py +490 -0
- matridge/reactions.py +125 -0
- matridge/session.py +301 -0
- matridge/util.py +235 -0
- matridge-0.2.0.dist-info/METADATA +736 -0
- matridge-0.2.0.dist-info/RECORD +16 -0
- matridge-0.2.0.dist-info/WHEEL +5 -0
- matridge-0.2.0.dist-info/entry_points.txt +2 -0
- matridge-0.2.0.dist-info/top_level.txt +1 -0
matridge/matrix.py
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import time
|
|
3
|
+
from asyncio import Task, create_task, sleep
|
|
4
|
+
from functools import wraps
|
|
5
|
+
from typing import TYPE_CHECKING, AsyncIterator, Awaitable, Callable, Optional, Union
|
|
6
|
+
|
|
7
|
+
import nio
|
|
8
|
+
from async_lru import alru_cache
|
|
9
|
+
from nio import Event
|
|
10
|
+
from slidge.core import config as global_config
|
|
11
|
+
from slidge.util.types import LegacyAttachment
|
|
12
|
+
from slixmpp import JID
|
|
13
|
+
from slixmpp.exceptions import XMPPError
|
|
14
|
+
|
|
15
|
+
from . import config
|
|
16
|
+
from .reactions import ReactionCache
|
|
17
|
+
from .util import Credentials, get_replace, server_timestamp_to_datetime
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from .group import MUC, Participant
|
|
21
|
+
from .session import Session
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def catch_all(coro: Callable[["Client", nio.MatrixRoom, nio.Event], Awaitable[None]]):
|
|
25
|
+
@wraps(coro)
|
|
26
|
+
async def wrapped(self: "Client", room: nio.MatrixRoom, event: nio.Event, *a, **kw):
|
|
27
|
+
event_id = getattr(event, "event_id", None)
|
|
28
|
+
if event_id in self.session.events_to_ignore:
|
|
29
|
+
self.log.debug("Ignoring an event matridge has sent: %s", event_id)
|
|
30
|
+
return
|
|
31
|
+
try:
|
|
32
|
+
return await coro(self, room, event, *a, **kw)
|
|
33
|
+
except XMPPError as e:
|
|
34
|
+
self.log.debug(
|
|
35
|
+
"Exception raised in matrix client callback %s", coro, exc_info=e
|
|
36
|
+
)
|
|
37
|
+
except Exception as e:
|
|
38
|
+
self.log.exception(
|
|
39
|
+
"Exception raised in matrix client callback %s", coro, exc_info=e
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
return wrapped
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class AuthenticationClient(nio.AsyncClient):
|
|
46
|
+
def __init__(
|
|
47
|
+
self, server: str, handle: str, jid: JID, log: Optional[logging.Logger] = None
|
|
48
|
+
):
|
|
49
|
+
if not server.startswith("http"):
|
|
50
|
+
server = "https://" + server
|
|
51
|
+
self.store_path = store_path = global_config.HOME_DIR / (jid.bare + "_state")
|
|
52
|
+
store_path.mkdir(exist_ok=True)
|
|
53
|
+
cfg = nio.AsyncClientConfig(
|
|
54
|
+
store_sync_tokens=True,
|
|
55
|
+
max_limit_exceeded=0,
|
|
56
|
+
max_timeouts=0,
|
|
57
|
+
encryption_enabled=True,
|
|
58
|
+
)
|
|
59
|
+
super().__init__(server, handle, store_path=str(store_path), config=cfg)
|
|
60
|
+
if log:
|
|
61
|
+
self.log = log
|
|
62
|
+
else:
|
|
63
|
+
self.log = logging.getLogger(__name__)
|
|
64
|
+
|
|
65
|
+
def get_credentials(self, resp: nio.LoginResponse) -> Credentials:
|
|
66
|
+
return {
|
|
67
|
+
"homeserver": self.homeserver,
|
|
68
|
+
"user_id": resp.user_id,
|
|
69
|
+
"device_id": resp.device_id,
|
|
70
|
+
"access_token": resp.access_token,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async def fix_homeserver(self):
|
|
74
|
+
"""
|
|
75
|
+
Uses https://$HOMESERVER/.well-known/matrix/client to fix the homeserver
|
|
76
|
+
URL.
|
|
77
|
+
"""
|
|
78
|
+
response = await self.discovery_info()
|
|
79
|
+
if isinstance(response, nio.DiscoveryInfoResponse):
|
|
80
|
+
self.homeserver = response.homeserver_url
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Client(AuthenticationClient):
|
|
84
|
+
MIN_RETRY_TIME = 3
|
|
85
|
+
MAX_RETRY_TIME = 300
|
|
86
|
+
REQUEST_TIMEOUT = 60
|
|
87
|
+
CONSIDER_SUCCESSFUL = 10
|
|
88
|
+
|
|
89
|
+
def __init__(self, server: str, handle: str, session: "Session"):
|
|
90
|
+
super().__init__(server, handle, session.user.jid, session.log)
|
|
91
|
+
self.__sync_task: Optional[Task] = None
|
|
92
|
+
self.session = session
|
|
93
|
+
self.reactions = ReactionCache(self)
|
|
94
|
+
|
|
95
|
+
def load(self):
|
|
96
|
+
stored = self.session.user.legacy_module_data
|
|
97
|
+
self.access_token: str = stored["access_token"] # type:ignore
|
|
98
|
+
self.user_id: str = stored["user_id"] # type:ignore
|
|
99
|
+
self.device_id: str = stored["device_id"] # type:ignore
|
|
100
|
+
|
|
101
|
+
async def login_token(self):
|
|
102
|
+
self.load()
|
|
103
|
+
await self.fix_homeserver()
|
|
104
|
+
self.load_store()
|
|
105
|
+
|
|
106
|
+
def __add_event_handlers(self):
|
|
107
|
+
self.add_event_callback(self.on_event, nio.Event) # type:ignore
|
|
108
|
+
self.add_event_callback(self.on_message, nio.RoomMessage) # type:ignore
|
|
109
|
+
self.add_event_callback(self.on_avatar, nio.RoomAvatarEvent) # type:ignore
|
|
110
|
+
self.add_event_callback(self.on_topic, nio.RoomTopicEvent) # type:ignore
|
|
111
|
+
self.add_event_callback(self.on_name, nio.RoomNameEvent) # type:ignore
|
|
112
|
+
self.add_event_callback(self.on_sticker, nio.StickerEvent) # type:ignore
|
|
113
|
+
self.add_event_callback(self.on_member, nio.RoomMemberEvent) # type:ignore
|
|
114
|
+
self.add_event_callback(self.on_redact, nio.RedactionEvent) # type:ignore
|
|
115
|
+
self.add_event_callback(self.on_reaction, nio.ReactionEvent) # type:ignore
|
|
116
|
+
self.add_presence_callback(self.on_presence, nio.PresenceEvent) # type:ignore
|
|
117
|
+
self.add_ephemeral_callback(self.on_receipt, nio.ReceiptEvent) # type:ignore
|
|
118
|
+
self.add_ephemeral_callback(
|
|
119
|
+
self.on_typing, # type:ignore
|
|
120
|
+
nio.TypingNoticeEvent,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
self.add_to_device_callback(
|
|
124
|
+
self.on_key_verification, # type:ignore
|
|
125
|
+
(nio.KeyVerificationEvent, nio.UnknownToDeviceEvent),
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
async def __get_muc(self, room: Union[nio.MatrixRoom, str]) -> "MUC":
|
|
129
|
+
room_id = room.room_id if isinstance(room, nio.MatrixRoom) else room
|
|
130
|
+
return await self.session.bookmarks.by_legacy_id(room_id)
|
|
131
|
+
|
|
132
|
+
async def __sync_forever(self):
|
|
133
|
+
attempts = 0
|
|
134
|
+
while True:
|
|
135
|
+
start = time.time()
|
|
136
|
+
try:
|
|
137
|
+
await self.sync_forever(timeout=self.REQUEST_TIMEOUT)
|
|
138
|
+
except Exception as e:
|
|
139
|
+
duration = time.time() - start
|
|
140
|
+
if duration < self.CONSIDER_SUCCESSFUL:
|
|
141
|
+
attempts += 1
|
|
142
|
+
wait = min(attempts * self.MIN_RETRY_TIME, self.MAX_RETRY_TIME)
|
|
143
|
+
else:
|
|
144
|
+
attempts = 0
|
|
145
|
+
wait = self.MIN_RETRY_TIME
|
|
146
|
+
if attempts < 2:
|
|
147
|
+
self.log.debug(
|
|
148
|
+
"Sync task has raised %r, retrying in %s", e, wait, exc_info=e
|
|
149
|
+
)
|
|
150
|
+
else:
|
|
151
|
+
self.log.error(
|
|
152
|
+
"Sync task has raised %r, retrying in %s", e, wait, exc_info=e
|
|
153
|
+
)
|
|
154
|
+
await sleep(wait)
|
|
155
|
+
else:
|
|
156
|
+
break
|
|
157
|
+
|
|
158
|
+
async def get_participant(
|
|
159
|
+
self, room: nio.MatrixRoom, event: nio.Event
|
|
160
|
+
) -> "Participant":
|
|
161
|
+
muc = await self.__get_muc(room)
|
|
162
|
+
self.log.debug(
|
|
163
|
+
"sender (%s) == me (%s)? %s",
|
|
164
|
+
event.sender,
|
|
165
|
+
self.session.contacts.user_legacy_id,
|
|
166
|
+
event.sender == self.session.contacts.user_legacy_id,
|
|
167
|
+
)
|
|
168
|
+
return await muc.get_participant_by_legacy_id(event.sender)
|
|
169
|
+
|
|
170
|
+
async def listen(self):
|
|
171
|
+
# we need to sync full state or else we don't get the list of all rooms
|
|
172
|
+
resp = await self.sync(full_state=True)
|
|
173
|
+
self.log.debug("Sync")
|
|
174
|
+
if isinstance(resp, nio.SyncError):
|
|
175
|
+
raise PermissionError(resp)
|
|
176
|
+
self.__add_event_handlers()
|
|
177
|
+
self.__sync_task = create_task(self.__sync_forever())
|
|
178
|
+
|
|
179
|
+
def stop_listen(self):
|
|
180
|
+
if self.__sync_task is None:
|
|
181
|
+
return
|
|
182
|
+
self.__sync_task.cancel()
|
|
183
|
+
|
|
184
|
+
async def fetch_history(self, room_id: str, limit: int) -> AsyncIterator[Event]:
|
|
185
|
+
sync_resp = await self.sync()
|
|
186
|
+
if isinstance(sync_resp, nio.SyncError):
|
|
187
|
+
return
|
|
188
|
+
resp = await self.room_messages(
|
|
189
|
+
room_id,
|
|
190
|
+
limit=limit,
|
|
191
|
+
start=sync_resp.next_batch,
|
|
192
|
+
message_filter={"types": ["m.room.message"]},
|
|
193
|
+
)
|
|
194
|
+
if not isinstance(resp, nio.RoomMessagesResponse):
|
|
195
|
+
self.log.warning("Could not fill history.", sync_resp)
|
|
196
|
+
return
|
|
197
|
+
for event in resp.chunk:
|
|
198
|
+
yield event
|
|
199
|
+
|
|
200
|
+
@catch_all
|
|
201
|
+
async def on_event(self, room: nio.MatrixRoom, event: nio.Event):
|
|
202
|
+
if config.NIO_VERBOSE:
|
|
203
|
+
self.log.debug("Event %s '%s': %r", type(event), room, event)
|
|
204
|
+
|
|
205
|
+
@catch_all
|
|
206
|
+
async def on_message(self, room: nio.MatrixRoom, event: nio.RoomMessage):
|
|
207
|
+
self.log.debug("Message: %s", event)
|
|
208
|
+
|
|
209
|
+
participant = await self.get_participant(room, event)
|
|
210
|
+
await participant.send_matrix_message(event)
|
|
211
|
+
|
|
212
|
+
async def on_presence(self, presence: nio.PresenceEvent):
|
|
213
|
+
if presence.user_id == self.session.contacts.user_legacy_id:
|
|
214
|
+
return
|
|
215
|
+
try:
|
|
216
|
+
contact = await self.session.contacts.by_legacy_id(presence.user_id)
|
|
217
|
+
except XMPPError as e:
|
|
218
|
+
self.log.debug("Ignoring presence: %s", presence, exc_info=e)
|
|
219
|
+
return
|
|
220
|
+
contact.update_presence(presence)
|
|
221
|
+
|
|
222
|
+
@catch_all
|
|
223
|
+
async def on_avatar(self, room: nio.MatrixRoom, event: nio.RoomAvatarEvent):
|
|
224
|
+
muc = await self.__get_muc(room)
|
|
225
|
+
muc.avatar = event.avatar_url
|
|
226
|
+
|
|
227
|
+
@catch_all
|
|
228
|
+
async def on_topic(self, room: nio.MatrixRoom, event: nio.RoomTopicEvent):
|
|
229
|
+
muc = await self.__get_muc(room)
|
|
230
|
+
participant = await self.get_participant(room, event)
|
|
231
|
+
muc.subject = event.topic
|
|
232
|
+
muc.subject_setter = participant.name
|
|
233
|
+
muc.subject_date = server_timestamp_to_datetime(event)
|
|
234
|
+
|
|
235
|
+
@catch_all
|
|
236
|
+
async def on_name(self, room: nio.MatrixRoom, event: nio.RoomNameEvent):
|
|
237
|
+
muc = await self.__get_muc(room)
|
|
238
|
+
muc.name = event.name
|
|
239
|
+
|
|
240
|
+
@catch_all
|
|
241
|
+
async def on_sticker(self, room: nio.MatrixRoom, event: nio.StickerEvent):
|
|
242
|
+
participant = await self.get_participant(room, event)
|
|
243
|
+
|
|
244
|
+
resp = await self.download(event.url)
|
|
245
|
+
if isinstance(resp, nio.DownloadResponse):
|
|
246
|
+
await participant.send_files(
|
|
247
|
+
[LegacyAttachment(data=resp.body, caption=event.body)]
|
|
248
|
+
)
|
|
249
|
+
else:
|
|
250
|
+
self.log.error("Failed to download sticker: %r", resp)
|
|
251
|
+
|
|
252
|
+
@catch_all
|
|
253
|
+
async def on_member(self, room: nio.MatrixRoom, event: nio.RoomMemberEvent):
|
|
254
|
+
muc = await self.__get_muc(room)
|
|
255
|
+
participant = await self.get_participant(room, event)
|
|
256
|
+
if event.membership == "join":
|
|
257
|
+
pass
|
|
258
|
+
elif event.membership == "leave":
|
|
259
|
+
if participant.is_user:
|
|
260
|
+
await self.session.bookmarks.remove(muc)
|
|
261
|
+
else:
|
|
262
|
+
muc.remove_participant(participant)
|
|
263
|
+
elif event.membership == "ban":
|
|
264
|
+
# TODO: handle bans in slidge core
|
|
265
|
+
pass
|
|
266
|
+
elif event.membership == "invite":
|
|
267
|
+
# TODO: what's that event exactly?
|
|
268
|
+
pass
|
|
269
|
+
|
|
270
|
+
@catch_all
|
|
271
|
+
async def on_typing(self, room: nio.MatrixRoom, event: nio.TypingNoticeEvent):
|
|
272
|
+
muc = await self.__get_muc(room)
|
|
273
|
+
for user_id in event.users:
|
|
274
|
+
participant = await muc.get_participant_by_legacy_id(user_id)
|
|
275
|
+
participant.composing()
|
|
276
|
+
|
|
277
|
+
@catch_all
|
|
278
|
+
async def on_receipt(self, room: nio.MatrixRoom, event: nio.ReceiptEvent):
|
|
279
|
+
muc = await self.__get_muc(room)
|
|
280
|
+
for receipt in event.receipts:
|
|
281
|
+
if receipt.receipt_type == "m.read":
|
|
282
|
+
participant = await muc.get_participant_by_legacy_id(receipt.user_id)
|
|
283
|
+
participant.displayed(receipt.event_id)
|
|
284
|
+
|
|
285
|
+
@catch_all
|
|
286
|
+
async def on_reaction(self, room: nio.MatrixRoom, event: nio.ReactionEvent, **kw):
|
|
287
|
+
self.log.debug("Reaction2")
|
|
288
|
+
|
|
289
|
+
source = event.source
|
|
290
|
+
msg_id = await self.get_original_id(room.room_id, event.reacts_to)
|
|
291
|
+
|
|
292
|
+
sender = source["sender"]
|
|
293
|
+
emoji = event.key
|
|
294
|
+
|
|
295
|
+
await self.reactions.add(room.room_id, msg_id, sender, emoji, event.event_id)
|
|
296
|
+
reactions = await self.reactions.get(room.room_id, msg_id, sender)
|
|
297
|
+
|
|
298
|
+
participant = await self.get_participant(room, event)
|
|
299
|
+
participant.react(msg_id, reactions, **kw)
|
|
300
|
+
|
|
301
|
+
@catch_all
|
|
302
|
+
async def on_redact(self, room: nio.MatrixRoom, event: nio.RedactionEvent):
|
|
303
|
+
self.log.debug("Redaction: %s", event)
|
|
304
|
+
redacter = await self.get_participant(room, event)
|
|
305
|
+
if reaction_target := self.reactions.remove(event.redacts):
|
|
306
|
+
msg_id = await self.get_original_id(room.room_id, reaction_target.event)
|
|
307
|
+
reactions = await self.reactions.get(
|
|
308
|
+
reaction_target.room, msg_id, reaction_target.sender
|
|
309
|
+
)
|
|
310
|
+
redacter.react(msg_id, reactions)
|
|
311
|
+
return
|
|
312
|
+
|
|
313
|
+
redacted_event = await self.get_event(room.room_id, event.redacts)
|
|
314
|
+
|
|
315
|
+
if redacted_event and event.sender == redacted_event.sender:
|
|
316
|
+
redacter.retract(event.redacts)
|
|
317
|
+
else:
|
|
318
|
+
redacter.moderate(event.redacts, event.reason)
|
|
319
|
+
|
|
320
|
+
@alru_cache(maxsize=1000)
|
|
321
|
+
async def get_original_id(self, room_id: str, event_id: str) -> str:
|
|
322
|
+
event = await self.get_event(room_id, event_id)
|
|
323
|
+
if event is None:
|
|
324
|
+
return event_id
|
|
325
|
+
# no need to check recursively because replacements must refer to
|
|
326
|
+
# the original event
|
|
327
|
+
return get_replace(event.source) or event_id
|
|
328
|
+
|
|
329
|
+
@alru_cache(maxsize=100)
|
|
330
|
+
async def get_event(self, room_id: str, event_id: str) -> Optional[nio.Event]:
|
|
331
|
+
resp = await self.session.matrix.room_get_event(room_id, event_id)
|
|
332
|
+
if isinstance(resp, nio.RoomGetEventError):
|
|
333
|
+
return None
|
|
334
|
+
return resp.event
|
|
335
|
+
|
|
336
|
+
async def on_key_verification(
|
|
337
|
+
self, event: nio.KeyVerificationEvent | nio.UnknownToDeviceEvent
|
|
338
|
+
):
|
|
339
|
+
# TODO: once https://github.com/matrix-nio/matrix-nio/issues/430 is fixed, we should be able to simplify
|
|
340
|
+
# this by ditching UnknownToDeviceEvent
|
|
341
|
+
# Thanks to DomNomNom from the nio Channel,
|
|
342
|
+
# cf https://github.com/wreald/matrix-nio/commit/5cb8e99965bcb622101b1d
|
|
343
|
+
content = event.source.get("content", {})
|
|
344
|
+
if event.source.get("type") == "m.key.verification.request":
|
|
345
|
+
self.session.send_gateway_message(
|
|
346
|
+
"Got verification request. Waiting for other device to accept SAS method…"
|
|
347
|
+
)
|
|
348
|
+
methods = content.get("methods")
|
|
349
|
+
if "m.sas.v1" not in methods:
|
|
350
|
+
self.session.send_gateway_message(
|
|
351
|
+
"Received a device verification request, but other device does not support SAS authentication. "
|
|
352
|
+
f"Methods: {methods}."
|
|
353
|
+
)
|
|
354
|
+
return
|
|
355
|
+
txid = content.get("transaction_id")
|
|
356
|
+
ready_event = nio.ToDeviceMessage(
|
|
357
|
+
type="m.key.verification.ready",
|
|
358
|
+
recipient=event.sender,
|
|
359
|
+
recipient_device=content.get("from_device"),
|
|
360
|
+
content={
|
|
361
|
+
"from_device": self.device_id,
|
|
362
|
+
"methods": ["m.sas.v1"],
|
|
363
|
+
"transaction_id": txid,
|
|
364
|
+
},
|
|
365
|
+
)
|
|
366
|
+
resp = await self.to_device(ready_event, txid)
|
|
367
|
+
if isinstance(resp, nio.ToDeviceError):
|
|
368
|
+
self.session.send_gateway_message(f"to_device failed with {resp}")
|
|
369
|
+
elif isinstance(event, nio.KeyVerificationStart): # first step
|
|
370
|
+
if "emoji" not in event.short_authentication_string:
|
|
371
|
+
self.session.send_gateway_message(
|
|
372
|
+
"Received a device verification request, but other device does not support emoji verification "
|
|
373
|
+
f"{event.short_authentication_string}."
|
|
374
|
+
)
|
|
375
|
+
return
|
|
376
|
+
resp = await self.accept_key_verification(event.transaction_id)
|
|
377
|
+
if isinstance(resp, nio.ToDeviceError):
|
|
378
|
+
self.session.send_gateway_message(
|
|
379
|
+
f"accept_key_verification failed with {resp}"
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
sas = self.key_verifications.get(event.transaction_id)
|
|
383
|
+
|
|
384
|
+
if sas is None:
|
|
385
|
+
self.session.send_gateway_message(f"transaction_id could not be found")
|
|
386
|
+
return
|
|
387
|
+
|
|
388
|
+
todevice_msg = sas.share_key()
|
|
389
|
+
resp = await self.to_device(todevice_msg)
|
|
390
|
+
if isinstance(resp, nio.ToDeviceError):
|
|
391
|
+
self.session.send_gateway_message(f"❌ to_device failed with {resp}")
|
|
392
|
+
|
|
393
|
+
elif isinstance(event, nio.KeyVerificationCancel): # anytime
|
|
394
|
+
self.session.send_gateway_message(
|
|
395
|
+
f"Verification has been cancelled by {event.sender} "
|
|
396
|
+
f'for reason "{event.reason}".'
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
elif isinstance(event, nio.KeyVerificationKey): # second step
|
|
400
|
+
sas = self.key_verifications.get(event.transaction_id)
|
|
401
|
+
|
|
402
|
+
if sas is None:
|
|
403
|
+
self.session.send_gateway_message(f"transaction_id could not be found")
|
|
404
|
+
return
|
|
405
|
+
|
|
406
|
+
self.session.send_gateway_message(f"{sas.get_emoji()}")
|
|
407
|
+
|
|
408
|
+
yn = await self.session.input("Do the emojis match? (Y/N) (C for Cancel) ")
|
|
409
|
+
if yn.lower() == "y":
|
|
410
|
+
resp = await self.confirm_short_auth_string(event.transaction_id)
|
|
411
|
+
if isinstance(resp, nio.ToDeviceError):
|
|
412
|
+
self.session.send_gateway_message(
|
|
413
|
+
f"confirm_short_auth_string failed with {resp}"
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
# Extra step in new flow: once we have completed the SAS
|
|
417
|
+
# verification successfully, send a 'done' to-device event
|
|
418
|
+
# to the other device to assert that the verification was
|
|
419
|
+
# successful.
|
|
420
|
+
done_message = nio.ToDeviceMessage(
|
|
421
|
+
type="m.key.verification.done",
|
|
422
|
+
recipient=event.sender,
|
|
423
|
+
recipient_device=sas.other_olm_device.device_id,
|
|
424
|
+
content={
|
|
425
|
+
"transaction_id": sas.transaction_id,
|
|
426
|
+
},
|
|
427
|
+
)
|
|
428
|
+
resp = await self.to_device(done_message, sas.transaction_id)
|
|
429
|
+
if isinstance(resp, nio.ToDeviceError):
|
|
430
|
+
self.session.send_gateway_message(f"'done' failed with {resp}")
|
|
431
|
+
|
|
432
|
+
elif yn.lower() == "n": # no, don't match, reject
|
|
433
|
+
resp = await self.cancel_key_verification(
|
|
434
|
+
event.transaction_id, reject=True
|
|
435
|
+
)
|
|
436
|
+
if isinstance(resp, nio.ToDeviceError):
|
|
437
|
+
self.session.send_gateway_message(
|
|
438
|
+
f"cancel_key_verification failed with {resp}"
|
|
439
|
+
)
|
|
440
|
+
else: # C or anything for cancel
|
|
441
|
+
self.session.send_gateway_message(
|
|
442
|
+
"Cancelled by user! Verification will be cancelled."
|
|
443
|
+
)
|
|
444
|
+
resp = await self.cancel_key_verification(
|
|
445
|
+
event.transaction_id, reject=False
|
|
446
|
+
)
|
|
447
|
+
if isinstance(resp, nio.ToDeviceError):
|
|
448
|
+
self.session.send_gateway_message(
|
|
449
|
+
f"cancel_key_verification failed with {resp}"
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
elif isinstance(event, nio.KeyVerificationMac): # third step
|
|
453
|
+
sas = self.key_verifications.get(event.transaction_id)
|
|
454
|
+
|
|
455
|
+
if sas is None:
|
|
456
|
+
self.session.send_gateway_message(f"transaction_id could not be found")
|
|
457
|
+
return
|
|
458
|
+
|
|
459
|
+
try:
|
|
460
|
+
todevice_msg = sas.get_mac()
|
|
461
|
+
except nio.LocalProtocolError as e:
|
|
462
|
+
# e.g. it might have been cancelled by ourselves
|
|
463
|
+
self.session.send_gateway_message(
|
|
464
|
+
f"Cancelled or protocol error: Reason: {e}.\n"
|
|
465
|
+
f"Verification with {event.sender} not concluded. "
|
|
466
|
+
"Try again?"
|
|
467
|
+
)
|
|
468
|
+
else:
|
|
469
|
+
resp = await self.to_device(todevice_msg)
|
|
470
|
+
if isinstance(resp, nio.ToDeviceError):
|
|
471
|
+
self.session.send_gateway_message(f"to_device failed with {resp}")
|
|
472
|
+
elif event.source.get("type") == "m.key.verification.done":
|
|
473
|
+
# Final step, other device acknowledges verification success.
|
|
474
|
+
txid = content.get("transaction_id")
|
|
475
|
+
sas = self.key_verifications[txid]
|
|
476
|
+
|
|
477
|
+
self.session.send_gateway_message(
|
|
478
|
+
f"sas.we_started_it = {sas.we_started_it}\n"
|
|
479
|
+
f"sas.sas_accepted = {sas.sas_accepted}\n"
|
|
480
|
+
f"sas.canceled = {sas.canceled}\n"
|
|
481
|
+
f"sas.timed_out = {sas.timed_out}\n"
|
|
482
|
+
f"sas.verified = {sas.verified}\n"
|
|
483
|
+
f"sas.verified_devices = {sas.verified_devices}\n"
|
|
484
|
+
)
|
|
485
|
+
self.session.send_gateway_message("Emoji verification was successful!")
|
|
486
|
+
else:
|
|
487
|
+
self.session.send_gateway_message(
|
|
488
|
+
f"Received unexpected event type {type(event)}. "
|
|
489
|
+
f"Event is {event}. Event will be ignored."
|
|
490
|
+
)
|
matridge/reactions.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
from collections import defaultdict, namedtuple
|
|
2
|
+
from typing import TYPE_CHECKING, Literal, Optional, overload
|
|
3
|
+
|
|
4
|
+
import nio
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from matridge.matrix import Client
|
|
8
|
+
|
|
9
|
+
ReactionTarget = namedtuple("ReactionTarget", ["room", "event", "sender"])
|
|
10
|
+
Reaction = namedtuple("Reaction", ["event", "emoji"])
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ReactionCache:
|
|
14
|
+
"""
|
|
15
|
+
To avoid fetching history on each matrix reaction event, we store the
|
|
16
|
+
"reaction state" per sender per message.
|
|
17
|
+
|
|
18
|
+
This is because matrix reaction events are atomic, unlike XMPP reactions
|
|
19
|
+
which contain the full state in each event.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
# TODO: periodically purge cache for messages older than XX days *and/or*
|
|
23
|
+
# implement proper non-RAM persistent storage
|
|
24
|
+
|
|
25
|
+
def __init__(self, client: "Client"):
|
|
26
|
+
self.matrix = client
|
|
27
|
+
self.log = client.session.log
|
|
28
|
+
|
|
29
|
+
# key = room, msg, sender
|
|
30
|
+
self._reaction_cache = defaultdict[ReactionTarget, list[Reaction]](list)
|
|
31
|
+
|
|
32
|
+
# key = event
|
|
33
|
+
# on redaction events, we only get the
|
|
34
|
+
self._event_cache = dict[str, ReactionTarget]()
|
|
35
|
+
|
|
36
|
+
async def _fetch_if_needed(self, target: ReactionTarget):
|
|
37
|
+
if target not in self._reaction_cache:
|
|
38
|
+
await self._fetch(target.room, target.sender)
|
|
39
|
+
# nothing was added for this target, meaning it's empty
|
|
40
|
+
# initialize an empty list to avoid checking for the same message later
|
|
41
|
+
if target not in self._reaction_cache:
|
|
42
|
+
self._reaction_cache[target] = []
|
|
43
|
+
|
|
44
|
+
async def _fetch(self, room: str, sender: Optional[str] = None, limit=100):
|
|
45
|
+
self.log.debug("Getting reactions...")
|
|
46
|
+
|
|
47
|
+
filt = {"senders": [sender], "types": ["m.reaction"]}
|
|
48
|
+
|
|
49
|
+
sync_resp = await self.matrix.sync(sync_filter=filt)
|
|
50
|
+
self.log.debug("Sync")
|
|
51
|
+
if isinstance(sync_resp, nio.SyncError):
|
|
52
|
+
return
|
|
53
|
+
|
|
54
|
+
resp = await self.matrix.room_messages(
|
|
55
|
+
room,
|
|
56
|
+
limit=limit,
|
|
57
|
+
start=sync_resp.next_batch,
|
|
58
|
+
message_filter=filt,
|
|
59
|
+
)
|
|
60
|
+
if not isinstance(resp, nio.RoomMessagesResponse):
|
|
61
|
+
return
|
|
62
|
+
|
|
63
|
+
for event in resp.chunk:
|
|
64
|
+
if not isinstance(event, nio.ReactionEvent):
|
|
65
|
+
continue
|
|
66
|
+
reacts_to = event.reacts_to
|
|
67
|
+
if not reacts_to:
|
|
68
|
+
continue
|
|
69
|
+
emoji = event.key
|
|
70
|
+
if emoji:
|
|
71
|
+
target = ReactionTarget(
|
|
72
|
+
room=room,
|
|
73
|
+
sender=event.sender,
|
|
74
|
+
event=await self.matrix.get_original_id(room, reacts_to),
|
|
75
|
+
)
|
|
76
|
+
self._reaction_cache[target].append(
|
|
77
|
+
Reaction(event=event.event_id, emoji=emoji)
|
|
78
|
+
)
|
|
79
|
+
self._event_cache[event.event_id] = target
|
|
80
|
+
else:
|
|
81
|
+
self.log.debug("Weird reaction? %s", event)
|
|
82
|
+
|
|
83
|
+
async def add(
|
|
84
|
+
self, room: str, msg: str, sender: str, emoji: str, reaction_event: str
|
|
85
|
+
) -> None:
|
|
86
|
+
target = ReactionTarget(room=room, event=msg, sender=sender)
|
|
87
|
+
await self._fetch_if_needed(target)
|
|
88
|
+
reaction = Reaction(event=reaction_event, emoji=emoji)
|
|
89
|
+
self._reaction_cache[target].append(reaction)
|
|
90
|
+
self._event_cache[reaction_event] = target
|
|
91
|
+
self.log.debug("Added: %s - %s", target, reaction)
|
|
92
|
+
|
|
93
|
+
@overload
|
|
94
|
+
async def get(
|
|
95
|
+
self, room: str, msg: str, sender: str, with_event_ids: Literal[False]
|
|
96
|
+
) -> set[str]: ...
|
|
97
|
+
|
|
98
|
+
@overload
|
|
99
|
+
async def get(self, room: str, msg: str, sender: str) -> set[str]: ...
|
|
100
|
+
|
|
101
|
+
@overload
|
|
102
|
+
async def get(
|
|
103
|
+
self, room: str, msg: str, sender: str, with_event_ids: Literal[True]
|
|
104
|
+
) -> dict[str, str]: ...
|
|
105
|
+
|
|
106
|
+
async def get(self, room, msg, sender, with_event_ids=False):
|
|
107
|
+
target = ReactionTarget(room=room, event=msg, sender=sender)
|
|
108
|
+
await self._fetch_if_needed(target)
|
|
109
|
+
if with_event_ids:
|
|
110
|
+
return {r.emoji: r.event for r in self._reaction_cache[target]}
|
|
111
|
+
else:
|
|
112
|
+
return set(r.emoji for r in self._reaction_cache[target])
|
|
113
|
+
|
|
114
|
+
def remove(self, event_id: str) -> Optional[ReactionTarget]:
|
|
115
|
+
self.log.debug("Needle: %s; Haystack: %s", event_id, self._event_cache)
|
|
116
|
+
target = self._event_cache.pop(event_id, None)
|
|
117
|
+
if target is None:
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
cache = self._reaction_cache[target]
|
|
121
|
+
cache[:] = [r for r in cache if r.event != event_id]
|
|
122
|
+
return target
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
__all__ = ("ReactionCache",)
|