portal.py 43 KB

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