This repository has been archived by the owner on Mar 2, 2024. It is now read-only.
/
portal.py
2833 lines (2590 loc) · 113 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-instagram - A Matrix-Instagram puppeting bridge.
# Copyright (C) 2023 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,
Callable,
Literal,
Optional,
Union,
cast,
)
from collections import deque
from io import BytesIO
from urllib.parse import urlparse
import asyncio
import base64
import hashlib
import html
import json
import mimetypes
import re
import sqlite3
import time
from aiohttp import ClientResponse, ClientSession
from yarl import URL
import asyncpg
import magic
from mauigpapi.errors import IGRateLimitError, IGResponseError
from mauigpapi.types import (
AnimatedMediaItem,
CommandResponse,
ExpiredMediaItem,
MediaShareItem,
MediaType,
MessageSyncMessage,
Reaction,
ReactionStatus,
ReelMediaShareItem,
ReelShareType,
RegularMediaItem,
Thread,
ThreadImage,
ThreadItem,
ThreadItemType,
ThreadUser,
ThreadUserLastSeenAt,
TypingStatus,
VoiceMediaItem,
XMAMediaShareItem,
)
from mautrix.appservice import DOUBLE_PUPPET_SOURCE_KEY, IntentAPI
from mautrix.bridge import BasePortal, async_getter_lock
from mautrix.errors import DecryptionError, MatrixError, MForbidden, MNotFound
from mautrix.types import (
AudioInfo,
BatchID,
BatchSendEvent,
BatchSendStateEvent,
BeeperMessageStatusEventContent,
ContentURI,
EventID,
EventType,
Format,
ImageInfo,
LocationMessageEventContent,
MediaMessageEventContent,
Membership,
MemberStateEventContent,
MessageEventContent,
MessageStatus,
MessageStatusReason,
MessageType,
ReactionEventContent,
RelatesTo,
RelationType,
RoomID,
TextMessageEventContent,
UserID,
VideoInfo,
)
from mautrix.util import background_task, ffmpeg
from mautrix.util.bridge_state import BridgeStateEvent
from mautrix.util.message_send_checkpoint import MessageSendCheckpointStatus
from . import formatter as fmt, matrix as m, puppet as p, user as u
from .config import Config
from .db import Backfill, Message as DBMessage, Portal as DBPortal, Reaction as DBReaction
if TYPE_CHECKING:
from .__main__ import InstagramBridge
try:
from mautrix.crypto.attachments import decrypt_attachment, encrypt_attachment
except ImportError:
encrypt_attachment = decrypt_attachment = None
try:
from PIL import Image
except ImportError:
Image = None
StateBridge = EventType.find("m.bridge", EventType.Class.STATE)
StateHalfShotBridge = EventType.find("uk.half-shot.bridge", EventType.Class.STATE)
MediaData = Union[
AnimatedMediaItem,
ExpiredMediaItem,
MediaShareItem,
ReelMediaShareItem,
RegularMediaItem,
VoiceMediaItem,
XMAMediaShareItem,
]
MediaUploadFunc = Callable[["u.User", MediaData, IntentAPI], Awaitable[MediaMessageEventContent]]
PortalCreateDummy = EventType.find("fi.mau.dummy.portal_created", EventType.Class.MESSAGE)
HistorySyncMarkerMessage = EventType.find("org.matrix.msc2716.marker", EventType.Class.MESSAGE)
ConvertedMessage = tuple[EventType, MessageEventContent]
# This doesn't need to capture all valid URLs, it's enough to catch most of them.
# False negatives simply mean the link won't be linkified on Instagram,
# but false positives will cause the message to fail to send.
SIMPLE_URL_REGEX = re.compile(
r"(?P<url>https?://[\da-z.-]+\.[a-z]{2,}(?:/[^\s]*)?)", flags=re.IGNORECASE
)
class UnsupportedAttachmentError(NotImplementedError):
pass
class Portal(DBPortal, BasePortal):
by_mxid: dict[RoomID, Portal] = {}
by_thread_id: dict[tuple[str, int], Portal] = {}
config: Config
matrix: m.MatrixHandler
private_chat_portal_meta: Literal["default", "always", "never"]
_main_intent: IntentAPI | None
_create_room_lock: asyncio.Lock
_msgid_dedup: deque[str]
_reqid_dedup: set[str]
_last_participant_update: set[int]
_reaction_lock: asyncio.Lock
_typing: set[UserID]
def __init__(
self,
thread_id: str,
receiver: int,
other_user_pk: int | None,
mxid: RoomID | None = None,
name: 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,
first_event_id: EventID | None = None,
next_batch_id: BatchID | None = None,
historical_base_insertion_event_id: EventID | None = None,
cursor: str | None = None,
thread_image_id: int | None = None,
) -> None:
super().__init__(
thread_id,
receiver,
other_user_pk,
mxid,
name,
avatar_url,
encrypted,
name_set,
avatar_set,
relay_user_id,
first_event_id,
next_batch_id,
historical_base_insertion_event_id,
cursor,
thread_image_id,
)
self._create_room_lock = asyncio.Lock()
self.log = self.log.getChild(thread_id)
self._msgid_dedup = deque(maxlen=100)
self._reqid_dedup = set()
self._last_participant_update = set()
self._main_intent = None
self._reaction_lock = asyncio.Lock()
self._typing = set()
self._relay_user = None
@property
def is_direct(self) -> bool:
return self.other_user_pk is not None
@property
def set_dm_room_metadata(self) -> bool:
return (
not self.is_direct
or self.private_chat_portal_meta == "always"
or (self.encrypted and self.private_chat_portal_meta != "never")
)
@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
@classmethod
def init_cls(cls, bridge: "InstagramBridge") -> None:
BasePortal.bridge = bridge
cls.config = bridge.config
cls.matrix = bridge.matrix
cls.az = bridge.az
cls.loop = bridge.loop
cls.bridge = bridge
cls.private_chat_portal_meta = cls.config["bridge.private_chat_portal_meta"]
# region Misc
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("Failed to send delivery receipt for %s", event_id)
async def _send_bridge_success(
self,
sender: u.User,
event_id: EventID,
event_type: EventType,
msgtype: MessageType | None = None,
) -> None:
sender.send_remote_checkpoint(
status=MessageSendCheckpointStatus.SUCCESS,
event_id=event_id,
room_id=self.mxid,
event_type=event_type,
message_type=msgtype,
)
background_task.create(self._send_message_status(event_id, err=None))
await self._send_delivery_receipt(event_id)
async def _send_bridge_error(
self,
sender: u.User,
err: Exception,
event_id: EventID,
event_type: EventType,
message_type: MessageType | None = None,
confirmed: bool = False,
) -> None:
sender.send_remote_checkpoint(
self._status_from_exception(err),
event_id,
self.mxid,
event_type,
message_type=message_type,
error=err,
)
if self.config["bridge.delivery_error_reports"]:
event_type_str = {
EventType.REACTION: "reaction",
EventType.ROOM_REDACTION: "redaction",
}.get(event_type, "message")
error_type = "was not" if confirmed else "may not have been"
await self._send_message(
self.main_intent,
TextMessageEventContent(
msgtype=MessageType.NOTICE,
body=f"\u26a0 Your {event_type_str} {error_type} bridged: {str(err)}",
),
)
background_task.create(self._send_message_status(event_id, err))
async def _send_message_status(self, event_id: EventID, err: Exception | None) -> None:
if not self.config["bridge.message_status_events"]:
return
intent = self.az.intent if self.encrypted else self.main_intent
status = BeeperMessageStatusEventContent(
network=self.bridge_info_state_key,
relates_to=RelatesTo(
rel_type=RelationType.REFERENCE,
event_id=event_id,
),
)
if err:
status.error = str(err)
if isinstance(err, NotImplementedError):
if isinstance(err, UnsupportedAttachmentError):
status.message = str(err)
status.reason = MessageStatusReason.UNSUPPORTED
status.status = MessageStatus.FAIL
else:
status.reason = MessageStatusReason.GENERIC_ERROR
status.status = MessageStatus.RETRIABLE
else:
status.status = MessageStatus.SUCCESS
await intent.send_message_event(
room_id=self.mxid,
event_type=EventType.BEEPER_MESSAGE_STATUS,
content=status,
)
async def _upsert_reaction(
self,
existing: DBReaction | None,
intent: IntentAPI,
mxid: EventID,
message: DBMessage,
sender: u.User | p.Puppet,
reaction: str,
mx_timestamp: int,
) -> None:
if existing:
self.log.debug(
f"_upsert_reaction redacting {existing.mxid} and inserting {mxid}"
f" (message: {message.mxid})"
)
await intent.redact(existing.mx_room, existing.mxid)
await existing.edit(
reaction=reaction, mxid=mxid, mx_room=message.mx_room, mx_timestamp=mx_timestamp
)
else:
self.log.debug(f"_upsert_reaction inserting {mxid} (message: {message.mxid})")
await DBReaction(
mxid=mxid,
mx_room=message.mx_room,
ig_item_id=message.item_id,
ig_receiver=self.receiver,
ig_sender=sender.igpk,
reaction=reaction,
mx_timestamp=mx_timestamp,
).insert()
# endregion
# region Matrix event handling
@staticmethod
def _status_from_exception(e: Exception) -> MessageSendCheckpointStatus:
if isinstance(e, NotImplementedError):
return MessageSendCheckpointStatus.UNSUPPORTED
elif isinstance(e, asyncio.TimeoutError):
return MessageSendCheckpointStatus.TIMEOUT
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"Error handling Matrix event {event_id}")
await self._send_bridge_error(
sender,
e,
event_id,
EventType.ROOM_MESSAGE,
message_type=message.msgtype,
confirmed=True,
)
else:
await self._send_bridge_success(
sender, event_id, EventType.ROOM_MESSAGE, message.msgtype
)
async def _handle_matrix_giphy(
self,
sender: u.User,
event_id: EventID,
request_id: str,
giphy_id: str,
) -> CommandResponse:
self.log.trace(f"Broadcasting giphy from {event_id} with request ID {request_id}")
return await sender.client.broadcast(
self.thread_id,
ThreadItemType.ANIMATED_MEDIA,
client_context=request_id,
id=giphy_id,
)
async def _handle_matrix_image(
self,
sender: u.User,
event_id: EventID,
request_id: str,
data: bytes,
mime_type: str,
width: int | None = None,
height: int | None = None,
) -> CommandResponse:
if mime_type != "image/jpeg":
if Image is None:
raise UnsupportedAttachmentError(
"Instagram does not allow non-JPEG images, and Pillow is not installed, "
"so the bridge couldn't convert the image automatically"
)
with BytesIO(data) as inp, BytesIO() as out:
img = Image.open(inp)
img.convert("RGB").save(out, format="JPEG", quality=80)
data = out.getvalue()
mime_type = "image/jpeg"
self.log.debug(f"Uploading photo from {event_id} (mime: {mime_type})")
upload_resp = await sender.client.upload(data, mimetype=mime_type)
self.log.debug(f"Broadcasting uploaded photo with request ID {request_id}")
retry_num = 0
max_retries = 4
while True:
try:
return await sender.client.broadcast(
self.thread_id,
ThreadItemType.PHOTO_ATTACHMENT,
client_context=request_id,
attachment_fbid=str(upload_resp.media_id),
allow_full_aspect_ratio="true",
ae_dual_send="false",
btt_dual_send="false",
)
except IGResponseError as e:
if e.response.status == 503 and retry_num < max_retries:
self.log.warning("Received 503 on image broadcast, retrying in 5 seconds")
sender.send_remote_checkpoint(
status=MessageSendCheckpointStatus.WILL_RETRY,
event_id=event_id,
room_id=self.mxid,
event_type=EventType.ROOM_MESSAGE,
message_type=MessageType.IMAGE,
error=e,
retry_num=retry_num,
)
await asyncio.sleep(5)
retry_num += 1
else:
raise e
async def _handle_matrix_video(
self,
sender: u.User,
event_id: EventID,
request_id: str,
data: bytes,
mime_type: str,
duration: int | None = None,
width: int | None = None,
height: int | None = None,
) -> CommandResponse:
if mime_type != "video/mp4":
self.log.debug(f"Converting video in {event_id} from {mime_type} to mp4")
data = await ffmpeg.convert_bytes(
data,
output_extension=".mp4",
output_args=(
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-c:a",
"aac",
"-movflags",
"+faststart",
),
input_mime=mime_type,
logger=self.log,
)
self.log.debug(f"Uploading video from {event_id}")
upload_resp = await sender.client.upload(data, mimetype="video/mp4")
self.log.debug(f"Broadcasting uploaded video with request ID {request_id}")
retry_num = 0
max_retries = 4
while True:
try:
return await sender.client.broadcast(
self.thread_id,
ThreadItemType.VIDEO_ATTACHMENT,
client_context=request_id,
attachment_fbid=str(upload_resp.media_id),
video_result=str(upload_resp.media_id),
ae_dual_send="false",
btt_dual_send="false",
)
except IGResponseError as e:
if e.response.status == 500 and retry_num < max_retries:
self.log.warning("Received 500 on video broadcast, retrying in 5 seconds")
sender.send_remote_checkpoint(
status=MessageSendCheckpointStatus.WILL_RETRY,
event_id=event_id,
room_id=self.mxid,
event_type=EventType.ROOM_MESSAGE,
message_type=MessageType.VIDEO,
error=e,
retry_num=retry_num,
)
await asyncio.sleep(5)
retry_num += 1
else:
raise e
async def _handle_matrix_audio(
self,
sender: u.User,
event_id: EventID,
request_id: str,
data: bytes,
mime_type: str,
waveform: list[int],
duration: int | None = None,
) -> CommandResponse:
if mime_type != "audio/mp4":
self.log.debug(f"Converting audio in {event_id} from {mime_type} to mp4")
data = await ffmpeg.convert_bytes(
data, output_extension=".m4a", output_args=("-c:a", "aac"), input_mime=mime_type
)
self.log.debug(f"Uploading audio from {event_id}")
upload_resp = await sender.client.upload(data, mimetype="audio/mp4")
self.log.debug(f"Broadcasting uploaded audio with request ID {request_id}")
return await sender.client.broadcast(
self.thread_id,
ThreadItemType.VOICE_ATTACHMENT,
client_context=request_id,
attachment_fbid=str(upload_resp.media_id),
# TODO upload_id?
ae_dual_send="false",
waveform=json.dumps([(part or 0) / 1024 for part in waveform], separators=(",", ":")),
waveform_sampling_frequency_hz="10",
)
async def _handle_matrix_message(
self, orig_sender: u.User, message: MessageEventContent, event_id: EventID
) -> None:
sender, is_relay = await self.get_relay_sender(orig_sender, f"message {event_id}")
assert sender, "user is not logged in"
if is_relay:
await self.apply_relay_message_format(orig_sender, message)
reply_to = {}
if message.get_reply_to():
msg = await DBMessage.get_by_mxid(message.get_reply_to(), self.mxid)
if msg and msg.client_context:
reply_to = {
"replied_to_item_id": msg.item_id,
"replied_to_client_context": msg.client_context,
}
request_id = sender.state.gen_client_context()
self._reqid_dedup.add(request_id)
self.log.debug(
f"Handling Matrix message {event_id} from {sender.mxid}/{sender.igpk} "
f"with request ID {request_id}"
)
if message.msgtype == MessageType.NOTICE and not self.config["bridge.bridge_notices"]:
self.log.debug(f"Dropping m.notice event {event_id}")
# TODO send checkpoint
return
if message.msgtype in (MessageType.EMOTE, MessageType.TEXT, MessageType.NOTICE):
if message.format == Format.HTML:
text, reply_to["mentioned_user_ids"] = await fmt.matrix_to_instagram(message)
else:
text = message.body
if message.msgtype == MessageType.EMOTE:
text = f"/me {text}"
self.log.trace(f"Sending Matrix text from {event_id} with request ID {request_id}")
urls = SIMPLE_URL_REGEX.findall(text) or None
if not self.is_direct:
# Instagram groups don't seem to support sending link previews,
# and the client_context-based deduplication breaks when trying to send them.
urls = None
resp = await sender.mqtt.send_text(
self.thread_id, text=text, urls=urls, client_context=request_id, **reply_to
)
elif message.msgtype.is_media and "fi.mau.instagram.giphy_id" in message:
resp = await self._handle_matrix_giphy(
sender, event_id, request_id, message["fi.mau.instagram.giphy_id"]
)
elif message.msgtype.is_media:
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
)
else:
data = await self.main_intent.download_media(message.url)
mime_type = message.info.mimetype or magic.from_buffer(data, mime=True)
if message.msgtype == MessageType.IMAGE:
resp = await self._handle_matrix_image(
sender,
event_id,
request_id,
data,
mime_type,
width=message.info.width,
height=message.info.height,
)
elif message.msgtype == MessageType.AUDIO:
waveform = message.get("org.matrix.msc1767.audio", {}).get("waveform", [0] * 30)
resp = await self._handle_matrix_audio(
sender,
event_id,
request_id,
data,
mime_type,
waveform,
duration=message.info.duration,
)
elif message.msgtype == MessageType.VIDEO:
resp = await self._handle_matrix_video(
sender,
event_id,
request_id,
data,
mime_type,
duration=message.info.duration,
width=message.info.width,
height=message.info.height,
)
else:
raise UnsupportedAttachmentError(
"Non-image/video/audio files are currently not supported"
)
else:
raise NotImplementedError(f"Unknown message type {message.msgtype}")
self.log.trace(f"Got response to message send {request_id}: {resp}")
if resp.status != "ok" or not resp.payload:
self.log.warning(f"Failed to handle {event_id}: {resp}")
if resp.exception == "ThreadUserIdDoesNotExist":
await orig_sender.message_fail_login_check()
raise Exception(f"Sending message failed: {resp.error_message}")
else:
self._msgid_dedup.appendleft(resp.payload.item_id)
try:
await DBMessage(
mxid=event_id,
mx_room=self.mxid,
item_id=resp.payload.item_id,
client_context=resp.payload.client_context,
receiver=self.receiver,
sender=sender.igpk,
ig_timestamp=int(resp.payload.timestamp),
).insert()
except (asyncpg.UniqueViolationError, sqlite3.IntegrityError) as e:
self.log.warning(
f"Error while persisting {event_id} ({resp.payload.client_context}) "
f"-> {resp.payload.item_id}: {e}"
)
self._reqid_dedup.remove(request_id)
self.log.debug(
f"Handled Matrix message {event_id} ({resp.payload.client_context}) "
f"-> {resp.payload.item_id}"
)
async def handle_matrix_reaction(
self, sender: u.User, event_id: EventID, reacting_to: EventID, emoji: str, timestamp: int
) -> None:
try:
await self._handle_matrix_reaction(sender, event_id, reacting_to, emoji, timestamp)
except Exception as e:
self.log.exception(f"Error handling Matrix reaction {event_id}")
await self._send_bridge_error(
sender,
e,
event_id,
EventType.REACTION,
confirmed=True,
)
else:
await self._send_bridge_success(sender, event_id, EventType.REACTION)
async def _handle_matrix_reaction(
self, sender: u.User, event_id: EventID, reacting_to: EventID, emoji: str, timestamp: int
) -> None:
if not await sender.is_logged_in():
self.log.debug(f"Ignoring reaction by non-logged-in user {sender.mxid}")
raise NotImplementedError("User is not logged in")
message = await DBMessage.get_by_mxid(reacting_to, self.mxid)
if not message or message.is_internal:
self.log.debug(f"Ignoring reaction to unknown event {reacting_to}")
await self.main_intent.redact(self.mxid, event_id, reason="Unknown target message")
raise NotImplementedError("Unknown target message")
existing = await DBReaction.get_by_item_id(message.item_id, message.receiver, sender.igpk)
if existing and existing.reaction == emoji:
return
async with self._reaction_lock:
resp = await sender.mqtt.send_reaction(
self.thread_id, item_id=message.item_id, emoji=emoji
)
if resp.status != "ok":
if resp.payload and resp.payload.message == "invalid unicode emoji":
# Instagram doesn't support this reaction. Notify the user, and redact it
# so that it doesn't get confusing.
await self.main_intent.redact(self.mxid, event_id, reason="Unsupported emoji")
raise NotImplementedError(f"Instagram does not support the {emoji} emoji.")
raise Exception(f"Unknown response error: {resp}")
self.log.trace(f"{sender.mxid} reacted to {message.item_id} with {emoji}")
await self._upsert_reaction(
existing, self.main_intent, event_id, message, sender, emoji, timestamp
)
async def handle_matrix_redaction(
self, orig_sender: u.User, event_id: EventID, redaction_event_id: EventID
) -> None:
sender = None
try:
sender, _ = await self.get_relay_sender(orig_sender, f"redaction {event_id}")
if not sender:
raise Exception("User is not logged in")
await self._handle_matrix_redaction(sender, event_id)
except Exception as e:
self.log.exception(f"Error handling Matrix redaction {event_id}")
await self._send_bridge_error(
sender or orig_sender,
e,
redaction_event_id,
EventType.ROOM_REDACTION,
confirmed=True,
)
else:
await self._send_bridge_success(sender, redaction_event_id, EventType.ROOM_REDACTION)
async def _handle_matrix_redaction(self, sender: u.User, event_id: EventID) -> None:
reaction = await DBReaction.get_by_mxid(event_id, self.mxid)
if reaction:
try:
await reaction.delete()
await sender.mqtt.send_reaction(
self.thread_id,
item_id=reaction.ig_item_id,
reaction_status=ReactionStatus.DELETED,
emoji="",
)
except Exception as e:
raise Exception(f"Removing reaction failed: {e}")
else:
self.log.trace(f"Removed reaction to {reaction.ig_item_id} after Matrix redaction")
return
message = await DBMessage.get_by_mxid(event_id, self.mxid)
if message and not message.is_internal:
try:
await message.delete()
await sender.client.delete_item(self.thread_id, message.item_id)
self.log.trace(f"Removed {message} after Matrix redaction")
except Exception as e:
raise Exception(f"Removing message failed: {e}")
else:
self.log.trace(f"Removed message {message.item_id} after Matrix redaction")
return
raise NotImplementedError("No message or reaction found for redaction")
async def handle_matrix_typing(self, users: set[UserID]) -> None:
if users == self._typing:
return
old_typing = self._typing
self._typing = users
await self._handle_matrix_typing(old_typing - users, TypingStatus.OFF)
await self._handle_matrix_typing(users - old_typing, TypingStatus.TEXT)
async def _handle_matrix_typing(self, users: set[UserID], status: TypingStatus) -> None:
if not self.config["bridge.bridge_matrix_typing"]:
return
for mxid in users:
user = await u.User.get_by_mxid(mxid, create=False)
if (
not user
or not await user.is_logged_in()
or user.remote_typing_status == status
or not user.is_connected
):
continue
user.remote_typing_status = None
await user.mqtt.indicate_activity(self.thread_id, status)
async def handle_matrix_leave(self, user: u.User) -> None:
if not await user.is_logged_in():
return
if self.is_direct:
self.log.info(f"{user.mxid} left private chat portal with {self.other_user_pk}")
if user.igpk == self.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.thread_id}")
# TODO cleanup if empty
# endregion
# region Instagram event handling
async def _reupload_instagram_media(
self, source: u.User, media: RegularMediaItem, intent: IntentAPI
) -> MediaMessageEventContent:
if media.media_type == MediaType.IMAGE:
image = media.best_image
if not image:
raise ValueError("Attachment not available: didn't find photo URL")
url = image.url
msgtype = MessageType.IMAGE
info = ImageInfo(height=image.height, width=image.width)
elif media.media_type == MediaType.VIDEO:
video = media.best_video
if not video:
raise ValueError("Attachment not available: didn't find video URL")
url = video.url
msgtype = MessageType.VIDEO
info = VideoInfo(height=video.height, width=video.width)
elif media.media_type == MediaType.CAROUSEL:
raise ValueError(
"Carousel media is not currently supported, "
"please view the post on Instagram via the link below"
)
else:
raise ValueError(
f"Attachment not available: unsupported media type {media.media_type.human_name}"
)
return await self._reupload_instagram_file(source, url, msgtype, info, intent)
async def _reupload_instagram_animated(
self, source: u.User, media: AnimatedMediaItem, intent: IntentAPI
) -> MediaMessageEventContent:
url = media.images.fixed_height.webp
info = ImageInfo(
height=int(media.images.fixed_height.height),
width=int(media.images.fixed_height.width),
)
return await self._reupload_instagram_file(source, url, MessageType.IMAGE, info, intent)
async def _reupload_instagram_xma(
self, source: u.User, media: XMAMediaShareItem, intent: IntentAPI
) -> MediaMessageEventContent:
if media.preview_url:
url = media.preview_url
info = ImageInfo(mimetype=media.preview_url_mime_type)
elif media.preview_url_info:
url = media.preview_url_info.url
info = ImageInfo(
height=media.preview_url_info.height,
width=media.preview_url_info.width,
)
else:
raise ValueError("XMA media has now preview URL")
reuploaded_image = await self._reupload_instagram_file(
source, url, MessageType.IMAGE, info, intent
)
reel_clip_id = media.reel_share_clip_id
if reel_clip_id:
try:
fetched_clip = await source.client.fetch_clip(reel_clip_id)
reuploaded_video = await self._reupload_instagram_media(
source, fetched_clip.media, intent
)
except Exception:
self.log.exception(f"Failed to fetch clip {reel_clip_id}, using fallback")
else:
reuploaded_video.info.thumbnail_file = reuploaded_image.file
reuploaded_video.info.thumbnail_url = reuploaded_image.url
reuploaded_video.info.thumbnail_info = reuploaded_image.info
return reuploaded_video
elif "/reel/" in media.target_url:
self.log.warning(f"No reel share clip ID found in {media.target_url}")
return reuploaded_image
async def _reupload_instagram_voice(
self, source: u.User, media: VoiceMediaItem, intent: IntentAPI
) -> MediaMessageEventContent:
async def convert_to_ogg(data, mimetype):
converted = await ffmpeg.convert_bytes(
data, ".ogg", output_args=("-c:a", "libopus"), input_mime=mimetype
)
return converted, "audio/ogg"
url = media.media.audio.audio_src
info = AudioInfo(duration=media.media.audio.duration)
waveform = [int(p * 1024) for p in media.media.audio.waveform_data]
content = await self._reupload_instagram_file(
source, url, MessageType.AUDIO, info, intent, convert_to_ogg
)
content["org.matrix.msc1767.audio"] = {
"duration": media.media.audio.duration,
"waveform": waveform,
}
content["org.matrix.msc3245.voice"] = {}
return content
async def _download_instagram_file(
self, source: u.User, url: str
) -> tuple[Optional[bytes], str]:
parsed_url = URL(url)
if "/" in parsed_url.query_string:
# Hacky hacks for forcing encoded slashes in query parameters. Normally yarl/aiohttp
# forces decoding slashes in query parameters, but that breaks Instagram's URL signature
# and the CDN rejects the request. (the reason there are slashes in the URL in the
# first place is presumably that Instagram hasn't heard of URL-safe base64).
urlparsed = urlparse(url)
parsed_url = parsed_url.with_query(None).with_path(
f"{urlparsed.path}?{urlparsed.query}", encoded=True
)
async def handle_resp(resp: ClientResponse) -> tuple[Optional[bytes], str]:
try:
length = int(resp.headers["Content-Length"])
except KeyError:
# TODO can the download be short-circuited if there's too much data?
self.log.warning(
"Got file download response with no Content-Length header,"
"reading data dangerously"
)
length = 0
if length > self.matrix.media_config.upload_size:
self.log.debug(
f"{parsed_url} was too large ({length} > {self.matrix.media_config.upload_size})"
)
raise ValueError("Attachment not available: too large")
self.log.debug(f"Downloading file with length {length}: {parsed_url}")
data = await resp.read()
if not data:
return None, ""
mimetype = resp.headers["Content-Type"] or magic.from_buffer(data, mime=True)
return data, mimetype
if self.config["bridge.use_proxy_for_media"]:
async with source.client.raw_http_get(parsed_url, raise_for_status=True) as resp:
return await handle_resp(resp)
else:
async with ClientSession() as session:
async with session.get(parsed_url, raise_for_status=True) as resp:
return await handle_resp(resp)
async def _reupload_instagram_file(
self,
source: u.User,
url: str,
msgtype: MessageType | None,
info: ImageInfo | VideoInfo | AudioInfo,
intent: IntentAPI,
convert_fn: Callable[[bytes, str], Awaitable[tuple[bytes, str]]] | None = None,
allow_encrypt: bool = True,
) -> MediaMessageEventContent:
data, mimetype = await self._download_instagram_file(source, url)
assert data is not None
info.mimetype = mimetype
# Run the conversion function on the data.
if convert_fn is not None:
data, info.mimetype = await convert_fn(data, info.mimetype)
if info.mimetype.startswith("image/") and not info.width and not info.height:
with BytesIO(data) as inp, Image.open(inp) as img:
info.width, info.height = img.size
info.size = len(data)
extension = {
"image/webp": ".webp",
"image/jpeg": ".jpg",
"video/mp4": ".mp4",
"audio/mp4": ".m4a",
"audio/ogg": ".ogg",
}.get(info.mimetype)
extension = extension or mimetypes.guess_extension(info.mimetype) or ""
file_name = f"{msgtype.value[2:]}{extension}" if msgtype else None
upload_mime_type = info.mimetype
upload_file_name = file_name
decryption_info = None
if allow_encrypt and self.encrypted and encrypt_attachment: