portal.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2020 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, TYPE_CHECKING, cast)
  18. from collections import deque
  19. from uuid import uuid4
  20. from io import BytesIO
  21. import mimetypes
  22. import asyncio
  23. import magic
  24. from mauigpapi.types import (Thread, ThreadUser, ThreadItem, RegularMediaItem, MediaType,
  25. ReactionStatus, Reaction, AnimatedMediaItem, ThreadItemType,
  26. VoiceMediaItem, ExpiredMediaItem, MessageSyncMessage, ReelShareType)
  27. from mautrix.appservice import AppService, IntentAPI
  28. from mautrix.bridge import BasePortal, NotificationDisabler
  29. from mautrix.types import (EventID, MessageEventContent, RoomID, EventType, MessageType, ImageInfo,
  30. VideoInfo, MediaMessageEventContent, TextMessageEventContent, AudioInfo,
  31. ContentURI, EncryptedFile, LocationMessageEventContent, Format)
  32. from mautrix.errors import MatrixError, MForbidden
  33. from mautrix.util.simple_lock import SimpleLock
  34. from mautrix.util.network_retry import call_with_net_retry
  35. from .db import Portal as DBPortal, Message as DBMessage, Reaction as DBReaction
  36. from .config import Config
  37. from . import user as u, puppet as p, matrix as m
  38. if TYPE_CHECKING:
  39. from .__main__ import InstagramBridge
  40. try:
  41. from mautrix.crypto.attachments import encrypt_attachment, decrypt_attachment
  42. except ImportError:
  43. encrypt_attachment = decrypt_attachment = None
  44. try:
  45. from PIL import Image
  46. except ImportError:
  47. Image = None
  48. StateBridge = EventType.find("m.bridge", EventType.Class.STATE)
  49. StateHalfShotBridge = EventType.find("uk.half-shot.bridge", EventType.Class.STATE)
  50. FileInfo = Union[AudioInfo, ImageInfo, VideoInfo]
  51. ReuploadedMediaInfo = NamedTuple('ReuploadedMediaInfo', mxc=Optional[ContentURI], url=str,
  52. decryption_info=Optional[EncryptedFile], msgtype=MessageType,
  53. file_name=str, info=FileInfo)
  54. class Portal(DBPortal, BasePortal):
  55. by_mxid: Dict[RoomID, 'Portal'] = {}
  56. by_thread_id: Dict[Tuple[str, int], 'Portal'] = {}
  57. config: Config
  58. matrix: 'm.MatrixHandler'
  59. az: AppService
  60. private_chat_portal_meta: bool
  61. _main_intent: Optional[IntentAPI]
  62. _create_room_lock: asyncio.Lock
  63. backfill_lock: SimpleLock
  64. _msgid_dedup: Deque[str]
  65. _reqid_dedup: Set[str]
  66. _reaction_dedup: Deque[Tuple[str, int, str]]
  67. _main_intent: IntentAPI
  68. _last_participant_update: Set[int]
  69. _reaction_lock: asyncio.Lock
  70. _backfill_leave: Optional[Set[IntentAPI]]
  71. def __init__(self, thread_id: str, receiver: int, other_user_pk: Optional[int],
  72. mxid: Optional[RoomID] = None, name: Optional[str] = None, encrypted: bool = False
  73. ) -> None:
  74. super().__init__(thread_id, receiver, other_user_pk, mxid, name, encrypted)
  75. self._create_room_lock = asyncio.Lock()
  76. self.log = self.log.getChild(thread_id)
  77. self._msgid_dedup = deque(maxlen=100)
  78. self._reaction_dedup = deque(maxlen=100)
  79. self._reqid_dedup = set()
  80. self._last_participant_update = set()
  81. self.backfill_lock = SimpleLock("Waiting for backfilling to finish before handling %s",
  82. log=self.log)
  83. self._backfill_leave = None
  84. self._main_intent = None
  85. self._reaction_lock = asyncio.Lock()
  86. @property
  87. def is_direct(self) -> bool:
  88. return self.other_user_pk is not None
  89. @property
  90. def main_intent(self) -> IntentAPI:
  91. if not self._main_intent:
  92. raise ValueError("Portal must be postinit()ed before main_intent can be used")
  93. return self._main_intent
  94. @classmethod
  95. def init_cls(cls, bridge: 'InstagramBridge') -> None:
  96. cls.config = bridge.config
  97. cls.matrix = bridge.matrix
  98. cls.az = bridge.az
  99. cls.loop = bridge.loop
  100. cls.bridge = bridge
  101. cls.private_chat_portal_meta = cls.config["bridge.private_chat_portal_meta"]
  102. NotificationDisabler.puppet_cls = p.Puppet
  103. NotificationDisabler.config_enabled = cls.config["bridge.backfill.disable_notifications"]
  104. # region Misc
  105. async def _send_delivery_receipt(self, event_id: EventID) -> None:
  106. if event_id and self.config["bridge.delivery_receipts"]:
  107. try:
  108. await self.az.intent.mark_read(self.mxid, event_id)
  109. except Exception:
  110. self.log.exception("Failed to send delivery receipt for %s", event_id)
  111. async def _upsert_reaction(self, existing: DBReaction, intent: IntentAPI, mxid: EventID,
  112. message: DBMessage, sender: Union['u.User', 'p.Puppet'],
  113. reaction: str) -> None:
  114. if existing:
  115. self.log.debug(f"_upsert_reaction redacting {existing.mxid} and inserting {mxid}"
  116. f" (message: {message.mxid})")
  117. await intent.redact(existing.mx_room, existing.mxid)
  118. await existing.edit(reaction=reaction, mxid=mxid, mx_room=message.mx_room)
  119. else:
  120. self.log.debug(f"_upsert_reaction inserting {mxid} (message: {message.mxid})")
  121. await DBReaction(mxid=mxid, mx_room=message.mx_room, ig_item_id=message.item_id,
  122. ig_receiver=self.receiver, ig_sender=sender.igpk, reaction=reaction
  123. ).insert()
  124. # endregion
  125. # region Matrix event handling
  126. async def handle_matrix_message(self, sender: 'u.User', message: MessageEventContent,
  127. event_id: EventID) -> None:
  128. if not sender.client:
  129. self.log.debug(f"Ignoring message {event_id} as user is not connected")
  130. return
  131. elif ((message.get(self.bridge.real_user_content_key,
  132. False) and await p.Puppet.get_by_custom_mxid(sender.mxid))):
  133. self.log.debug(f"Ignoring puppet-sent message by confirmed puppet user {sender.mxid}")
  134. return
  135. request_id = str(uuid4())
  136. self._reqid_dedup.add(request_id)
  137. if message.msgtype in (MessageType.EMOTE, MessageType.TEXT):
  138. text = message.body
  139. if message.msgtype == MessageType.EMOTE:
  140. text = f"/me {text}"
  141. resp = await sender.mqtt.send_text(self.thread_id, text=text,
  142. client_context=request_id)
  143. elif message.msgtype.is_media:
  144. if message.file and decrypt_attachment:
  145. data = await self.main_intent.download_media(message.file.url)
  146. data = decrypt_attachment(data, message.file.key.key,
  147. message.file.hashes.get("sha256"), message.file.iv)
  148. else:
  149. data = await self.main_intent.download_media(message.url)
  150. mime_type = message.info.mimetype or magic.from_buffer(data, mime=True)
  151. if mime_type != "image/jpeg" and mime_type.startswith("image/"):
  152. with BytesIO(data) as inp:
  153. img = Image.open(inp)
  154. with BytesIO() as out:
  155. img.convert("RGB").save(out, format="JPEG", quality=80)
  156. data = out.getvalue()
  157. mime_type = "image/jpeg"
  158. if mime_type == "image/jpeg":
  159. upload_resp = await sender.client.upload_jpeg_photo(data)
  160. # TODO is it possible to do this with MQTT?
  161. resp = await sender.client.broadcast(self.thread_id,
  162. ThreadItemType.CONFIGURE_PHOTO,
  163. client_context=request_id,
  164. upload_id=upload_resp.upload_id,
  165. allow_full_aspect_ratio="1")
  166. else:
  167. # TODO add link to media for unsupported file types
  168. return
  169. else:
  170. return
  171. if resp.status != "ok":
  172. self.log.warning(f"Failed to handle {event_id}: {resp}")
  173. else:
  174. self._msgid_dedup.appendleft(resp.payload.item_id)
  175. await DBMessage(mxid=event_id, mx_room=self.mxid, item_id=resp.payload.item_id,
  176. receiver=self.receiver, sender=sender.igpk).insert()
  177. self._reqid_dedup.remove(request_id)
  178. await self._send_delivery_receipt(event_id)
  179. self.log.debug(f"Handled Matrix message {event_id} -> {resp.payload.item_id}")
  180. async def handle_matrix_reaction(self, sender: 'u.User', event_id: EventID,
  181. reacting_to: EventID, emoji: str) -> None:
  182. message = await DBMessage.get_by_mxid(reacting_to, self.mxid)
  183. if not message or message.is_internal:
  184. self.log.debug(f"Ignoring reaction to unknown event {reacting_to}")
  185. return
  186. existing = await DBReaction.get_by_item_id(message.item_id, message.receiver, sender.igpk)
  187. if existing and existing.reaction == emoji:
  188. return
  189. dedup_id = (message.item_id, sender.igpk, emoji)
  190. self._reaction_dedup.appendleft(dedup_id)
  191. async with self._reaction_lock:
  192. # TODO check response?
  193. await sender.mqtt.send_reaction(self.thread_id, item_id=message.item_id, emoji=emoji)
  194. await self._upsert_reaction(existing, self.main_intent, event_id, message, sender,
  195. emoji)
  196. self.log.trace(f"{sender.mxid} reacted to {message.item_id} with {emoji}")
  197. await self._send_delivery_receipt(event_id)
  198. async def handle_matrix_redaction(self, sender: 'u.User', event_id: EventID,
  199. redaction_event_id: EventID) -> None:
  200. if not self.mxid:
  201. return
  202. # TODO implement
  203. reaction = await DBReaction.get_by_mxid(event_id, self.mxid)
  204. if reaction:
  205. try:
  206. await reaction.delete()
  207. await sender.mqtt.send_reaction(self.thread_id, item_id=reaction.ig_item_id,
  208. reaction_status=ReactionStatus.DELETED, emoji="")
  209. await self._send_delivery_receipt(redaction_event_id)
  210. self.log.trace(f"Removed {reaction} after Matrix redaction")
  211. except Exception:
  212. self.log.exception("Removing reaction failed")
  213. return
  214. message = await DBMessage.get_by_mxid(event_id, self.mxid)
  215. if message and not message.is_internal:
  216. try:
  217. await message.delete()
  218. await sender.client.delete_item(self.thread_id, message.item_id)
  219. self.log.trace(f"Removed {message} after Matrix redaction")
  220. except Exception:
  221. self.log.exception("Removing message failed")
  222. async def handle_matrix_leave(self, user: 'u.User') -> None:
  223. if self.is_direct:
  224. self.log.info(f"{user.mxid} left private chat portal with {self.other_user_pk}")
  225. if user.igpk == self.receiver:
  226. self.log.info(f"{user.mxid} was the recipient of this portal. "
  227. "Cleaning up and deleting...")
  228. await self.cleanup_and_delete()
  229. else:
  230. self.log.debug(f"{user.mxid} left portal to {self.thread_id}")
  231. # TODO cleanup if empty
  232. # endregion
  233. # region Instagram event handling
  234. async def _reupload_instagram_media(self, source: 'u.User', media: RegularMediaItem,
  235. intent: IntentAPI) -> Optional[ReuploadedMediaInfo]:
  236. if media.media_type == MediaType.IMAGE:
  237. image = media.best_image
  238. if not image:
  239. return None
  240. url = image.url
  241. msgtype = MessageType.IMAGE
  242. info = ImageInfo(height=image.height, width=image.width)
  243. elif media.media_type == MediaType.VIDEO:
  244. video = media.best_video
  245. if not video:
  246. return None
  247. url = video.url
  248. msgtype = MessageType.VIDEO
  249. info = VideoInfo(height=video.height, width=video.width)
  250. else:
  251. return None
  252. return await self._reupload_instagram_file(source, url, msgtype, info, intent)
  253. async def _reupload_instagram_animated(self, source: 'u.User', media: AnimatedMediaItem,
  254. intent: IntentAPI) -> Optional[ReuploadedMediaInfo]:
  255. url = media.images.fixed_height.webp
  256. info = ImageInfo(height=int(media.images.fixed_height.height),
  257. width=int(media.images.fixed_height.width))
  258. return await self._reupload_instagram_file(source, url, MessageType.IMAGE, info, intent)
  259. async def _reupload_instagram_voice(self, source: 'u.User', media: VoiceMediaItem,
  260. intent: IntentAPI) -> Optional[ReuploadedMediaInfo]:
  261. url = media.media.audio.audio_src
  262. info = AudioInfo(duration=media.media.audio.duration)
  263. return await self._reupload_instagram_file(source, url, MessageType.AUDIO, info, intent)
  264. async def _reupload_instagram_file(self, source: 'u.User', url: str, msgtype: MessageType,
  265. info: FileInfo, intent: IntentAPI
  266. ) -> Optional[ReuploadedMediaInfo]:
  267. async with await source.client.raw_http_get(url) as resp:
  268. data = await resp.read()
  269. info.mimetype = resp.headers["Content-Type"] or magic.from_buffer(data, mime=True)
  270. info.size = len(data)
  271. extension = {
  272. "image/webp": ".webp",
  273. "image/jpeg": ".jpg",
  274. "video/mp4": ".mp4",
  275. "audio/mp4": ".m4a",
  276. }.get(info.mimetype)
  277. extension = extension or mimetypes.guess_extension(info.mimetype) or ""
  278. file_name = f"{msgtype.value[2:]}{extension}"
  279. upload_mime_type = info.mimetype
  280. upload_file_name = file_name
  281. decryption_info = None
  282. if self.encrypted and encrypt_attachment:
  283. data, decryption_info = encrypt_attachment(data)
  284. upload_mime_type = "application/octet-stream"
  285. upload_file_name = None
  286. mxc = await call_with_net_retry(intent.upload_media, data, mime_type=upload_mime_type,
  287. filename=upload_file_name, _action="upload media")
  288. if decryption_info:
  289. decryption_info.url = mxc
  290. mxc = None
  291. return ReuploadedMediaInfo(mxc=mxc, url=url, decryption_info=decryption_info,
  292. file_name=file_name, msgtype=msgtype, info=info)
  293. async def _handle_instagram_media(self, source: 'u.User', intent: IntentAPI, item: ThreadItem
  294. ) -> Optional[EventID]:
  295. if item.media:
  296. reuploaded = await self._reupload_instagram_media(source, item.media, intent)
  297. elif item.visual_media:
  298. if isinstance(item.visual_media.media, ExpiredMediaItem):
  299. # TODO send error message instead
  300. return None
  301. reuploaded = await self._reupload_instagram_media(source, item.visual_media.media,
  302. intent)
  303. elif item.animated_media:
  304. reuploaded = await self._reupload_instagram_animated(source, item.animated_media,
  305. intent)
  306. elif item.voice_media:
  307. reuploaded = await self._reupload_instagram_voice(source, item.voice_media, intent)
  308. elif item.reel_share:
  309. reuploaded = await self._reupload_instagram_media(source, item.reel_share.media,
  310. intent)
  311. elif item.story_share:
  312. reuploaded = await self._reupload_instagram_media(source, item.story_share.media,
  313. intent)
  314. elif item.media_share:
  315. reuploaded = await self._reupload_instagram_media(source, item.media_share, intent)
  316. else:
  317. reuploaded = None
  318. if not reuploaded:
  319. self.log.debug(f"Unsupported media type in item {item}")
  320. return None
  321. content = MediaMessageEventContent(body=reuploaded.file_name, external_url=reuploaded.url,
  322. url=reuploaded.mxc, file=reuploaded.decryption_info,
  323. info=reuploaded.info, msgtype=reuploaded.msgtype)
  324. return await self._send_message(intent, content, timestamp=item.timestamp // 1000)
  325. async def _handle_instagram_media_share(self, source: 'u.User', intent: IntentAPI,
  326. item: ThreadItem) -> Optional[EventID]:
  327. share_item = item.media_share or item.story_share.media
  328. if share_item == item.media_share:
  329. prefix_text = f"Sent {share_item.user.username}'s photo"
  330. else:
  331. prefix_text = f"Sent {share_item.user.username}'s story"
  332. prefix = TextMessageEventContent(msgtype=MessageType.NOTICE, body=prefix_text)
  333. await self._send_message(intent, prefix)
  334. event_id = await self._handle_instagram_media(source, intent, item)
  335. if share_item.caption:
  336. body = f"> {share_item.caption.user.username}: {share_item.caption.text}"
  337. formatted_body = (f"<blockquote><strong>{share_item.caption.user.username}</strong>"
  338. f" {share_item.caption.text}</blockquote>")
  339. caption = TextMessageEventContent(msgtype=MessageType.TEXT, body=body,
  340. formatted_body=formatted_body, format=Format.HTML)
  341. await self._send_message(intent, caption)
  342. return event_id
  343. async def _handle_instagram_reel_share(self, source: 'u.User', intent: IntentAPI,
  344. item: ThreadItem) -> Optional[EventID]:
  345. if item.reel_share.type == ReelShareType.REPLY:
  346. if item.reel_share.reel_owner_id == source.igpk:
  347. prefix = "Replied to your story"
  348. else:
  349. prefix = f"Sent {item.reel_share.media.user.username}'s story"
  350. elif item.reel_share.type == ReelShareType.REACTION:
  351. prefix = "Reacted to your story"
  352. else:
  353. self.log.debug(f"Unsupported reel share type {item.reel_share.type}")
  354. return None
  355. prefix = TextMessageEventContent(msgtype=MessageType.NOTICE, body=prefix)
  356. content = TextMessageEventContent(msgtype=MessageType.TEXT, body=item.text)
  357. await self._send_message(intent, prefix)
  358. fake_item_id = f"fi.mau.instagram.reel_share_item.{item.reel_share.media.pk}"
  359. existing = await DBMessage.get_by_item_id(fake_item_id, self.receiver)
  360. if existing:
  361. # If the user already reacted or replied to the same reel share item,
  362. # use a Matrix reply instead of reposting the image.
  363. content.set_reply(existing.mxid)
  364. else:
  365. media_event_id = await self._handle_instagram_media(source, intent, item)
  366. await DBMessage(mxid=media_event_id, mx_room=self.mxid, item_id=fake_item_id,
  367. receiver=self.receiver, sender=item.reel_share.media.user.pk).insert()
  368. return await self._send_message(intent, content)
  369. async def _handle_instagram_text(self, intent: IntentAPI, text: str, timestamp: int
  370. ) -> EventID:
  371. content = TextMessageEventContent(msgtype=MessageType.TEXT, body=text)
  372. return await self._send_message(intent, content, timestamp=timestamp // 1000)
  373. async def _handle_instagram_location(self, intent: IntentAPI, item: ThreadItem) -> EventID:
  374. loc = item.location
  375. long_char = "E" if loc.lng > 0 else "W"
  376. lat_char = "N" if loc.lat > 0 else "S"
  377. body = (f"{loc.name} - {round(abs(loc.lat), 4)}° {lat_char}, "
  378. f"{round(abs(loc.lng), 4)}° {long_char}")
  379. url = f"https://www.openstreetmap.org/#map=15/{loc.lat}/{loc.lng}"
  380. external_url = None
  381. if loc.external_source == "facebook_places":
  382. external_url = f"https://www.facebook.com/{loc.short_name}-{loc.facebook_places_id}"
  383. content = LocationMessageEventContent(
  384. msgtype=MessageType.LOCATION, geo_uri=f"geo:{loc.lat},{loc.lng}",
  385. body=f"Location: {body}\n{url}", external_url=external_url)
  386. content["format"] = str(Format.HTML)
  387. content["formatted_body"] = f"Location: <a href='{url}'>{body}</a>"
  388. return await self._send_message(intent, content, timestamp=item.timestamp // 1000)
  389. async def handle_instagram_item(self, source: 'u.User', sender: 'p.Puppet', item: ThreadItem,
  390. is_backfill: bool = False) -> None:
  391. try:
  392. await self._handle_instagram_item(source, sender, item, is_backfill)
  393. except Exception:
  394. self.log.exception("Fatal error handling Instagram item")
  395. self.log.trace("Item content: %s", item.serialize())
  396. async def _handle_instagram_item(self, source: 'u.User', sender: 'p.Puppet', item: ThreadItem,
  397. is_backfill: bool = False) -> None:
  398. if item.client_context in self._reqid_dedup:
  399. self.log.debug(f"Ignoring message {item.item_id} by {item.user_id}"
  400. " as it was sent by us (client_context in dedup queue)")
  401. elif item.item_id in self._msgid_dedup:
  402. self.log.debug(f"Ignoring message {item.item_id} by {item.user_id}"
  403. " as it was already handled (message.id in dedup queue)")
  404. elif await DBMessage.get_by_item_id(item.item_id, self.receiver) is not None:
  405. self.log.debug(f"Ignoring message {item.item_id} by {item.user_id}"
  406. " as it was already handled (message.id found in database)")
  407. else:
  408. self._msgid_dedup.appendleft(item.item_id)
  409. if self.backfill_lock.locked and sender.need_backfill_invite(self):
  410. self.log.debug("Adding %s's default puppet to room for backfilling", sender.mxid)
  411. if self.is_direct:
  412. await self.main_intent.invite_user(self.mxid, sender.default_mxid)
  413. intent = sender.default_mxid_intent
  414. await intent.ensure_joined(self.mxid)
  415. self._backfill_leave.add(intent)
  416. else:
  417. intent = sender.intent_for(self)
  418. event_id = None
  419. if item.media or item.animated_media or item.voice_media or item.visual_media:
  420. event_id = await self._handle_instagram_media(source, intent, item)
  421. elif item.location:
  422. event_id = await self._handle_instagram_location(intent, item)
  423. elif item.reel_share:
  424. event_id = await self._handle_instagram_reel_share(source, intent, item)
  425. elif item.media_share or item.story_share:
  426. event_id = await self._handle_instagram_media_share(source, intent, item)
  427. if item.text:
  428. event_id = await self._handle_instagram_text(intent, item.text, item.timestamp)
  429. elif item.like:
  430. # We handle likes as text because Matrix clients do big emoji on their own.
  431. event_id = await self._handle_instagram_text(intent, item.like, item.timestamp)
  432. elif item.link:
  433. event_id = await self._handle_instagram_text(intent, item.link.text,
  434. item.timestamp)
  435. if event_id:
  436. msg = DBMessage(mxid=event_id, mx_room=self.mxid, item_id=item.item_id,
  437. receiver=self.receiver, sender=sender.pk)
  438. await msg.insert()
  439. await self._send_delivery_receipt(event_id)
  440. self.log.debug(f"Handled Instagram message {item.item_id} -> {event_id}")
  441. if is_backfill and item.reactions:
  442. await self._handle_instagram_reactions(msg, item.reactions.emojis)
  443. else:
  444. self.log.debug(f"Unhandled Instagram message {item.item_id}")
  445. async def handle_instagram_remove(self, item_id: str) -> None:
  446. message = await DBMessage.get_by_item_id(item_id, self.receiver)
  447. if message is None:
  448. return
  449. await message.delete()
  450. sender = await p.Puppet.get_by_pk(message.sender)
  451. try:
  452. await sender.intent_for(self).redact(self.mxid, message.mxid)
  453. except MForbidden:
  454. await self.main_intent.redact(self.mxid, message.mxid)
  455. self.log.debug(f"Redacted {message.mxid} after Instagram unsend")
  456. async def _handle_instagram_reactions(self, message: DBMessage, reactions: List[Reaction]
  457. ) -> None:
  458. old_reactions: Dict[int, DBReaction]
  459. old_reactions = {reaction.ig_sender: reaction for reaction
  460. in await DBReaction.get_all_by_item_id(message.item_id, self.receiver)}
  461. for new_reaction in reactions:
  462. old_reaction = old_reactions.pop(new_reaction.sender_id, None)
  463. if old_reaction and old_reaction.reaction == new_reaction.emoji:
  464. continue
  465. puppet = await p.Puppet.get_by_pk(new_reaction.sender_id)
  466. intent = puppet.intent_for(self)
  467. reaction_event_id = await intent.react(self.mxid, message.mxid, new_reaction.emoji)
  468. await self._upsert_reaction(old_reaction, intent, reaction_event_id, message,
  469. puppet, new_reaction.emoji)
  470. for old_reaction in old_reactions.values():
  471. await old_reaction.delete()
  472. puppet = await p.Puppet.get_by_pk(old_reaction.ig_sender)
  473. await puppet.intent_for(self).redact(self.mxid, old_reaction.mxid)
  474. async def handle_instagram_update(self, item: MessageSyncMessage) -> None:
  475. message = await DBMessage.get_by_item_id(item.item_id, self.receiver)
  476. if not message:
  477. return
  478. if item.has_seen:
  479. puppet = await p.Puppet.get_by_pk(item.has_seen, create=False)
  480. if puppet:
  481. await puppet.intent_for(self).mark_read(self.mxid, message.mxid)
  482. else:
  483. async with self._reaction_lock:
  484. await self._handle_instagram_reactions(message, (item.reactions.emojis
  485. if item.reactions else []))
  486. # endregion
  487. # region Updating portal info
  488. async def update_info(self, thread: Thread, source: 'u.User') -> None:
  489. changed = await self._update_name(thread.thread_title)
  490. if changed:
  491. await self.update_bridge_info()
  492. await self.update()
  493. await self._update_participants(thread.users, source)
  494. # TODO update power levels with thread.admin_user_ids
  495. async def _update_name(self, name: str) -> bool:
  496. if self.name != name:
  497. self.name = name
  498. if self.mxid:
  499. await self.main_intent.set_room_name(self.mxid, name)
  500. return True
  501. return False
  502. async def _update_participants(self, users: List[ThreadUser], source: 'u.User') -> None:
  503. if not self.mxid:
  504. return
  505. # Make sure puppets who should be here are here
  506. for user in users:
  507. puppet = await p.Puppet.get_by_pk(user.pk)
  508. await puppet.update_info(user, source)
  509. await puppet.intent_for(self).ensure_joined(self.mxid)
  510. # Kick puppets who shouldn't be here
  511. current_members = {int(user.pk) for user in users}
  512. for user_id in await self.main_intent.get_room_members(self.mxid):
  513. pk = p.Puppet.get_id_from_mxid(user_id)
  514. if pk and pk not in current_members:
  515. await self.main_intent.kick_user(self.mxid, p.Puppet.get_mxid_from_id(pk),
  516. reason="User had left this Instagram DM")
  517. # endregion
  518. # region Backfilling
  519. async def backfill(self, source: 'u.User', is_initial: bool = False) -> None:
  520. limit = (self.config["bridge.backfill.initial_limit"] if is_initial
  521. else self.config["bridge.backfill.missed_limit"])
  522. if limit == 0:
  523. return
  524. elif limit < 0:
  525. limit = None
  526. with self.backfill_lock:
  527. await self._backfill(source, is_initial, limit)
  528. async def _backfill(self, source: 'u.User', is_initial: bool, limit: int) -> None:
  529. self.log.debug("Backfilling history through %s", source.mxid)
  530. entries = await self._fetch_backfill_items(source, is_initial, limit)
  531. if not entries:
  532. self.log.debug("Didn't get any items to backfill from server")
  533. return
  534. self.log.debug("Got %d entries from server", len(entries))
  535. self._backfill_leave = set()
  536. async with NotificationDisabler(self.mxid, source):
  537. for entry in reversed(entries):
  538. sender = await p.Puppet.get_by_pk(int(entry.user_id))
  539. await self.handle_instagram_item(source, sender, entry, is_backfill=True)
  540. for intent in self._backfill_leave:
  541. self.log.trace("Leaving room with %s post-backfill", intent.mxid)
  542. await intent.leave_room(self.mxid)
  543. self._backfill_leave = None
  544. self.log.info("Backfilled %d messages through %s", len(entries), source.mxid)
  545. async def _fetch_backfill_items(self, source: 'u.User', is_initial: bool, limit: int
  546. ) -> List[ThreadItem]:
  547. items = []
  548. self.log.debug("Fetching up to %d messages through %s", limit, source.igpk)
  549. async for item in source.client.iter_thread(self.thread_id):
  550. if len(items) >= limit:
  551. self.log.debug(f"Fetched {len(items)} messages (the limit)")
  552. break
  553. elif not is_initial:
  554. msg = await DBMessage.get_by_item_id(item.item_id, receiver=self.receiver)
  555. if msg is not None:
  556. self.log.debug(f"Fetched {len(items)} messages and hit a message"
  557. " that's already in the database.")
  558. break
  559. items.append(item)
  560. return items
  561. # endregion
  562. # region Bridge info state event
  563. @property
  564. def bridge_info_state_key(self) -> str:
  565. return f"net.maunium.instagram://instagram/{self.thread_id}"
  566. @property
  567. def bridge_info(self) -> Dict[str, Any]:
  568. return {
  569. "bridgebot": self.az.bot_mxid,
  570. "creator": self.main_intent.mxid,
  571. "protocol": {
  572. "id": "instagram",
  573. "displayname": "Instagram DM",
  574. "avatar_url": self.config["appservice.bot_avatar"],
  575. },
  576. "channel": {
  577. "id": self.thread_id,
  578. "displayname": self.name,
  579. }
  580. }
  581. async def update_bridge_info(self) -> None:
  582. if not self.mxid:
  583. self.log.debug("Not updating bridge info: no Matrix room created")
  584. return
  585. try:
  586. self.log.debug("Updating bridge info...")
  587. await self.main_intent.send_state_event(self.mxid, StateBridge,
  588. self.bridge_info, self.bridge_info_state_key)
  589. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  590. await self.main_intent.send_state_event(self.mxid, StateHalfShotBridge,
  591. self.bridge_info, self.bridge_info_state_key)
  592. except Exception:
  593. self.log.warning("Failed to update bridge info", exc_info=True)
  594. # endregion
  595. # region Creating Matrix rooms
  596. async def create_matrix_room(self, source: 'u.User', info: Thread) -> Optional[RoomID]:
  597. if self.mxid:
  598. try:
  599. await self.update_matrix_room(source, info)
  600. except Exception:
  601. self.log.exception("Failed to update portal")
  602. return self.mxid
  603. async with self._create_room_lock:
  604. return await self._create_matrix_room(source, info)
  605. async def update_matrix_room(self, source: 'u.User', info: Thread, backfill: bool = False
  606. ) -> None:
  607. await self.main_intent.invite_user(self.mxid, source.mxid, check_cache=True)
  608. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  609. if puppet:
  610. did_join = await puppet.intent.ensure_joined(self.mxid)
  611. if did_join and self.is_direct:
  612. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  613. await self.update_info(info, source)
  614. if backfill:
  615. last_msg = await DBMessage.get_by_item_id(info.last_permanent_item.item_id,
  616. receiver=self.receiver)
  617. if last_msg is None:
  618. self.log.debug(f"Last permanent item ({info.last_permanent_item.item_id})"
  619. " not found in database, starting backfilling")
  620. await self.backfill(source, is_initial=False)
  621. # TODO
  622. # up = DBUserPortal.get(source.fbid, self.fbid, self.fb_receiver)
  623. # if not up:
  624. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  625. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  626. # in_community=in_community).insert()
  627. # elif not up.in_community:
  628. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  629. # up.edit(in_community=in_community)
  630. async def _create_matrix_room(self, source: 'u.User', info: Thread) -> Optional[RoomID]:
  631. if self.mxid:
  632. await self.update_matrix_room(source, info)
  633. return self.mxid
  634. await self.update_info(info, source)
  635. self.log.debug("Creating Matrix room")
  636. name: Optional[str] = None
  637. initial_state = [{
  638. "type": str(StateBridge),
  639. "state_key": self.bridge_info_state_key,
  640. "content": self.bridge_info,
  641. }, {
  642. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  643. "type": str(StateHalfShotBridge),
  644. "state_key": self.bridge_info_state_key,
  645. "content": self.bridge_info,
  646. }]
  647. invites = [source.mxid]
  648. if self.config["bridge.encryption.default"] and self.matrix.e2ee:
  649. self.encrypted = True
  650. initial_state.append({
  651. "type": "m.room.encryption",
  652. "content": {"algorithm": "m.megolm.v1.aes-sha2"},
  653. })
  654. if self.is_direct:
  655. invites.append(self.az.bot_mxid)
  656. if self.encrypted or self.private_chat_portal_meta or not self.is_direct:
  657. name = self.name
  658. if self.config["appservice.community_id"]:
  659. initial_state.append({
  660. "type": "m.room.related_groups",
  661. "content": {"groups": [self.config["appservice.community_id"]]},
  662. })
  663. # We lock backfill lock here so any messages that come between the room being created
  664. # and the initial backfill finishing wouldn't be bridged before the backfill messages.
  665. with self.backfill_lock:
  666. self.mxid = await self.main_intent.create_room(name=name, is_direct=self.is_direct,
  667. initial_state=initial_state,
  668. invitees=invites)
  669. if not self.mxid:
  670. raise Exception("Failed to create room: no mxid returned")
  671. if self.encrypted and self.matrix.e2ee and self.is_direct:
  672. try:
  673. await self.az.intent.ensure_joined(self.mxid)
  674. except Exception:
  675. self.log.warning("Failed to add bridge bot "
  676. f"to new private chat {self.mxid}")
  677. await self.update()
  678. self.log.debug(f"Matrix room created: {self.mxid}")
  679. self.by_mxid[self.mxid] = self
  680. await self._update_participants(info.users, source)
  681. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  682. if puppet:
  683. try:
  684. await puppet.intent.join_room_by_id(self.mxid)
  685. if self.is_direct:
  686. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  687. except MatrixError:
  688. self.log.debug("Failed to join custom puppet into newly created portal",
  689. exc_info=True)
  690. # TODO
  691. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  692. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  693. # in_community=in_community).upsert()
  694. try:
  695. await self.backfill(source, is_initial=True)
  696. except Exception:
  697. self.log.exception("Failed to backfill new portal")
  698. return self.mxid
  699. # endregion
  700. # region Database getters
  701. async def postinit(self) -> None:
  702. self.by_thread_id[(self.thread_id, self.receiver)] = self
  703. if self.mxid:
  704. self.by_mxid[self.mxid] = self
  705. self._main_intent = ((await p.Puppet.get_by_pk(self.other_user_pk)).default_mxid_intent
  706. if self.other_user_pk else self.az.intent)
  707. async def delete(self) -> None:
  708. await DBMessage.delete_all(self.mxid)
  709. self.by_mxid.pop(self.mxid, None)
  710. self.mxid = None
  711. self.encrypted = False
  712. await self.update()
  713. async def save(self) -> None:
  714. await self.update()
  715. @classmethod
  716. def all_with_room(cls) -> AsyncGenerator['Portal', None]:
  717. return cls._db_to_portals(super().all_with_room())
  718. @classmethod
  719. def find_private_chats_with(cls, other_user: int) -> AsyncGenerator['Portal', None]:
  720. return cls._db_to_portals(super().find_private_chats_with(other_user))
  721. @classmethod
  722. async def _db_to_portals(cls, query: Awaitable[List['Portal']]
  723. ) -> AsyncGenerator['Portal', None]:
  724. portals = await query
  725. for index, portal in enumerate(portals):
  726. try:
  727. yield cls.by_thread_id[(portal.thread_id, portal.receiver)]
  728. except KeyError:
  729. await portal.postinit()
  730. yield portal
  731. @classmethod
  732. async def get_by_mxid(cls, mxid: RoomID) -> Optional['Portal']:
  733. try:
  734. return cls.by_mxid[mxid]
  735. except KeyError:
  736. pass
  737. portal = cast(cls, await super().get_by_mxid(mxid))
  738. if portal is not None:
  739. await portal.postinit()
  740. return portal
  741. return None
  742. @classmethod
  743. async def get_by_thread_id(cls, thread_id: str, receiver: int,
  744. is_group: Optional[bool] = None,
  745. other_user_pk: Optional[int] = None) -> Optional['Portal']:
  746. if is_group and receiver != 0:
  747. receiver = 0
  748. try:
  749. return cls.by_thread_id[(thread_id, receiver)]
  750. except KeyError:
  751. pass
  752. if is_group is None and receiver != 0:
  753. try:
  754. return cls.by_thread_id[(thread_id, 0)]
  755. except KeyError:
  756. pass
  757. portal = cast(cls, await super().get_by_thread_id(thread_id, receiver,
  758. rec_must_match=is_group is not None))
  759. if portal is not None:
  760. await portal.postinit()
  761. return portal
  762. if is_group is not None:
  763. portal = cls(thread_id, receiver, other_user_pk=other_user_pk)
  764. await portal.insert()
  765. await portal.postinit()
  766. return portal
  767. return None
  768. @classmethod
  769. async def get_by_thread(cls, thread: Thread, receiver: int) -> Optional['Portal']:
  770. if thread.is_group:
  771. receiver = 0
  772. other_user_pk = None
  773. else:
  774. other_user_pk = thread.users[0].pk
  775. return await cls.get_by_thread_id(thread.thread_id, receiver, is_group=thread.is_group,
  776. other_user_pk=other_user_pk)
  777. # endregion