This repository has been archived by the owner on Mar 2, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathportal.py
2011 lines (1863 loc) · 76.7 KB
/
portal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# mautrix-facebook - A Matrix-Facebook Messenger puppeting bridge.
# Copyright (C) 2022 Tulir Asokan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from __future__ import annotations
from typing import TYPE_CHECKING, Any, AsyncGenerator, Awaitable, Pattern, cast
from collections import deque
from html import escape
from io import BytesIO
import asyncio
import base64
import mimetypes
import re
import time
from yarl import URL
import magic
from maufbapi.types import graphql, mqtt
from mautrix.appservice import DOUBLE_PUPPET_SOURCE_KEY, IntentAPI
from mautrix.bridge import BasePortal, NotificationDisabler, async_getter_lock
from mautrix.errors import IntentError, MatrixError, MForbidden, MNotFound, SessionNotFound
from mautrix.types import (
AudioInfo,
ContentURI,
EncryptedFile,
EventID,
EventType,
FileInfo,
Format,
ImageInfo,
LocationMessageEventContent,
MediaMessageEventContent,
Membership,
MemberStateEventContent,
MessageEventContent,
MessageType,
RelationType,
RoomID,
TextMessageEventContent,
UserID,
VideoInfo,
)
from mautrix.util import ffmpeg
from mautrix.util.message_send_checkpoint import MessageSendCheckpointStatus
from mautrix.util.simple_lock import SimpleLock
from . import matrix as m, puppet as p, user as u
from .config import Config
from .db import (
Message as DBMessage,
Portal as DBPortal,
Reaction as DBReaction,
ThreadType,
UserPortal as UserPortal,
)
from .formatter import facebook_to_matrix, matrix_to_facebook
if TYPE_CHECKING:
from .__main__ import MessengerBridge
try:
from PIL import Image
except ImportError:
Image = None
try:
from mautrix.crypto.attachments import decrypt_attachment, encrypt_attachment
except ImportError:
decrypt_attachment = encrypt_attachment = None
geo_uri_regex: Pattern = re.compile(r"^geo:(-?\d+.\d+),(-?\d+.\d+)$")
class FakeLock:
async def __aenter__(self) -> None:
pass
async def __aexit__(self, exc_type, exc, tb) -> None:
pass
StateBridge = EventType.find("m.bridge", EventType.Class.STATE)
StateHalfShotBridge = EventType.find("uk.half-shot.bridge", EventType.Class.STATE)
class Portal(DBPortal, BasePortal):
invite_own_puppet_to_pm: bool = False
by_mxid: dict[RoomID, Portal] = {}
by_fbid: dict[tuple[int, int], Portal] = {}
matrix: m.MatrixHandler
config: Config
_main_intent: IntentAPI | None
_create_room_lock: asyncio.Lock
_dedup: deque[str]
_oti_dedup: dict[int, DBMessage]
_send_locks: dict[int, asyncio.Lock]
_noop_lock: FakeLock = FakeLock()
_typing: set[UserID]
backfill_lock: SimpleLock
_backfill_leave: set[IntentAPI] | None
def __init__(
self,
fbid: int,
fb_receiver: int,
fb_type: ThreadType,
mxid: RoomID | None = None,
name: str | None = None,
photo_id: str | None = None,
avatar_url: ContentURI | None = None,
encrypted: bool = False,
name_set: bool = False,
avatar_set: bool = False,
relay_user_id: UserID | None = None,
) -> None:
super().__init__(
fbid,
fb_receiver,
fb_type,
mxid,
name,
photo_id,
avatar_url,
encrypted,
name_set,
avatar_set,
relay_user_id,
)
self.log = self.log.getChild(self.fbid_log)
self._main_intent = None
self._create_room_lock = asyncio.Lock()
self._dedup = deque(maxlen=100)
self._oti_dedup = {}
self._send_locks = {}
self._typing = set()
self.backfill_lock = SimpleLock(
"Waiting for backfilling to finish before handling %s", log=self.log
)
self._backfill_leave = None
self._relay_user = None
@classmethod
def init_cls(cls, bridge: "MessengerBridge") -> None:
BasePortal.bridge = bridge
cls.az = bridge.az
cls.config = bridge.config
cls.loop = bridge.loop
cls.matrix = bridge.matrix
cls.invite_own_puppet_to_pm = cls.config["bridge.invite_own_puppet_to_pm"]
NotificationDisabler.puppet_cls = p.Puppet
NotificationDisabler.config_enabled = cls.config["bridge.backfill.disable_notifications"]
# region DB conversion
async def delete(self) -> None:
if self.mxid:
await DBMessage.delete_all_by_room(self.mxid)
self.by_fbid.pop(self.fbid_full, None)
self.by_mxid.pop(self.mxid, None)
await super().delete()
# endregion
# region Properties
@property
def fbid_full(self) -> tuple[int, int]:
return self.fbid, self.fb_receiver
@property
def fbid_log(self) -> str:
if self.is_direct:
return f"{self.fbid}<->{self.fb_receiver}"
return str(self.fbid)
@property
def mqtt_key(self) -> mqtt.ThreadKey:
if self.fb_type == ThreadType.USER:
return mqtt.ThreadKey(other_user_id=self.fbid)
elif self.fb_type == ThreadType.GROUP:
return mqtt.ThreadKey(thread_fbid=self.fbid)
else:
raise ValueError("Unsupported thread type")
@property
def graphql_key(self) -> graphql.ThreadKey:
if self.fb_type == ThreadType.USER:
return graphql.ThreadKey(other_user_id=str(self.fbid))
elif self.fb_type == ThreadType.GROUP:
return graphql.ThreadKey(thread_fbid=str(self.fbid))
else:
raise ValueError("Unsupported thread type")
@property
def is_direct(self) -> bool:
return self.fb_type == ThreadType.USER
@property
def main_intent(self) -> IntentAPI:
if not self._main_intent:
raise ValueError("Portal must be postinit()ed before main_intent can be used")
return self._main_intent
# endregion
# region Chat info updating
async def update_info(
self, source: u.User | None = None, info: graphql.Thread | None = None
) -> graphql.Thread | None:
if not info:
self.log.debug("Called update_info with no info, fetching thread info...")
threads = await source.client.fetch_thread_info(self.fbid)
if not threads:
return None
elif threads[0].thread_key.id != self.fbid:
self.log.warning(
"fetch_thread_info response contained different ID (%s) than expected (%s)",
threads[0].thread_key.id,
self.fbid,
)
self.log.debug(f"Number of threads in unexpected response: {len(threads)}")
info = threads[0]
if info.thread_key != self.graphql_key:
self.log.warning(
"Got different ID (%s) than what asked for (%s) when fetching info",
info.thread_key.id,
self.fbid,
)
changed = False
if not self.is_direct:
changed = any(
await asyncio.gather(
self._update_name(info.name),
self._update_photo(source, info.image),
)
)
changed = await self._update_participants(source, info) or changed
if changed:
await self.update_bridge_info()
await self.save()
return info
@staticmethod
def get_photo_id(photo: graphql.Picture | str | None) -> str | None:
if not photo:
return None
elif isinstance(photo, graphql.Picture):
photo = photo.uri
path = URL(photo).path
return path[path.rfind("/") + 1 :]
@classmethod
async def _reupload_fb_file(
cls,
url: str,
source: u.User,
intent: IntentAPI,
*,
filename: str | None = None,
encrypt: bool = False,
referer: str = "messenger_thread_photo",
find_size: bool = False,
convert_audio: bool = False,
) -> tuple[ContentURI, FileInfo | VideoInfo | AudioInfo | ImageInfo, EncryptedFile | None]:
if not url:
raise ValueError("URL not provided")
headers = {"referer": f"fbapp://{source.state.application.client_id}/{referer}"}
sandbox = cls.config["bridge.sandbox_media_download"]
async with source.client.get(url, headers=headers, sandbox=sandbox) as resp:
length = int(resp.headers["Content-Length"])
if length > cls.matrix.media_config.upload_size:
raise ValueError("File not available: too large")
data = await resp.read()
mime = magic.from_buffer(data, mime=True)
if convert_audio and mime != "audio/ogg":
data = await ffmpeg.convert_bytes(
data, ".ogg", output_args=("-c:a", "libopus"), input_mime=mime
)
mime = "audio/ogg"
info = FileInfo(mimetype=mime, size=len(data))
if Image and mime.startswith("image/") and find_size:
with Image.open(BytesIO(data)) as img:
width, height = img.size
info = ImageInfo(mimetype=mime, size=len(data), width=width, height=height)
upload_mime_type = mime
decryption_info = None
if encrypt and encrypt_attachment:
data, decryption_info = encrypt_attachment(data)
upload_mime_type = "application/octet-stream"
filename = None
url = await intent.upload_media(data, mime_type=upload_mime_type, filename=filename)
if decryption_info:
decryption_info.url = url
return url, info, decryption_info
async def _update_name(self, name: str) -> bool:
if not name:
self.log.warning("Got empty name in _update_name call")
return False
if self.name != name or not self.name_set:
self.log.trace("Updating name %s -> %s", self.name, name)
self.name = name
if self.mxid and (self.encrypted or not self.is_direct):
try:
await self.main_intent.set_room_name(self.mxid, self.name)
self.name_set = True
except Exception:
self.log.exception("Failed to set room name")
self.name_set = False
return True
return False
async def _update_photo(self, source: u.User, photo: graphql.Picture) -> bool:
if self.is_direct and not self.encrypted:
return False
photo_id = self.get_photo_id(photo)
if self.photo_id != photo_id or not self.avatar_set:
self.photo_id = photo_id
if photo:
if self.photo_id != photo_id or not self.avatar_url:
# Reset avatar_url first in case the upload fails
self.avatar_url = None
self.avatar_url = await p.Puppet.reupload_avatar(
source,
self.main_intent,
photo.uri,
self.fbid,
use_graph=self.is_direct and (photo.height or 0) < 500,
)
else:
self.avatar_url = ContentURI("")
if self.mxid:
try:
await self.main_intent.set_room_avatar(self.mxid, self.avatar_url)
self.avatar_set = True
except Exception:
self.log.exception("Failed to set room avatar")
self.avatar_set = False
return True
return False
async def _update_photo_from_puppet(self, puppet: p.Puppet) -> bool:
if self.photo_id == puppet.photo_id and self.avatar_set:
return False
self.photo_id = puppet.photo_id
if puppet.photo_mxc:
self.avatar_url = puppet.photo_mxc
elif self.photo_id:
profile = await self.main_intent.get_profile(puppet.default_mxid)
self.avatar_url = profile.avatar_url
puppet.photo_mxc = profile.avatar_url
else:
self.avatar_url = ContentURI("")
if self.mxid:
try:
await self.main_intent.set_room_avatar(self.mxid, self.avatar_url)
self.avatar_set = True
except Exception:
self.log.exception("Failed to set room avatar")
self.avatar_set = False
return True
async def sync_per_room_nick(self, puppet: p.Puppet, name: str) -> None:
intent = puppet.intent_for(self)
content = MemberStateEventContent(
membership=Membership.JOIN,
avatar_url=puppet.photo_mxc,
displayname=name or puppet.name,
)
content[DOUBLE_PUPPET_SOURCE_KEY] = self.bridge.name
current_state = await intent.state_store.get_member(self.mxid, intent.mxid)
if not current_state or current_state.displayname != content.displayname:
self.log.debug(
"Syncing %s's per-room nick %s to the room",
puppet.fbid,
content.displayname,
)
await intent.send_state_event(
self.mxid, EventType.ROOM_MEMBER, content, state_key=intent.mxid
)
async def _update_participants(self, source: u.User, info: graphql.Thread) -> bool:
changed = False
nick_map = info.customization_info.nickname_map if info.customization_info else {}
for participant in info.all_participants.nodes:
puppet = await p.Puppet.get_by_fbid(int(participant.id))
await puppet.update_info(source, participant.messaging_actor)
if self.is_direct and self.fbid == puppet.fbid and self.encrypted:
changed = await self._update_name(puppet.name) or changed
changed = await self._update_photo_from_puppet(puppet) or changed
if self.mxid:
if puppet.fbid != self.fb_receiver or puppet.is_real_user:
await puppet.intent_for(self).ensure_joined(self.mxid, bot=self.main_intent)
if puppet.fbid in nick_map:
await self.sync_per_room_nick(puppet, nick_map[puppet.fbid])
return changed
# endregion
# region Matrix room creation
async def update_matrix_room(self, source: u.User, info: graphql.Thread | None = None) -> None:
try:
await self._update_matrix_room(source, info)
except Exception:
self.log.exception("Failed to update portal")
def _get_invite_content(self, double_puppet: p.Puppet | None) -> dict[str, Any]:
invite_content = {}
if double_puppet:
invite_content["fi.mau.will_auto_accept"] = True
if self.is_direct:
invite_content["is_direct"] = True
return invite_content
async def _update_matrix_room(
self, source: u.User, info: graphql.Thread | None = None
) -> None:
puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
await self.main_intent.invite_user(
self.mxid,
source.mxid,
check_cache=True,
extra_content=self._get_invite_content(puppet),
)
if puppet:
did_join = await puppet.intent.ensure_joined(self.mxid)
if did_join and self.is_direct:
await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
info = await self.update_info(source, info)
if not info:
self.log.warning("Canceling _update_matrix_room as update_info didn't return info")
return
up = await UserPortal.get(source.fbid, self.fbid, self.fb_receiver)
if not up:
in_community = await source._community_helper.add_room(source._community_id, self.mxid)
await UserPortal(
user=source.fbid,
portal=self.fbid,
portal_receiver=self.fb_receiver,
in_community=in_community,
).insert()
elif not up.in_community:
up.in_community = await source._community_helper.add_room(
source._community_id, self.mxid
)
await up.save()
await self._sync_read_receipts(info.read_receipts.nodes)
async def _sync_read_receipts(self, receipts: list[graphql.ReadReceipt]) -> None:
for receipt in receipts:
message = await DBMessage.get_closest_before(
self.fbid, self.fb_receiver, receipt.timestamp
)
if not message:
continue
puppet = await p.Puppet.get_by_fbid(receipt.actor.id, create=False)
if not puppet:
continue
try:
await puppet.intent_for(self).mark_read(message.mx_room, message.mxid)
except Exception:
self.log.warning(
f"Failed to mark {message.mxid} in {message.mx_room} "
f"as read by {puppet.intent.mxid}",
exc_info=True,
)
async def create_matrix_room(
self, source: u.User, info: graphql.Thread | None = None
) -> RoomID | None:
if self.mxid:
try:
await self._update_matrix_room(source, info)
except Exception:
self.log.exception("Failed to update portal")
return self.mxid
async with self._create_room_lock:
try:
return await self._create_matrix_room(source, info)
except Exception:
self.log.exception("Failed to create portal")
return None
@property
def bridge_info_state_key(self) -> str:
return f"net.maunium.facebook://facebook/{self.fbid}"
@property
def bridge_info(self) -> dict[str, Any]:
return {
"bridgebot": self.az.bot_mxid,
"creator": self.main_intent.mxid,
"protocol": {
"id": "facebook",
"displayname": "Facebook Messenger",
"avatar_url": self.config["appservice.bot_avatar"],
},
"channel": {
"id": str(self.fbid),
"displayname": self.name,
"avatar_url": self.avatar_url,
},
}
async def update_bridge_info(self) -> None:
if not self.mxid:
self.log.debug("Not updating bridge info: no Matrix room created")
return
try:
self.log.debug("Updating bridge info...")
await self.main_intent.send_state_event(
self.mxid, StateBridge, self.bridge_info, self.bridge_info_state_key
)
# TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
await self.main_intent.send_state_event(
self.mxid, StateHalfShotBridge, self.bridge_info, self.bridge_info_state_key
)
except Exception:
self.log.warning("Failed to update bridge info", exc_info=True)
async def _create_matrix_room(
self, source: u.User, info: graphql.Thread | None = None
) -> RoomID | None:
if self.mxid:
await self._update_matrix_room(source, info)
return self.mxid
self.log.debug(f"Creating Matrix room")
name: str | None = None
initial_state = [
{
"type": str(StateBridge),
"state_key": self.bridge_info_state_key,
"content": self.bridge_info,
},
# TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
{
"type": str(StateHalfShotBridge),
"state_key": self.bridge_info_state_key,
"content": self.bridge_info,
},
]
invites = []
if self.config["bridge.encryption.default"] and self.matrix.e2ee:
self.encrypted = True
initial_state.append(
{
"type": "m.room.encryption",
"content": {"algorithm": "m.megolm.v1.aes-sha2"},
}
)
if self.is_direct:
invites.append(self.az.bot_mxid)
info = await self.update_info(source=source, info=info)
if not info:
self.log.debug("update_info() didn't return info, cancelling room creation")
return None
if self.encrypted or not self.is_direct:
name = self.name
initial_state.append(
{
"type": str(EventType.ROOM_AVATAR),
"content": {"url": self.avatar_url},
}
)
if self.config["appservice.community_id"]:
initial_state.append(
{
"type": "m.room.related_groups",
"content": {"groups": [self.config["appservice.community_id"]]},
}
)
# We lock backfill lock here so any messages that come between the room being created
# and the initial backfill finishing wouldn't be bridged before the backfill messages.
with self.backfill_lock:
creation_content = {}
if not self.config["bridge.federate_rooms"]:
creation_content["m.federate"] = False
self.mxid = await self.main_intent.create_room(
name=name,
is_direct=self.is_direct,
initial_state=initial_state,
invitees=invites,
creation_content=creation_content,
)
if not self.mxid:
raise Exception("Failed to create room: no mxid returned")
if self.encrypted and self.matrix.e2ee and self.is_direct:
try:
await self.az.intent.ensure_joined(self.mxid)
except Exception:
self.log.warning(f"Failed to add bridge bot to new private chat {self.mxid}")
await self.save()
self.log.debug(f"Matrix room created: {self.mxid}")
self.by_mxid[self.mxid] = self
puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
await self.main_intent.invite_user(
self.mxid, source.mxid, extra_content=self._get_invite_content(puppet)
)
if puppet:
try:
if self.is_direct:
await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
await puppet.intent.join_room_by_id(self.mxid)
except MatrixError:
self.log.debug(
"Failed to join custom puppet into newly created portal",
exc_info=True,
)
if not self.is_direct:
await self._update_participants(source, info)
in_community = await source._community_helper.add_room(source._community_id, self.mxid)
await UserPortal(
user=source.fbid,
portal=self.fbid,
portal_receiver=self.fb_receiver,
in_community=in_community,
).upsert()
try:
await self.backfill(source, is_initial=True, thread=info)
except Exception:
self.log.exception("Failed to backfill new portal")
await self._sync_read_receipts(info.read_receipts.nodes)
return self.mxid
# endregion
# region Matrix event handling
def require_send_lock(self, user_id: int) -> asyncio.Lock:
try:
lock = self._send_locks[user_id]
except KeyError:
lock = asyncio.Lock()
self._send_locks[user_id] = lock
return lock
def optional_send_lock(self, user_id: int) -> asyncio.Lock | FakeLock:
try:
return self._send_locks[user_id]
except KeyError:
pass
return self._noop_lock
async def _send_delivery_receipt(self, event_id: EventID) -> None:
if event_id and self.config["bridge.delivery_receipts"]:
try:
await self.az.intent.mark_read(self.mxid, event_id)
except Exception:
self.log.exception(f"Failed to send delivery receipt for {event_id}")
async def _send_bridge_error(self, msg: str) -> None:
await self._send_message(
self.main_intent,
TextMessageEventContent(
msgtype=MessageType.NOTICE,
body=f"\u26a0 Your message may not have been bridged: {msg}",
),
)
def _status_from_exception(self, e: Exception) -> MessageSendCheckpointStatus:
if isinstance(e, NotImplementedError):
return MessageSendCheckpointStatus.UNSUPPORTED
return MessageSendCheckpointStatus.PERM_FAILURE
async def handle_matrix_message(
self, sender: u.User, message: MessageEventContent, event_id: EventID
) -> None:
try:
await self._handle_matrix_message(sender, message, event_id)
except Exception as e:
self.log.exception(f"Failed to handle Matrix event {event_id}: {e}")
sender.send_remote_checkpoint(
self._status_from_exception(e),
event_id,
self.mxid,
EventType.ROOM_MESSAGE,
message.msgtype,
error=e,
)
await self._send_bridge_error(str(e))
else:
await self._send_delivery_receipt(event_id)
async def _handle_matrix_message(
self, orig_sender: u.User, message: MessageEventContent, event_id: EventID
) -> None:
if message.get_edit():
raise NotImplementedError("Edits are not supported by the Facebook bridge.")
sender, is_relay = await self.get_relay_sender(orig_sender, f"message {event_id}")
if not sender:
raise Exception("not logged in")
elif not sender.mqtt:
raise Exception("not connected to MQTT")
elif is_relay:
await self.apply_relay_message_format(orig_sender, message)
if message.msgtype == MessageType.TEXT or message.msgtype == MessageType.NOTICE:
await self._handle_matrix_text(event_id, sender, message)
elif message.msgtype.is_media:
await self._handle_matrix_media(event_id, sender, message, is_relay)
# elif message.msgtype == MessageType.LOCATION:
# await self._handle_matrix_location(sender, message)
else:
raise NotImplementedError(f"Unsupported message type {message.msgtype}")
async def _make_dbm(self, sender: u.User, event_id: EventID) -> DBMessage:
oti = sender.mqtt.generate_offline_threading_id()
dbm = DBMessage(
mxid=event_id,
mx_room=self.mxid,
fb_txn_id=oti,
index=0,
fb_chat=self.fbid,
fb_receiver=self.fb_receiver,
fb_sender=sender.fbid,
timestamp=int(time.time() * 1000),
fbid=None,
)
self._oti_dedup[oti] = dbm
await dbm.insert()
return dbm
async def _handle_matrix_text(
self, event_id: EventID, sender: u.User, message: TextMessageEventContent
) -> None:
converted = await matrix_to_facebook(message, self.mxid, self.log)
dbm = await self._make_dbm(sender, event_id)
resp = await sender.mqtt.send_message(
self.fbid,
self.fb_type != ThreadType.USER,
message=converted.text,
mentions=converted.mentions,
reply_to=converted.reply_to,
offline_threading_id=dbm.fb_txn_id,
)
if not resp.success and resp.error_message:
self.log.debug(f"Error handling Matrix message {event_id}: {resp.error_message}")
raise Exception(resp.error_message)
else:
self.log.debug(f"Handled Matrix message {event_id} -> OTI: {dbm.fb_txn_id}")
sender.send_remote_checkpoint(
MessageSendCheckpointStatus.SUCCESS,
event_id,
self.mxid,
EventType.ROOM_MESSAGE,
message.msgtype,
)
async def _handle_matrix_media(
self, event_id: EventID, sender: u.User, message: MediaMessageEventContent, is_relay: bool
) -> None:
if message.file and decrypt_attachment:
data = await self.main_intent.download_media(message.file.url)
data = decrypt_attachment(
data, message.file.key.key, message.file.hashes.get("sha256"), message.file.iv
)
elif message.url:
data = await self.main_intent.download_media(message.url)
else:
raise NotImplementedError("No file or URL specified")
mime = message.info.mimetype or magic.from_buffer(data, mime=True)
dbm = await self._make_dbm(sender, event_id)
reply_to = None
if message.relates_to.rel_type == RelationType.REPLY:
reply_to_msg = await DBMessage.get_by_mxid(message.relates_to.event_id, self.mxid)
if reply_to_msg:
reply_to = reply_to_msg.fbid
else:
self.log.warning(
f"Couldn't find reply target {message.relates_to.event_id}"
" to bridge media message reply metadata to Facebook"
)
filename = message.body
if is_relay:
caption = (await matrix_to_facebook(message, self.mxid, self.log)).text
else:
caption = None
if message.msgtype == MessageType.AUDIO:
if not mime.startswith("audio/mp"):
data = await ffmpeg.convert_bytes(
data,
output_extension=".m4a",
output_args=("-c:a", "aac"),
input_mime=mime,
)
mime = "audio/mpeg"
filename = "audio.m4a"
duration = message.info.duration
else:
duration = None
# await sender.mqtt.opened_thread(self.fbid)
resp = await sender.client.send_media(
data,
filename,
mime,
caption=caption,
offline_threading_id=dbm.fb_txn_id,
reply_to=reply_to,
chat_id=self.fbid,
is_group=self.fb_type != ThreadType.USER,
duration=duration,
)
if not resp.media_id and resp.debug_info:
self.log.debug(
f"Error uploading media for Matrix message {event_id}: {resp.debug_info.message}"
)
raise Exception(f"Media upload error: {resp.debug_info.message}")
else:
sender.send_remote_checkpoint(
MessageSendCheckpointStatus.SUCCESS,
event_id,
self.mxid,
EventType.ROOM_MESSAGE,
message.msgtype,
)
try:
self._oti_dedup.pop(dbm.fb_txn_id)
except KeyError:
self.log.trace(f"Message ID for OTI {dbm.fb_txn_id} seems to have been found already")
else:
dbm.fbid = resp.message_id
# TODO can we find the timestamp?
await dbm.update()
self.log.debug(f"Handled Matrix message {event_id} -> {resp.message_id} / {dbm.fb_txn_id}")
async def _handle_matrix_location(
self, sender: u.User, message: LocationMessageEventContent
) -> str:
pass
# TODO
# match = geo_uri_regex.fullmatch(message.geo_uri)
# return await self.thread_for(sender).send_pinned_location(float(match.group(1)),
# float(match.group(2)))
async def handle_matrix_redaction(
self, sender: u.User, event_id: EventID, redaction_event_id: EventID
) -> None:
try:
await self._handle_matrix_redaction(sender, event_id, redaction_event_id)
except Exception as e:
self.log.exception(f"Failed to handle Matrix event {event_id}: {e}")
sender.send_remote_checkpoint(
self._status_from_exception(e),
event_id,
self.mxid,
EventType.ROOM_REDACTION,
error=e,
)
await self._send_bridge_error(str(e))
else:
await self._send_delivery_receipt(event_id)
async def _handle_matrix_redaction(
self, sender: u.User, event_id: EventID, redaction_event_id: EventID
) -> None:
sender, _ = await self.get_relay_sender(sender, f"redaction {event_id}")
if not sender:
raise Exception("not logged in")
message = await DBMessage.get_by_mxid(event_id, self.mxid)
if message:
try:
await message.delete()
await sender.client.unsend(message.fbid)
except Exception as e:
self.log.exception(f"Unsend failed: {e}")
raise
else:
sender.send_remote_checkpoint(
MessageSendCheckpointStatus.SUCCESS,
redaction_event_id,
self.mxid,
EventType.ROOM_REDACTION,
)
await self._send_delivery_receipt(redaction_event_id)
return
reaction = await DBReaction.get_by_mxid(event_id, self.mxid)
if reaction:
try:
await reaction.delete()
await sender.client.react(reaction.fb_msgid, None)
except Exception as e:
self.log.exception(f"Removing reaction failed: {e}")
raise
else:
sender.send_remote_checkpoint(
MessageSendCheckpointStatus.SUCCESS,
redaction_event_id,
self.mxid,
EventType.ROOM_REDACTION,
)
await self._send_delivery_receipt(redaction_event_id)
return
raise NotImplementedError("Only message and reaction redactions are supported")
async def handle_matrix_reaction(
self, sender: u.User, event_id: EventID, reacting_to: EventID, reaction: str
) -> None:
sender, is_relay = await self.get_relay_sender(sender, f"reaction {event_id}")
if not sender or is_relay:
return
# Facebook doesn't use variation selectors, Matrix does
reaction = reaction.rstrip("\ufe0f")
async with self.require_send_lock(sender.fbid):
message = await DBMessage.get_by_mxid(reacting_to, self.mxid)
if not message:
self.log.debug(f"Ignoring reaction to unknown event {reacting_to}")
return
existing = await DBReaction.get_by_fbid(message.fbid, self.fb_receiver, sender.fbid)
if existing and existing.reaction == reaction:
sender.send_remote_checkpoint(
MessageSendCheckpointStatus.SUCCESS,
event_id,
self.mxid,
EventType.REACTION,
)
return
try:
await sender.client.react(message.fbid, reaction)
except Exception as e:
self.log.exception(f"Failed to react to {event_id}")
sender.send_remote_checkpoint(
MessageSendCheckpointStatus.PERM_FAILURE,
event_id,
self.mxid,
EventType.REACTION,
error=e,
)
else:
sender.send_remote_checkpoint(
MessageSendCheckpointStatus.SUCCESS,
event_id,
self.mxid,
EventType.REACTION,
)
await self._send_delivery_receipt(event_id)
await self._upsert_reaction(
existing, self.main_intent, event_id, message, sender, reaction
)
async def handle_matrix_leave(self, user: u.User) -> None:
if self.is_direct:
self.log.info(f"{user.mxid} left private chat portal with {self.fbid}")
if user.fbid == self.fb_receiver:
self.log.info(
f"{user.mxid} was the recipient of this portal. Cleaning up and deleting..."
)
await self.cleanup_and_delete()
else:
self.log.debug(f"{user.mxid} left portal to {self.fbid}")
async def _set_typing(self, users: set[UserID], typing: bool) -> None:
for mxid in users:
user: u.User = await u.User.get_by_mxid(mxid, create=False)
if user and user.mqtt:
await user.mqtt.set_typing(self.fbid, typing)
async def handle_matrix_typing(self, users: set[UserID]) -> None:
await asyncio.gather(
self._set_typing(users - self._typing, typing=True),
self._set_typing(self._typing - users, typing=False),
)
self._typing = users
async def enable_dm_encryption(self) -> bool:
ok = await super().enable_dm_encryption()
if ok: