portal.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2021 Tulir Asokan
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from typing import (Dict, Tuple, Optional, List, Deque, Set, Any, Union, AsyncGenerator,
  17. Awaitable, NamedTuple, Callable, TYPE_CHECKING, cast)
  18. from collections import deque
  19. from io import BytesIO
  20. import mimetypes
  21. import asyncio
  22. import asyncpg
  23. import magic
  24. from mautrix.util.message_send_checkpoint import MessageSendCheckpointStatus
  25. from mauigpapi.types import (Thread, ThreadUser, ThreadItem, RegularMediaItem, MediaType,
  26. ReactionStatus, Reaction, AnimatedMediaItem, ThreadItemType,
  27. VoiceMediaItem, ExpiredMediaItem, MessageSyncMessage, ReelShareType,
  28. TypingStatus, ThreadUserLastSeenAt, MediaShareItem)
  29. from mautrix.appservice import AppService, IntentAPI
  30. from mautrix.bridge import BasePortal, NotificationDisabler, async_getter_lock
  31. from mautrix.types import (EventID, MessageEventContent, RoomID, EventType, MessageType, ImageInfo,
  32. VideoInfo, MediaMessageEventContent, TextMessageEventContent, AudioInfo,
  33. ContentURI, EncryptedFile, LocationMessageEventContent, Format, UserID)
  34. from mautrix.errors import MatrixError, MForbidden, MNotFound, SessionNotFound
  35. from mautrix.util.simple_lock import SimpleLock
  36. from .db import Portal as DBPortal, Message as DBMessage, Reaction as DBReaction
  37. from .config import Config
  38. from . import user as u, puppet as p, matrix as m
  39. if TYPE_CHECKING:
  40. from .__main__ import InstagramBridge
  41. try:
  42. from mautrix.crypto.attachments import encrypt_attachment, decrypt_attachment
  43. except ImportError:
  44. encrypt_attachment = decrypt_attachment = None
  45. try:
  46. from PIL import Image
  47. except ImportError:
  48. Image = None
  49. StateBridge = EventType.find("m.bridge", EventType.Class.STATE)
  50. StateHalfShotBridge = EventType.find("uk.half-shot.bridge", EventType.Class.STATE)
  51. FileInfo = Union[AudioInfo, ImageInfo, VideoInfo]
  52. ReuploadedMediaInfo = NamedTuple('ReuploadedMediaInfo', mxc=Optional[ContentURI], url=str,
  53. decryption_info=Optional[EncryptedFile], msgtype=MessageType,
  54. file_name=str, info=FileInfo)
  55. MediaData = Union[RegularMediaItem, ExpiredMediaItem]
  56. MediaUploadFunc = Callable[['u.User', MediaData, IntentAPI], Awaitable[ReuploadedMediaInfo]]
  57. class Portal(DBPortal, BasePortal):
  58. by_mxid: Dict[RoomID, 'Portal'] = {}
  59. by_thread_id: Dict[Tuple[str, int], 'Portal'] = {}
  60. config: Config
  61. matrix: 'm.MatrixHandler'
  62. az: AppService
  63. private_chat_portal_meta: bool
  64. _main_intent: Optional[IntentAPI]
  65. _create_room_lock: asyncio.Lock
  66. backfill_lock: SimpleLock
  67. _msgid_dedup: Deque[str]
  68. _reqid_dedup: Set[str]
  69. _reaction_dedup: Deque[Tuple[str, int, str]]
  70. _main_intent: IntentAPI
  71. _last_participant_update: Set[int]
  72. _reaction_lock: asyncio.Lock
  73. _backfill_leave: Optional[Set[IntentAPI]]
  74. _typing: Set[UserID]
  75. def __init__(self, thread_id: str, receiver: int, other_user_pk: Optional[int],
  76. mxid: Optional[RoomID] = None, name: Optional[str] = None,
  77. avatar_url: Optional[ContentURI] = None, encrypted: bool = False,
  78. name_set: bool = False, avatar_set: bool = False,
  79. relay_user_id: Optional[UserID] = None) -> None:
  80. super().__init__(thread_id, receiver, other_user_pk, mxid, name, avatar_url, encrypted,
  81. name_set, avatar_set, relay_user_id)
  82. self._create_room_lock = asyncio.Lock()
  83. self.log = self.log.getChild(thread_id)
  84. self._msgid_dedup = deque(maxlen=100)
  85. self._reaction_dedup = deque(maxlen=100)
  86. self._reqid_dedup = set()
  87. self._last_participant_update = set()
  88. self.backfill_lock = SimpleLock("Waiting for backfilling to finish before handling %s",
  89. log=self.log)
  90. self._backfill_leave = None
  91. self._main_intent = None
  92. self._reaction_lock = asyncio.Lock()
  93. self._typing = set()
  94. self._relay_user = None
  95. @property
  96. def is_direct(self) -> bool:
  97. return self.other_user_pk is not None
  98. @property
  99. def main_intent(self) -> IntentAPI:
  100. if not self._main_intent:
  101. raise ValueError("Portal must be postinit()ed before main_intent can be used")
  102. return self._main_intent
  103. @classmethod
  104. def init_cls(cls, bridge: 'InstagramBridge') -> None:
  105. cls.config = bridge.config
  106. cls.matrix = bridge.matrix
  107. cls.az = bridge.az
  108. cls.loop = bridge.loop
  109. cls.bridge = bridge
  110. cls.private_chat_portal_meta = cls.config["bridge.private_chat_portal_meta"]
  111. NotificationDisabler.puppet_cls = p.Puppet
  112. NotificationDisabler.config_enabled = cls.config["bridge.backfill.disable_notifications"]
  113. # region Misc
  114. async def _send_delivery_receipt(self, event_id: EventID) -> None:
  115. if event_id and self.config["bridge.delivery_receipts"]:
  116. try:
  117. await self.az.intent.mark_read(self.mxid, event_id)
  118. except Exception:
  119. self.log.exception("Failed to send delivery receipt for %s", event_id)
  120. async def _send_bridge_error(self, sender: 'u.User', err: Union[Exception, str],
  121. event_id: EventID, event_type: EventType,
  122. message_type: Optional[MessageType] = None,
  123. msg: Optional[str] = None, confirmed: bool = False,
  124. status: MessageSendCheckpointStatus = MessageSendCheckpointStatus.PERM_FAILURE,
  125. ) -> None:
  126. sender.send_remote_checkpoint(
  127. status,
  128. event_id,
  129. self.mxid,
  130. event_type,
  131. message_type=message_type,
  132. error=err,
  133. )
  134. if self.config["bridge.delivery_error_reports"]:
  135. event_type_str = {
  136. EventType.REACTION: "reaction",
  137. EventType.ROOM_REDACTION: "redaction",
  138. }.get(event_type, "message")
  139. error_type = "was not" if confirmed else "may not have been"
  140. await self._send_message(self.main_intent, TextMessageEventContent(
  141. msgtype=MessageType.NOTICE,
  142. body=f"\u26a0 Your {event_type_str} {error_type} bridged: {msg or str(err)}"))
  143. async def _upsert_reaction(self, existing: Optional[DBReaction], intent: IntentAPI,
  144. mxid: EventID, message: DBMessage,
  145. sender: Union['u.User', 'p.Puppet'], reaction: str) -> None:
  146. if existing:
  147. self.log.debug(f"_upsert_reaction redacting {existing.mxid} and inserting {mxid}"
  148. f" (message: {message.mxid})")
  149. await intent.redact(existing.mx_room, existing.mxid)
  150. await existing.edit(reaction=reaction, mxid=mxid, mx_room=message.mx_room)
  151. else:
  152. self.log.debug(f"_upsert_reaction inserting {mxid} (message: {message.mxid})")
  153. await DBReaction(mxid=mxid, mx_room=message.mx_room, ig_item_id=message.item_id,
  154. ig_receiver=self.receiver, ig_sender=sender.igpk, reaction=reaction
  155. ).insert()
  156. # endregion
  157. # region Matrix event handling
  158. def _status_from_exception(self, e: Exception) -> MessageSendCheckpointStatus:
  159. if isinstance(e, NotImplementedError):
  160. return MessageSendCheckpointStatus.UNSUPPORTED
  161. return MessageSendCheckpointStatus.PERM_FAILURE
  162. async def handle_matrix_message(self, sender: 'u.User', message: MessageEventContent,
  163. event_id: EventID) -> None:
  164. try:
  165. await self._handle_matrix_message(sender, message, event_id)
  166. except Exception as e:
  167. self.log.exception(f"Fatal error handling Matrix event {event_id}: {e}")
  168. await self._send_bridge_error(
  169. sender,
  170. e,
  171. event_id,
  172. EventType.ROOM_MESSAGE,
  173. message_type=message.msgtype,
  174. status=self._status_from_exception(e),
  175. confirmed=True,
  176. )
  177. async def _handle_matrix_message(self, orig_sender: 'u.User', message: MessageEventContent,
  178. event_id: EventID) -> None:
  179. sender, is_relay = await self.get_relay_sender(orig_sender, f"message {event_id}")
  180. assert sender, "user is not logged in"
  181. assert sender.is_connected, "You're not connected to Instagram"
  182. if is_relay:
  183. await self.apply_relay_message_format(orig_sender, message)
  184. request_id = sender.state.gen_client_context()
  185. self._reqid_dedup.add(request_id)
  186. self.log.debug(f"Handling Matrix message {event_id} from {sender.mxid}/{sender.igpk} "
  187. f"with request ID {request_id}")
  188. if message.msgtype in (MessageType.EMOTE, MessageType.TEXT):
  189. text = message.body
  190. if message.msgtype == MessageType.EMOTE:
  191. text = f"/me {text}"
  192. self.log.trace(f"Sending Matrix text from {event_id} with request ID {request_id}")
  193. resp = await sender.mqtt.send_text(self.thread_id, text=text,
  194. client_context=request_id)
  195. elif message.msgtype.is_media:
  196. if message.file and decrypt_attachment:
  197. data = await self.main_intent.download_media(message.file.url)
  198. data = decrypt_attachment(data, message.file.key.key,
  199. message.file.hashes.get("sha256"), message.file.iv)
  200. else:
  201. data = await self.main_intent.download_media(message.url)
  202. mime_type = message.info.mimetype or magic.from_buffer(data, mime=True)
  203. if mime_type != "image/jpeg" and mime_type.startswith("image/"):
  204. with BytesIO(data) as inp:
  205. img = Image.open(inp)
  206. with BytesIO() as out:
  207. img.convert("RGB").save(out, format="JPEG", quality=80)
  208. data = out.getvalue()
  209. mime_type = "image/jpeg"
  210. if mime_type == "image/jpeg":
  211. self.log.trace(f"Uploading photo from {event_id}")
  212. upload_resp = await sender.client.upload_jpeg_photo(data)
  213. self.log.trace(f"Broadcasting uploaded photo with request ID {request_id}")
  214. # TODO is it possible to do this with MQTT?
  215. resp = await sender.client.broadcast(self.thread_id,
  216. ThreadItemType.CONFIGURE_PHOTO,
  217. client_context=request_id,
  218. upload_id=upload_resp.upload_id,
  219. allow_full_aspect_ratio="1")
  220. else:
  221. raise NotImplementedError("Non-image files are currently not supported")
  222. else:
  223. raise NotImplementedError(f"Unknown message type {message.msgtype}")
  224. self.log.trace(f"Got response to message send {request_id}: {resp}")
  225. if resp.status != "ok":
  226. self.log.warning(f"Failed to handle {event_id}: {resp}")
  227. raise Exception(f"Failed to handle event. Error: {resp.payload.message}")
  228. else:
  229. sender.send_remote_checkpoint(
  230. status=MessageSendCheckpointStatus.SUCCESS,
  231. event_id=event_id,
  232. room_id=self.mxid,
  233. event_type=EventType.ROOM_MESSAGE,
  234. message_type=message.msgtype,
  235. )
  236. await self._send_delivery_receipt(event_id)
  237. self._msgid_dedup.appendleft(resp.payload.item_id)
  238. try:
  239. await DBMessage(mxid=event_id, mx_room=self.mxid, item_id=resp.payload.item_id,
  240. receiver=self.receiver, sender=sender.igpk).insert()
  241. except asyncpg.UniqueViolationError as e:
  242. self.log.warning(f"Error while persisting {event_id} "
  243. f"({resp.payload.client_context}) -> {resp.payload.item_id}: {e}")
  244. self._reqid_dedup.remove(request_id)
  245. self.log.debug(f"Handled Matrix message {event_id} ({resp.payload.client_context}) "
  246. f"-> {resp.payload.item_id}")
  247. async def handle_matrix_reaction(self, sender: 'u.User', event_id: EventID,
  248. reacting_to: EventID, emoji: str) -> None:
  249. try:
  250. await self._handle_matrix_reaction(sender, event_id, reacting_to, emoji)
  251. except Exception as e:
  252. self.log.exception(f"Fatal error handling Matrix event {event_id}: {e}")
  253. await self._send_bridge_error(
  254. sender,
  255. e,
  256. event_id,
  257. EventType.REACTION,
  258. status=self._status_from_exception(e),
  259. confirmed=True,
  260. msg="Fatal error handling reaction (see logs for more details)",
  261. )
  262. async def _handle_matrix_reaction(self, sender: 'u.User', event_id: EventID,
  263. reacting_to: EventID, emoji: str) -> None:
  264. message = await DBMessage.get_by_mxid(reacting_to, self.mxid)
  265. if not message or message.is_internal:
  266. self.log.debug(f"Ignoring reaction to unknown event {reacting_to}")
  267. return
  268. if not await sender.is_logged_in():
  269. self.log.debug(f"Ignoring reaction by non-logged-in user {sender.mxid}")
  270. return
  271. existing = await DBReaction.get_by_item_id(message.item_id, message.receiver, sender.igpk)
  272. if existing and existing.reaction == emoji:
  273. sender.send_remote_checkpoint(
  274. status=MessageSendCheckpointStatus.SUCCESS,
  275. event_id=event_id,
  276. room_id=self.mxid,
  277. event_type=EventType.REACTION,
  278. )
  279. return
  280. dedup_id = (message.item_id, sender.igpk, emoji)
  281. self._reaction_dedup.appendleft(dedup_id)
  282. async with self._reaction_lock:
  283. try:
  284. resp = await sender.mqtt.send_reaction(self.thread_id, item_id=message.item_id,
  285. emoji=emoji)
  286. if resp.status != "ok":
  287. raise Exception(f"Failed to react to {event_id}: {resp}")
  288. except Exception as e:
  289. self.log.exception(f"Failed to handle {event_id}: {e}")
  290. raise
  291. else:
  292. sender.send_remote_checkpoint(
  293. status=MessageSendCheckpointStatus.SUCCESS,
  294. event_id=event_id,
  295. room_id=self.mxid,
  296. event_type=EventType.REACTION,
  297. )
  298. await self._send_delivery_receipt(event_id)
  299. self.log.trace(f"{sender.mxid} reacted to {message.item_id} with {emoji}")
  300. await self._upsert_reaction(existing, self.main_intent, event_id, message, sender,
  301. emoji)
  302. async def handle_matrix_redaction(self, orig_sender: 'u.User', event_id: EventID,
  303. redaction_event_id: EventID) -> None:
  304. sender = None
  305. try:
  306. sender, _ = await self.get_relay_sender(orig_sender, f"redaction {event_id}")
  307. if not sender:
  308. raise Exception("User is not logged in")
  309. await self._handle_matrix_redaction(sender, event_id, redaction_event_id)
  310. except Exception as e:
  311. self.log.exception(f"Fatal error handling Matrix event {event_id}: {e}")
  312. await self._send_bridge_error(
  313. sender or orig_sender,
  314. e,
  315. redaction_event_id,
  316. EventType.ROOM_REDACTION,
  317. status=self._status_from_exception(e),
  318. confirmed=True,
  319. )
  320. async def _handle_matrix_redaction(self, sender: 'u.User', event_id: EventID,
  321. redaction_event_id: EventID) -> None:
  322. if not sender.is_connected:
  323. raise Exception("You're not connected to Instagram")
  324. reaction = await DBReaction.get_by_mxid(event_id, self.mxid)
  325. if reaction:
  326. try:
  327. await reaction.delete()
  328. await sender.mqtt.send_reaction(self.thread_id, item_id=reaction.ig_item_id,
  329. reaction_status=ReactionStatus.DELETED, emoji="")
  330. except Exception as e:
  331. raise Exception(f"Removing reaction failed: {e}")
  332. else:
  333. sender.send_remote_checkpoint(
  334. status=MessageSendCheckpointStatus.SUCCESS,
  335. event_id=redaction_event_id,
  336. room_id=self.mxid,
  337. event_type=EventType.ROOM_REDACTION,
  338. )
  339. await self._send_delivery_receipt(redaction_event_id)
  340. self.log.trace(f"Removed {reaction} after Matrix redaction")
  341. return
  342. message = await DBMessage.get_by_mxid(event_id, self.mxid)
  343. if message and not message.is_internal:
  344. try:
  345. await message.delete()
  346. await sender.client.delete_item(self.thread_id, message.item_id)
  347. self.log.trace(f"Removed {message} after Matrix redaction")
  348. except Exception as e:
  349. raise Exception(f"Removing message failed: {e}")
  350. else:
  351. sender.send_remote_checkpoint(
  352. status=MessageSendCheckpointStatus.SUCCESS,
  353. event_id=redaction_event_id,
  354. room_id=self.mxid,
  355. event_type=EventType.ROOM_REDACTION,
  356. )
  357. await self._send_delivery_receipt(redaction_event_id)
  358. self.log.trace(f"Removed {reaction} after Matrix redaction")
  359. return
  360. raise Exception("No message or reaction found for redaction")
  361. async def handle_matrix_typing(self, users: Set[UserID]) -> None:
  362. if users == self._typing:
  363. return
  364. old_typing = self._typing
  365. self._typing = users
  366. await self._handle_matrix_typing(old_typing - users, TypingStatus.OFF)
  367. await self._handle_matrix_typing(users - old_typing, TypingStatus.TEXT)
  368. async def _handle_matrix_typing(self, users: Set[UserID], status: TypingStatus) -> None:
  369. for mxid in users:
  370. user = await u.User.get_by_mxid(mxid, create=False)
  371. if ((not user or not await user.is_logged_in() or user.remote_typing_status == status
  372. or not user.is_connected)):
  373. continue
  374. user.remote_typing_status = None
  375. await user.mqtt.indicate_activity(self.thread_id, status)
  376. async def handle_matrix_leave(self, user: 'u.User') -> None:
  377. if not await user.is_logged_in():
  378. return
  379. if self.is_direct:
  380. self.log.info(f"{user.mxid} left private chat portal with {self.other_user_pk}")
  381. if user.igpk == self.receiver:
  382. self.log.info(f"{user.mxid} was the recipient of this portal. "
  383. "Cleaning up and deleting...")
  384. await self.cleanup_and_delete()
  385. else:
  386. self.log.debug(f"{user.mxid} left portal to {self.thread_id}")
  387. # TODO cleanup if empty
  388. # endregion
  389. # region Instagram event handling
  390. async def _reupload_instagram_media(self, source: 'u.User', media: RegularMediaItem,
  391. intent: IntentAPI) -> ReuploadedMediaInfo:
  392. if media.media_type == MediaType.IMAGE:
  393. image = media.best_image
  394. if not image:
  395. raise ValueError("Attachment not available: didn't find photo URL")
  396. url = image.url
  397. msgtype = MessageType.IMAGE
  398. info = ImageInfo(height=image.height, width=image.width)
  399. elif media.media_type == MediaType.VIDEO:
  400. video = media.best_video
  401. if not video:
  402. raise ValueError("Attachment not available: didn't find video URL")
  403. url = video.url
  404. msgtype = MessageType.VIDEO
  405. info = VideoInfo(height=video.height, width=video.width)
  406. else:
  407. raise ValueError("Attachment not available: unsupported media type")
  408. return await self._reupload_instagram_file(source, url, msgtype, info, intent)
  409. async def _reupload_instagram_animated(self, source: 'u.User', media: AnimatedMediaItem,
  410. intent: IntentAPI) -> ReuploadedMediaInfo:
  411. url = media.images.fixed_height.webp
  412. info = ImageInfo(height=int(media.images.fixed_height.height),
  413. width=int(media.images.fixed_height.width))
  414. return await self._reupload_instagram_file(source, url, MessageType.IMAGE, info, intent)
  415. async def _reupload_instagram_voice(self, source: 'u.User', media: VoiceMediaItem,
  416. intent: IntentAPI) -> ReuploadedMediaInfo:
  417. url = media.media.audio.audio_src
  418. info = AudioInfo(duration=media.media.audio.duration)
  419. return await self._reupload_instagram_file(source, url, MessageType.AUDIO, info, intent)
  420. async def _reupload_instagram_file(self, source: 'u.User', url: str, msgtype: MessageType,
  421. info: FileInfo, intent: IntentAPI
  422. ) -> ReuploadedMediaInfo:
  423. async with await source.client.raw_http_get(url) as resp:
  424. try:
  425. length = int(resp.headers["Content-Length"])
  426. except KeyError:
  427. # TODO can the download be short-circuited if there's too much data?
  428. self.log.warning("Got file download response with no Content-Length header,"
  429. "reading data dangerously")
  430. length = 0
  431. if length > self.matrix.media_config.upload_size:
  432. self.log.debug(f"{url} was too large ({length} "
  433. f"> {self.matrix.media_config.upload_size})")
  434. raise ValueError("Attachment not available: too large")
  435. data = await resp.read()
  436. info.mimetype = resp.headers["Content-Type"] or magic.from_buffer(data, mime=True)
  437. info.size = len(data)
  438. extension = {
  439. "image/webp": ".webp",
  440. "image/jpeg": ".jpg",
  441. "video/mp4": ".mp4",
  442. "audio/mp4": ".m4a",
  443. }.get(info.mimetype)
  444. extension = extension or mimetypes.guess_extension(info.mimetype) or ""
  445. file_name = f"{msgtype.value[2:]}{extension}"
  446. upload_mime_type = info.mimetype
  447. upload_file_name = file_name
  448. decryption_info = None
  449. if self.encrypted and encrypt_attachment:
  450. data, decryption_info = encrypt_attachment(data)
  451. upload_mime_type = "application/octet-stream"
  452. upload_file_name = None
  453. mxc = await intent.upload_media(data, mime_type=upload_mime_type,
  454. filename=upload_file_name)
  455. if decryption_info:
  456. decryption_info.url = mxc
  457. mxc = None
  458. return ReuploadedMediaInfo(mxc=mxc, url=url, decryption_info=decryption_info,
  459. file_name=file_name, msgtype=msgtype, info=info)
  460. def _get_instagram_media_info(self, item: ThreadItem) -> Tuple[MediaUploadFunc, MediaData]:
  461. # TODO maybe use a dict and item.item_type instead of a ton of ifs
  462. method = self._reupload_instagram_media
  463. if item.media:
  464. media_data = item.media
  465. elif item.visual_media:
  466. media_data = item.visual_media.media
  467. elif item.animated_media:
  468. media_data = item.animated_media
  469. method = self._reupload_instagram_animated
  470. elif item.voice_media:
  471. media_data = item.voice_media
  472. method = self._reupload_instagram_voice
  473. elif item.reel_share:
  474. media_data = item.reel_share.media
  475. elif item.story_share:
  476. media_data = item.story_share.media
  477. elif item.media_share:
  478. media_data = item.media_share
  479. else:
  480. self.log.debug(f"Unknown media type in {item}")
  481. raise ValueError("Attachment not available: unsupported media type")
  482. if not media_data:
  483. self.log.debug(f"Didn't get media_data in {item}")
  484. raise ValueError("Attachment not available: unsupported media type")
  485. elif isinstance(media_data, ExpiredMediaItem):
  486. self.log.debug(f"Expired media in item {item}")
  487. raise ValueError("Attachment not available: media expired")
  488. return method, media_data
  489. async def _handle_instagram_media(self, source: 'u.User', intent: IntentAPI, item: ThreadItem
  490. ) -> Optional[EventID]:
  491. try:
  492. reupload_func, media_data = self._get_instagram_media_info(item)
  493. reuploaded = await reupload_func(source, media_data, intent)
  494. except ValueError as e:
  495. content = TextMessageEventContent(body=str(e), msgtype=MessageType.NOTICE)
  496. except Exception:
  497. self.log.warning("Failed to upload media", exc_info=True)
  498. content = TextMessageEventContent(body="Attachment not available: failed to copy file",
  499. msgtype=MessageType.NOTICE)
  500. else:
  501. content = MediaMessageEventContent(
  502. body=reuploaded.file_name, external_url=reuploaded.url, url=reuploaded.mxc,
  503. file=reuploaded.decryption_info, info=reuploaded.info, msgtype=reuploaded.msgtype)
  504. await self._add_instagram_reply(content, item.replied_to_message)
  505. return await self._send_message(intent, content, timestamp=item.timestamp // 1000)
  506. async def _handle_instagram_media_share(self, source: 'u.User', intent: IntentAPI,
  507. item: ThreadItem) -> Optional[EventID]:
  508. share_item = item.media_share or item.story_share.media
  509. user_text = f"@{share_item.user.username}"
  510. user_link = (f'<a href="https://www.instagram.com/{share_item.user.username}/">'
  511. f'{user_text}</a>')
  512. item_type_name = item.media_share.media_type.human_name if item.media_share else "story"
  513. prefix = TextMessageEventContent(msgtype=MessageType.NOTICE, format=Format.HTML,
  514. body=f"Sent {user_text}'s {item_type_name}",
  515. formatted_body=f"Sent {user_link}'s {item_type_name}")
  516. await self._send_message(intent, prefix, timestamp=item.timestamp // 1000)
  517. event_id = await self._handle_instagram_media(source, intent, item)
  518. if share_item.caption:
  519. external_url = f"https://www.instagram.com/p/{share_item.code}/"
  520. body = (f"> {share_item.caption.user.username}: {share_item.caption.text}\n\n"
  521. f"{external_url}")
  522. formatted_body = (f"<blockquote><strong>{share_item.caption.user.username}</strong>"
  523. f" {share_item.caption.text}</blockquote>"
  524. f'<a href="{external_url}">instagram.com/p/{share_item.code}</a>')
  525. caption = TextMessageEventContent(msgtype=MessageType.TEXT, body=body,
  526. formatted_body=formatted_body, format=Format.HTML,
  527. external_url=external_url)
  528. await self._send_message(intent, caption, timestamp=item.timestamp // 1000)
  529. return event_id
  530. async def _handle_instagram_reel_share(self, source: 'u.User', intent: IntentAPI,
  531. item: ThreadItem) -> Optional[EventID]:
  532. media = item.reel_share.media
  533. prefix_html = None
  534. if item.reel_share.type == ReelShareType.REPLY:
  535. if item.reel_share.reel_owner_id == source.igpk:
  536. prefix = "Replied to your story"
  537. else:
  538. username = media.user.username
  539. prefix = f"Sent @{username}'s story"
  540. user_link = f'<a href="https://www.instagram.com/{username}/">@{username}</a>'
  541. prefix_html = f"Sent {user_link}'s story"
  542. elif item.reel_share.type == ReelShareType.REACTION:
  543. prefix = "Reacted to your story"
  544. elif item.reel_share.type == ReelShareType.MENTION:
  545. if item.reel_share.mentioned_user_id == source.igpk:
  546. prefix = "Mentioned you in their story"
  547. else:
  548. prefix = "You mentioned them in your story"
  549. else:
  550. self.log.debug(f"Unsupported reel share type {item.reel_share.type}")
  551. return None
  552. prefix_content = TextMessageEventContent(msgtype=MessageType.NOTICE, body=prefix)
  553. if prefix_html:
  554. prefix_content.format = Format.HTML
  555. prefix_content.formatted_body = prefix_html
  556. content = TextMessageEventContent(msgtype=MessageType.TEXT, body=item.reel_share.text)
  557. if not content.body and isinstance(media, MediaShareItem):
  558. content.body = media.caption.text if media.caption else ""
  559. if not content.body:
  560. content.body = "<no caption>"
  561. await self._send_message(intent, prefix_content, timestamp=item.timestamp // 1000)
  562. if isinstance(media, ExpiredMediaItem):
  563. # TODO send message about expired story
  564. pass
  565. else:
  566. fake_item_id = f"fi.mau.instagram.reel_share.{item.user_id}.{media.pk}"
  567. existing = await DBMessage.get_by_item_id(fake_item_id, self.receiver)
  568. if existing:
  569. # If the user already reacted or replied to the same reel share item,
  570. # use a Matrix reply instead of reposting the image.
  571. content.set_reply(existing.mxid)
  572. else:
  573. media_event_id = await self._handle_instagram_media(source, intent, item)
  574. await DBMessage(mxid=media_event_id, mx_room=self.mxid, item_id=fake_item_id,
  575. receiver=self.receiver, sender=media.user.pk).insert()
  576. return await self._send_message(intent, content, timestamp=item.timestamp // 1000)
  577. async def _handle_instagram_text(self, intent: IntentAPI, item: ThreadItem, text: str,
  578. ) -> EventID:
  579. content = TextMessageEventContent(msgtype=MessageType.TEXT, body=text)
  580. await self._add_instagram_reply(content, item.replied_to_message)
  581. return await self._send_message(intent, content, timestamp=item.timestamp // 1000)
  582. async def _send_instagram_unhandled(self, intent: IntentAPI, item: ThreadItem) -> EventID:
  583. content = TextMessageEventContent(msgtype=MessageType.NOTICE,
  584. body="Unsupported message type")
  585. await self._add_instagram_reply(content, item.replied_to_message)
  586. return await self._send_message(intent, content, timestamp=item.timestamp // 1000)
  587. async def _handle_instagram_location(self, intent: IntentAPI, item: ThreadItem
  588. ) -> Optional[EventID]:
  589. loc = item.location
  590. if not loc.lng or not loc.lat:
  591. # TODO handle somehow
  592. return None
  593. long_char = "E" if loc.lng > 0 else "W"
  594. lat_char = "N" if loc.lat > 0 else "S"
  595. body = (f"{loc.name} - {round(abs(loc.lat), 4)}° {lat_char}, "
  596. f"{round(abs(loc.lng), 4)}° {long_char}")
  597. url = f"https://www.openstreetmap.org/#map=15/{loc.lat}/{loc.lng}"
  598. external_url = None
  599. if loc.external_source == "facebook_places":
  600. external_url = f"https://www.facebook.com/{loc.short_name}-{loc.facebook_places_id}"
  601. content = LocationMessageEventContent(
  602. msgtype=MessageType.LOCATION, geo_uri=f"geo:{loc.lat},{loc.lng}",
  603. body=f"Location: {body}\n{url}", external_url=external_url)
  604. content["format"] = str(Format.HTML)
  605. content["formatted_body"] = f"Location: <a href='{url}'>{body}</a>"
  606. await self._add_instagram_reply(content, item.replied_to_message)
  607. return await self._send_message(intent, content, timestamp=item.timestamp // 1000)
  608. async def handle_instagram_item(self, source: 'u.User', sender: 'p.Puppet', item: ThreadItem,
  609. is_backfill: bool = False) -> None:
  610. try:
  611. await self._handle_instagram_item(source, sender, item, is_backfill)
  612. except Exception:
  613. self.log.exception("Fatal error handling Instagram item")
  614. self.log.trace("Item content: %s", item.serialize())
  615. async def _add_instagram_reply(self, content: MessageEventContent,
  616. reply_to: Optional[ThreadItem]) -> None:
  617. if not reply_to:
  618. return
  619. message = await DBMessage.get_by_item_id(reply_to.item_id, self.receiver)
  620. if not message:
  621. return
  622. content.set_reply(message.mxid)
  623. if not isinstance(content, TextMessageEventContent):
  624. return
  625. try:
  626. evt = await self.main_intent.get_event(message.mx_room, message.mxid)
  627. except (MNotFound, MForbidden):
  628. evt = None
  629. if not evt:
  630. return
  631. if evt.type == EventType.ROOM_ENCRYPTED:
  632. try:
  633. evt = await self.matrix.e2ee.decrypt(evt, wait_session_timeout=0)
  634. except SessionNotFound:
  635. return
  636. if isinstance(evt.content, TextMessageEventContent):
  637. evt.content.trim_reply_fallback()
  638. content.set_reply(evt)
  639. async def _handle_instagram_item(self, source: 'u.User', sender: 'p.Puppet', item: ThreadItem,
  640. is_backfill: bool = False) -> None:
  641. if not isinstance(item, ThreadItem):
  642. # Parsing these items failed, they should have been logged already
  643. return
  644. elif item.client_context in self._reqid_dedup:
  645. self.log.debug(f"Ignoring message {item.item_id} ({item.client_context}) by "
  646. f"{item.user_id} as it was sent by us (client_context in dedup queue)")
  647. elif item.item_id in self._msgid_dedup:
  648. self.log.debug(f"Ignoring message {item.item_id} ({item.client_context}) by "
  649. f"{item.user_id} as it was already handled (message.id in dedup queue)")
  650. elif await DBMessage.get_by_item_id(item.item_id, self.receiver) is not None:
  651. self.log.debug(f"Ignoring message {item.item_id} ({item.client_context}) by "
  652. f"{item.user_id} as it was already handled (message.id in database)")
  653. else:
  654. self.log.debug(f"Starting handling of message {item.item_id} ({item.client_context}) "
  655. f"by {item.user_id}")
  656. self._msgid_dedup.appendleft(item.item_id)
  657. if self.backfill_lock.locked and sender.need_backfill_invite(self):
  658. self.log.debug("Adding %s's default puppet to room for backfilling", sender.mxid)
  659. if self.is_direct:
  660. await self.main_intent.invite_user(self.mxid, sender.default_mxid)
  661. intent = sender.default_mxid_intent
  662. await intent.ensure_joined(self.mxid)
  663. self._backfill_leave.add(intent)
  664. else:
  665. intent = sender.intent_for(self)
  666. event_id = None
  667. if item.media or item.animated_media or item.voice_media or item.visual_media:
  668. event_id = await self._handle_instagram_media(source, intent, item)
  669. elif item.location:
  670. event_id = await self._handle_instagram_location(intent, item)
  671. elif item.reel_share:
  672. event_id = await self._handle_instagram_reel_share(source, intent, item)
  673. elif item.media_share or item.story_share:
  674. event_id = await self._handle_instagram_media_share(source, intent, item)
  675. elif item.action_log:
  676. # These probably don't need to be bridged
  677. self.log.debug(f"Ignoring action log message {item.item_id}")
  678. return
  679. # TODO handle item.clip?
  680. if item.text:
  681. event_id = await self._handle_instagram_text(intent, item, item.text)
  682. elif item.like:
  683. # We handle likes as text because Matrix clients do big emoji on their own.
  684. event_id = await self._handle_instagram_text(intent, item, item.like)
  685. elif item.link:
  686. event_id = await self._handle_instagram_text(intent, item, item.link.text)
  687. handled = bool(event_id)
  688. if not event_id:
  689. self.log.debug(f"Unhandled Instagram message {item.item_id}")
  690. event_id = await self._send_instagram_unhandled(intent, item)
  691. msg = DBMessage(mxid=event_id, mx_room=self.mxid, item_id=item.item_id,
  692. receiver=self.receiver, sender=sender.pk)
  693. await msg.insert()
  694. await self._send_delivery_receipt(event_id)
  695. if handled:
  696. self.log.debug(f"Handled Instagram message {item.item_id} -> {event_id}")
  697. else:
  698. self.log.debug(f"Unhandled Instagram message {item.item_id} "
  699. f"(type {item.item_type} -> fallback error {event_id})")
  700. if is_backfill and item.reactions:
  701. await self._handle_instagram_reactions(msg, item.reactions.emojis)
  702. async def handle_instagram_remove(self, item_id: str) -> None:
  703. message = await DBMessage.get_by_item_id(item_id, self.receiver)
  704. if message is None:
  705. return
  706. await message.delete()
  707. sender = await p.Puppet.get_by_pk(message.sender)
  708. try:
  709. await sender.intent_for(self).redact(self.mxid, message.mxid)
  710. except MForbidden:
  711. await self.main_intent.redact(self.mxid, message.mxid)
  712. self.log.debug(f"Redacted {message.mxid} after Instagram unsend")
  713. async def _handle_instagram_reactions(self, message: DBMessage, reactions: List[Reaction]
  714. ) -> None:
  715. old_reactions: Dict[int, DBReaction]
  716. old_reactions = {reaction.ig_sender: reaction for reaction
  717. in await DBReaction.get_all_by_item_id(message.item_id, self.receiver)}
  718. for new_reaction in reactions:
  719. old_reaction = old_reactions.pop(new_reaction.sender_id, None)
  720. if old_reaction and old_reaction.reaction == new_reaction.emoji:
  721. continue
  722. puppet = await p.Puppet.get_by_pk(new_reaction.sender_id)
  723. intent = puppet.intent_for(self)
  724. reaction_event_id = await intent.react(self.mxid, message.mxid, new_reaction.emoji)
  725. await self._upsert_reaction(old_reaction, intent, reaction_event_id, message,
  726. puppet, new_reaction.emoji)
  727. for old_reaction in old_reactions.values():
  728. await old_reaction.delete()
  729. puppet = await p.Puppet.get_by_pk(old_reaction.ig_sender)
  730. await puppet.intent_for(self).redact(self.mxid, old_reaction.mxid)
  731. async def handle_instagram_update(self, item: MessageSyncMessage) -> None:
  732. message = await DBMessage.get_by_item_id(item.item_id, self.receiver)
  733. if not message:
  734. return
  735. if item.has_seen:
  736. puppet = await p.Puppet.get_by_pk(item.has_seen, create=False)
  737. if puppet:
  738. await puppet.intent_for(self).mark_read(self.mxid, message.mxid)
  739. else:
  740. async with self._reaction_lock:
  741. await self._handle_instagram_reactions(message, (item.reactions.emojis
  742. if item.reactions else []))
  743. # endregion
  744. # region Updating portal info
  745. def _get_thread_name(self, thread: Thread) -> str:
  746. if self.is_direct:
  747. if self.other_user_pk == thread.viewer_id and len(thread.users) == 0:
  748. return "Instagram chat with yourself"
  749. elif len(thread.users) == 1:
  750. tpl = self.config["bridge.private_chat_name_template"]
  751. ui = thread.users[0]
  752. return tpl.format(displayname=ui.full_name, id=ui.pk, username=ui.username)
  753. pass
  754. elif thread.thread_title:
  755. return self.config["bridge.group_chat_name_template"].format(name=thread.thread_title)
  756. else:
  757. return ""
  758. async def update_info(self, thread: Thread, source: 'u.User') -> None:
  759. changed = await self._update_name(self._get_thread_name(thread))
  760. changed = await self._update_participants(thread.users, source) or changed
  761. if changed:
  762. await self.update_bridge_info()
  763. await self.update()
  764. # TODO update power levels with thread.admin_user_ids
  765. async def _update_name(self, name: str) -> bool:
  766. if name and (self.name != name or not self.name_set):
  767. self.name = name
  768. if self.mxid:
  769. try:
  770. await self.main_intent.set_room_name(self.mxid, name)
  771. self.name_set = True
  772. except Exception:
  773. self.log.exception("Failed to update name")
  774. self.name_set = False
  775. return True
  776. return False
  777. async def _update_photo_from_puppet(self, puppet: 'p.Puppet') -> bool:
  778. if not self.private_chat_portal_meta and not self.encrypted:
  779. return False
  780. if self.avatar_set and self.avatar_url == puppet.photo_mxc:
  781. return False
  782. self.avatar_url = puppet.photo_mxc
  783. if self.mxid:
  784. try:
  785. await self.main_intent.set_room_avatar(self.mxid, puppet.photo_mxc)
  786. self.avatar_set = True
  787. except Exception:
  788. self.log.exception("Failed to set room avatar")
  789. self.avatar_set = False
  790. return True
  791. async def _update_participants(self, users: List[ThreadUser], source: 'u.User') -> bool:
  792. meta_changed = False
  793. # Make sure puppets who should be here are here
  794. for user in users:
  795. puppet = await p.Puppet.get_by_pk(user.pk)
  796. await puppet.update_info(user, source)
  797. if self.mxid:
  798. await puppet.intent_for(self).ensure_joined(self.mxid)
  799. if puppet.pk == self.other_user_pk:
  800. meta_changed = await self._update_photo_from_puppet(puppet)
  801. if self.mxid:
  802. # Kick puppets who shouldn't be here
  803. current_members = {int(user.pk) for user in users}
  804. for user_id in await self.main_intent.get_room_members(self.mxid):
  805. pk = p.Puppet.get_id_from_mxid(user_id)
  806. if pk and pk not in current_members and pk != self.other_user_pk:
  807. await self.main_intent.kick_user(self.mxid, p.Puppet.get_mxid_from_id(pk),
  808. reason="User had left this Instagram DM")
  809. return meta_changed
  810. async def _update_read_receipts(self, receipts: Dict[Union[int, str], ThreadUserLastSeenAt]
  811. ) -> None:
  812. for user_id, receipt in receipts.items():
  813. message = await DBMessage.get_by_item_id(receipt.item_id, self.receiver)
  814. if not message:
  815. continue
  816. puppet = await p.Puppet.get_by_pk(int(user_id), create=False)
  817. if not puppet:
  818. continue
  819. try:
  820. await puppet.intent_for(self).mark_read(message.mx_room, message.mxid)
  821. except Exception:
  822. self.log.warning(f"Failed to mark {message.mxid} in {message.mx_room} "
  823. f"as read by {puppet.intent.mxid}", exc_info=True)
  824. # endregion
  825. # region Backfilling
  826. async def backfill(self, source: 'u.User', is_initial: bool = False) -> None:
  827. limit = (self.config["bridge.backfill.initial_limit"] if is_initial
  828. else self.config["bridge.backfill.missed_limit"])
  829. if limit == 0:
  830. return
  831. elif limit < 0:
  832. limit = None
  833. with self.backfill_lock:
  834. await self._backfill(source, is_initial, limit)
  835. async def _backfill(self, source: 'u.User', is_initial: bool, limit: int) -> None:
  836. self.log.debug("Backfilling history through %s", source.mxid)
  837. entries = await self._fetch_backfill_items(source, is_initial, limit)
  838. if not entries:
  839. self.log.debug("Didn't get any items to backfill from server")
  840. return
  841. self.log.debug("Got %d entries from server", len(entries))
  842. self._backfill_leave = set()
  843. async with NotificationDisabler(self.mxid, source):
  844. for entry in reversed(entries):
  845. sender = await p.Puppet.get_by_pk(int(entry.user_id))
  846. await self.handle_instagram_item(source, sender, entry, is_backfill=True)
  847. for intent in self._backfill_leave:
  848. self.log.trace("Leaving room with %s post-backfill", intent.mxid)
  849. await intent.leave_room(self.mxid)
  850. self._backfill_leave = None
  851. self.log.info("Backfilled %d messages through %s", len(entries), source.mxid)
  852. async def _fetch_backfill_items(self, source: 'u.User', is_initial: bool, limit: int
  853. ) -> List[ThreadItem]:
  854. items = []
  855. self.log.debug("Fetching up to %d messages through %s", limit, source.igpk)
  856. async for item in source.client.iter_thread(self.thread_id):
  857. if len(items) >= limit:
  858. self.log.debug(f"Fetched {len(items)} messages (the limit)")
  859. break
  860. elif not is_initial:
  861. msg = await DBMessage.get_by_item_id(item.item_id, receiver=self.receiver)
  862. if msg is not None:
  863. self.log.debug(f"Fetched {len(items)} messages and hit a message"
  864. " that's already in the database.")
  865. break
  866. items.append(item)
  867. return items
  868. # endregion
  869. # region Bridge info state event
  870. @property
  871. def bridge_info_state_key(self) -> str:
  872. return f"net.maunium.instagram://instagram/{self.thread_id}"
  873. @property
  874. def bridge_info(self) -> Dict[str, Any]:
  875. return {
  876. "bridgebot": self.az.bot_mxid,
  877. "creator": self.main_intent.mxid,
  878. "protocol": {
  879. "id": "instagram",
  880. "displayname": "Instagram DM",
  881. "avatar_url": self.config["appservice.bot_avatar"],
  882. },
  883. "channel": {
  884. "id": self.thread_id,
  885. "displayname": self.name,
  886. "avatar_url": self.avatar_url,
  887. }
  888. }
  889. async def update_bridge_info(self) -> None:
  890. if not self.mxid:
  891. self.log.debug("Not updating bridge info: no Matrix room created")
  892. return
  893. try:
  894. self.log.debug("Updating bridge info...")
  895. await self.main_intent.send_state_event(self.mxid, StateBridge,
  896. self.bridge_info, self.bridge_info_state_key)
  897. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  898. await self.main_intent.send_state_event(self.mxid, StateHalfShotBridge,
  899. self.bridge_info, self.bridge_info_state_key)
  900. except Exception:
  901. self.log.warning("Failed to update bridge info", exc_info=True)
  902. # endregion
  903. # region Creating Matrix rooms
  904. async def create_matrix_room(self, source: 'u.User', info: Thread) -> Optional[RoomID]:
  905. if self.mxid:
  906. try:
  907. await self.update_matrix_room(source, info)
  908. except Exception:
  909. self.log.exception("Failed to update portal")
  910. return self.mxid
  911. async with self._create_room_lock:
  912. return await self._create_matrix_room(source, info)
  913. def _get_invite_content(self, double_puppet: Optional['p.Puppet']) -> Dict[str, Any]:
  914. invite_content = {}
  915. if double_puppet:
  916. invite_content["fi.mau.will_auto_accept"] = True
  917. if self.is_direct:
  918. invite_content["is_direct"] = True
  919. return invite_content
  920. async def update_matrix_room(self, source: 'u.User', info: Thread, backfill: bool = False
  921. ) -> None:
  922. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  923. await self.main_intent.invite_user(self.mxid, source.mxid, check_cache=True,
  924. extra_content=self._get_invite_content(puppet))
  925. if puppet:
  926. did_join = await puppet.intent.ensure_joined(self.mxid)
  927. if did_join and self.is_direct:
  928. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  929. await self.update_info(info, source)
  930. if backfill:
  931. last_msg = await DBMessage.get_by_item_id(info.last_permanent_item.item_id,
  932. receiver=self.receiver)
  933. if last_msg is None:
  934. self.log.debug(f"Last permanent item ({info.last_permanent_item.item_id})"
  935. " not found in database, starting backfilling")
  936. await self.backfill(source, is_initial=False)
  937. await self._update_read_receipts(info.last_seen_at)
  938. # TODO
  939. # up = DBUserPortal.get(source.fbid, self.fbid, self.fb_receiver)
  940. # if not up:
  941. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  942. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  943. # in_community=in_community).insert()
  944. # elif not up.in_community:
  945. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  946. # up.edit(in_community=in_community)
  947. async def _create_matrix_room(self, source: 'u.User', info: Thread) -> Optional[RoomID]:
  948. if self.mxid:
  949. await self.update_matrix_room(source, info)
  950. return self.mxid
  951. await self.update_info(info, source)
  952. self.log.debug("Creating Matrix room")
  953. name: Optional[str] = None
  954. initial_state = [{
  955. "type": str(StateBridge),
  956. "state_key": self.bridge_info_state_key,
  957. "content": self.bridge_info,
  958. }, {
  959. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  960. "type": str(StateHalfShotBridge),
  961. "state_key": self.bridge_info_state_key,
  962. "content": self.bridge_info,
  963. }]
  964. invites = []
  965. if self.config["bridge.encryption.default"] and self.matrix.e2ee:
  966. self.encrypted = True
  967. initial_state.append({
  968. "type": "m.room.encryption",
  969. "content": {"algorithm": "m.megolm.v1.aes-sha2"},
  970. })
  971. if self.is_direct:
  972. invites.append(self.az.bot_mxid)
  973. if self.encrypted or self.private_chat_portal_meta or not self.is_direct:
  974. name = self.name
  975. if self.config["appservice.community_id"]:
  976. initial_state.append({
  977. "type": "m.room.related_groups",
  978. "content": {"groups": [self.config["appservice.community_id"]]},
  979. })
  980. # We lock backfill lock here so any messages that come between the room being created
  981. # and the initial backfill finishing wouldn't be bridged before the backfill messages.
  982. with self.backfill_lock:
  983. creation_content = {}
  984. if not self.config["bridge.federate_rooms"]:
  985. creation_content["m.federate"] = False
  986. self.mxid = await self.main_intent.create_room(
  987. name=name,
  988. is_direct=self.is_direct,
  989. initial_state=initial_state,
  990. invitees=invites,
  991. creation_content=creation_content,
  992. )
  993. if not self.mxid:
  994. raise Exception("Failed to create room: no mxid returned")
  995. if self.encrypted and self.matrix.e2ee and self.is_direct:
  996. try:
  997. await self.az.intent.ensure_joined(self.mxid)
  998. except Exception:
  999. self.log.warning("Failed to add bridge bot "
  1000. f"to new private chat {self.mxid}")
  1001. await self.update()
  1002. self.log.debug(f"Matrix room created: {self.mxid}")
  1003. self.by_mxid[self.mxid] = self
  1004. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  1005. await self.main_intent.invite_user(self.mxid, source.mxid,
  1006. extra_content=self._get_invite_content(puppet))
  1007. if puppet:
  1008. try:
  1009. if self.is_direct:
  1010. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  1011. await puppet.intent.join_room_by_id(self.mxid)
  1012. except MatrixError:
  1013. self.log.debug("Failed to join custom puppet into newly created portal",
  1014. exc_info=True)
  1015. await self._update_participants(info.users, source)
  1016. # TODO
  1017. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  1018. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  1019. # in_community=in_community).upsert()
  1020. try:
  1021. await self.backfill(source, is_initial=True)
  1022. except Exception:
  1023. self.log.exception("Failed to backfill new portal")
  1024. await self._update_read_receipts(info.last_seen_at)
  1025. return self.mxid
  1026. # endregion
  1027. # region Database getters
  1028. async def postinit(self) -> None:
  1029. self.by_thread_id[(self.thread_id, self.receiver)] = self
  1030. if self.mxid:
  1031. self.by_mxid[self.mxid] = self
  1032. self._main_intent = ((await p.Puppet.get_by_pk(self.other_user_pk)).default_mxid_intent
  1033. if self.other_user_pk else self.az.intent)
  1034. async def delete(self) -> None:
  1035. await DBMessage.delete_all(self.mxid)
  1036. self.by_mxid.pop(self.mxid, None)
  1037. self.mxid = None
  1038. self.encrypted = False
  1039. await self.update()
  1040. async def save(self) -> None:
  1041. await self.update()
  1042. @classmethod
  1043. def all_with_room(cls) -> AsyncGenerator['Portal', None]:
  1044. return cls._db_to_portals(super().all_with_room())
  1045. @classmethod
  1046. def find_private_chats_with(cls, other_user: int) -> AsyncGenerator['Portal', None]:
  1047. return cls._db_to_portals(super().find_private_chats_with(other_user))
  1048. @classmethod
  1049. async def _db_to_portals(cls, query: Awaitable[List['Portal']]
  1050. ) -> AsyncGenerator['Portal', None]:
  1051. portals = await query
  1052. for index, portal in enumerate(portals):
  1053. try:
  1054. yield cls.by_thread_id[(portal.thread_id, portal.receiver)]
  1055. except KeyError:
  1056. await portal.postinit()
  1057. yield portal
  1058. @classmethod
  1059. @async_getter_lock
  1060. async def get_by_mxid(cls, mxid: RoomID) -> Optional['Portal']:
  1061. try:
  1062. return cls.by_mxid[mxid]
  1063. except KeyError:
  1064. pass
  1065. portal = cast(cls, await super().get_by_mxid(mxid))
  1066. if portal is not None:
  1067. await portal.postinit()
  1068. return portal
  1069. return None
  1070. @classmethod
  1071. @async_getter_lock
  1072. async def get_by_thread_id(cls, thread_id: str, *, receiver: int,
  1073. is_group: Optional[bool] = None,
  1074. other_user_pk: Optional[int] = None) -> Optional['Portal']:
  1075. if is_group and receiver != 0:
  1076. receiver = 0
  1077. try:
  1078. return cls.by_thread_id[(thread_id, receiver)]
  1079. except KeyError:
  1080. pass
  1081. if is_group is None and receiver != 0:
  1082. try:
  1083. return cls.by_thread_id[(thread_id, 0)]
  1084. except KeyError:
  1085. pass
  1086. portal = cast(cls, await super().get_by_thread_id(thread_id, receiver=receiver,
  1087. rec_must_match=is_group is not None))
  1088. if portal is not None:
  1089. await portal.postinit()
  1090. return portal
  1091. if is_group is not None:
  1092. portal = cls(thread_id, receiver, other_user_pk=other_user_pk)
  1093. await portal.insert()
  1094. await portal.postinit()
  1095. return portal
  1096. return None
  1097. @classmethod
  1098. async def get_by_thread(cls, thread: Thread, receiver: int) -> Optional['Portal']:
  1099. if thread.is_group:
  1100. receiver = 0
  1101. other_user_pk = None
  1102. else:
  1103. if len(thread.users) == 0:
  1104. other_user_pk = receiver
  1105. else:
  1106. other_user_pk = thread.users[0].pk
  1107. return await cls.get_by_thread_id(thread.thread_id, receiver=receiver,
  1108. is_group=thread.is_group, other_user_pk=other_user_pk)
  1109. # endregion