portal.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. # mautrix-signal - A Matrix-Signal 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, Any, Union, AsyncGenerator, Awaitable,
  17. TYPE_CHECKING, cast)
  18. from collections import deque
  19. from uuid import UUID, uuid4
  20. import mimetypes
  21. import hashlib
  22. import asyncio
  23. import os.path
  24. import time
  25. import os
  26. from mausignald.types import (Address, MessageData, Reaction, Quote, Group, Contact, Profile,
  27. Attachment, GroupID, GroupV2ID, GroupV2, Mention, Sticker)
  28. from mautrix.appservice import AppService, IntentAPI
  29. from mautrix.bridge import BasePortal
  30. from mautrix.types import (EventID, MessageEventContent, RoomID, EventType, MessageType,
  31. MessageEvent, EncryptedEvent, ContentURI, MediaMessageEventContent,
  32. ImageInfo, VideoInfo, FileInfo, AudioInfo)
  33. from mautrix.errors import MatrixError, MForbidden
  34. from .db import Portal as DBPortal, Message as DBMessage, Reaction as DBReaction
  35. from .config import Config
  36. from .formatter import matrix_to_signal, signal_to_matrix
  37. from . import user as u, puppet as p, matrix as m, signal as s
  38. if TYPE_CHECKING:
  39. from .__main__ import SignalBridge
  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 signalstickers_client import StickersClient
  46. from signalstickers_client.models import StickerPack
  47. except ImportError:
  48. StickersClient = StickerPack = None
  49. try:
  50. import magic
  51. except ImportError:
  52. magic = None
  53. StateBridge = EventType.find("m.bridge", EventType.Class.STATE)
  54. StateHalfShotBridge = EventType.find("uk.half-shot.bridge", EventType.Class.STATE)
  55. ChatInfo = Union[Group, GroupV2, GroupV2ID, Contact, Profile, Address]
  56. class Portal(DBPortal, BasePortal):
  57. by_mxid: Dict[RoomID, 'Portal'] = {}
  58. by_chat_id: Dict[Tuple[str, str], 'Portal'] = {}
  59. _sticker_meta_cache: Dict[str, StickerPack] = {}
  60. config: Config
  61. matrix: 'm.MatrixHandler'
  62. signal: 's.SignalHandler'
  63. az: AppService
  64. private_chat_portal_meta: bool
  65. _main_intent: Optional[IntentAPI]
  66. _create_room_lock: asyncio.Lock
  67. _msgts_dedup: Deque[Tuple[Address, int]]
  68. _reaction_dedup: Deque[Tuple[Address, int, str]]
  69. _reaction_lock: asyncio.Lock
  70. def __init__(self, chat_id: Union[GroupID, Address], receiver: str,
  71. mxid: Optional[RoomID] = None, name: Optional[str] = None,
  72. avatar_hash: Optional[str] = None, avatar_url: Optional[ContentURI] = None,
  73. encrypted: bool = False) -> None:
  74. super().__init__(chat_id, receiver, mxid, name, avatar_hash, avatar_url, encrypted)
  75. self._create_room_lock = asyncio.Lock()
  76. self.log = self.log.getChild(self.chat_id_str)
  77. self._main_intent = None
  78. self._msgts_dedup = deque(maxlen=100)
  79. self._reaction_dedup = deque(maxlen=100)
  80. self._last_participant_update = set()
  81. self._reaction_lock = asyncio.Lock()
  82. @property
  83. def main_intent(self) -> IntentAPI:
  84. if not self._main_intent:
  85. raise ValueError("Portal must be postinit()ed before main_intent can be used")
  86. return self._main_intent
  87. @property
  88. def is_direct(self) -> bool:
  89. return isinstance(self.chat_id, Address)
  90. def handle_uuid_receive(self, uuid: UUID) -> None:
  91. if not self.is_direct or self.chat_id.uuid:
  92. raise ValueError("handle_uuid_receive can only be used for private chat portals with "
  93. "a phone number chat_id")
  94. del self.by_chat_id[(self.chat_id_str, self.receiver)]
  95. self.chat_id = Address(uuid=uuid)
  96. self.by_chat_id[(self.chat_id_str, self.receiver)] = self
  97. @classmethod
  98. def init_cls(cls, bridge: 'SignalBridge') -> None:
  99. cls.config = bridge.config
  100. cls.matrix = bridge.matrix
  101. cls.signal = bridge.signal
  102. cls.az = bridge.az
  103. cls.loop = bridge.loop
  104. BasePortal.bridge = bridge
  105. cls.private_chat_portal_meta = cls.config["bridge.private_chat_portal_meta"]
  106. # region Misc
  107. async def _send_delivery_receipt(self, event_id: EventID) -> None:
  108. if event_id and self.config["bridge.delivery_receipts"]:
  109. try:
  110. await self.az.intent.mark_read(self.mxid, event_id)
  111. except Exception:
  112. self.log.exception("Failed to send delivery receipt for %s", event_id)
  113. async def _upsert_reaction(self, existing: DBReaction, intent: IntentAPI, mxid: EventID,
  114. sender: Union['p.Puppet', 'u.User'], message: DBMessage, emoji: str
  115. ) -> None:
  116. if existing:
  117. self.log.debug(f"_upsert_reaction redacting {existing.mxid} and inserting {mxid}"
  118. f" (message: {message.mxid})")
  119. try:
  120. await intent.redact(existing.mx_room, existing.mxid)
  121. except MForbidden:
  122. self.log.debug("Unexpected MForbidden redacting reaction", exc_info=True)
  123. await existing.edit(emoji=emoji, mxid=mxid, mx_room=message.mx_room)
  124. else:
  125. self.log.debug(f"_upsert_reaction inserting {mxid} (message: {message.mxid})")
  126. await DBReaction(mxid=mxid, mx_room=message.mx_room, emoji=emoji,
  127. signal_chat_id=self.chat_id, signal_receiver=self.receiver,
  128. msg_author=message.sender, msg_timestamp=message.timestamp,
  129. author=sender.address).insert()
  130. # endregion
  131. # region Matrix event handling
  132. @staticmethod
  133. def _make_attachment(message: MediaMessageEventContent, path: str) -> Attachment:
  134. attachment = Attachment(custom_filename=message.body, content_type=message.info.mimetype,
  135. outgoing_filename=path)
  136. info = message.info
  137. attachment.width = info.get("w", info.get("width", 0))
  138. attachment.height = info.get("h", info.get("height", 0))
  139. attachment.voice_note = message.msgtype == MessageType.AUDIO
  140. return attachment
  141. async def _download_matrix_media(self, message: MediaMessageEventContent) -> str:
  142. if message.file:
  143. data = await self.main_intent.download_media(message.file.url)
  144. data = decrypt_attachment(data, message.file.key.key,
  145. message.file.hashes.get("sha256"), message.file.iv)
  146. else:
  147. data = await self.main_intent.download_media(message.url)
  148. path = os.path.join(self.config["signal.outgoing_attachment_dir"],
  149. f"mautrix-signal-{str(uuid4())}")
  150. with open(path, "wb") as file:
  151. file.write(data)
  152. return path
  153. async def handle_matrix_message(self, sender: 'u.User', message: MessageEventContent,
  154. event_id: EventID) -> None:
  155. if ((message.get(self.bridge.real_user_content_key, False)
  156. and await p.Puppet.get_by_custom_mxid(sender.mxid))):
  157. self.log.debug(f"Ignoring puppet-sent message by confirmed puppet user {sender.mxid}")
  158. return
  159. request_id = int(time.time() * 1000)
  160. self._msgts_dedup.appendleft((sender.address, request_id))
  161. quote = None
  162. if message.get_reply_to():
  163. reply = await DBMessage.get_by_mxid(message.get_reply_to(), self.mxid)
  164. # TODO include actual text? either store in db or fetch event from homeserver
  165. if reply is not None:
  166. quote = Quote(id=reply.timestamp, author=reply.sender, text="")
  167. attachments: Optional[List[Attachment]] = None
  168. attachment_path: Optional[str] = None
  169. mentions: Optional[List[Mention]] = None
  170. if message.msgtype.is_text:
  171. text, mentions = await matrix_to_signal(message)
  172. elif message.msgtype.is_media:
  173. attachment_path = await self._download_matrix_media(message)
  174. attachment = self._make_attachment(message, attachment_path)
  175. attachments = [attachment]
  176. text = None
  177. self.log.trace("Formed outgoing attachment %s", attachment)
  178. else:
  179. self.log.debug(f"Unknown msgtype {message.msgtype} in Matrix message {event_id}")
  180. return
  181. await self.signal.send(username=sender.username, recipient=self.chat_id, body=text,
  182. mentions=mentions, quote=quote, attachments=attachments,
  183. timestamp=request_id)
  184. msg = DBMessage(mxid=event_id, mx_room=self.mxid, sender=sender.address,
  185. timestamp=request_id,
  186. signal_chat_id=self.chat_id, signal_receiver=self.receiver)
  187. await msg.insert()
  188. await self._send_delivery_receipt(event_id)
  189. self.log.debug(f"Handled Matrix message {event_id} -> {request_id}")
  190. if attachment_path and self.config["signal.remove_file_after_handling"]:
  191. try:
  192. os.remove(attachment_path)
  193. except FileNotFoundError:
  194. pass
  195. async def handle_matrix_reaction(self, sender: 'u.User', event_id: EventID,
  196. reacting_to: EventID, emoji: str) -> None:
  197. # Signal doesn't seem to use variation selectors at all
  198. emoji = emoji.rstrip("\ufe0f")
  199. message = await DBMessage.get_by_mxid(reacting_to, self.mxid)
  200. if not message:
  201. self.log.debug(f"Ignoring reaction to unknown event {reacting_to}")
  202. return
  203. existing = await DBReaction.get_by_signal_id(self.chat_id, self.receiver, message.sender,
  204. message.timestamp, sender.address)
  205. if existing and existing.emoji == emoji:
  206. return
  207. dedup_id = (message.sender, message.timestamp, emoji)
  208. self._reaction_dedup.appendleft(dedup_id)
  209. async with self._reaction_lock:
  210. reaction = Reaction(emoji=emoji, remove=False,
  211. target_author=message.sender,
  212. target_sent_timestamp=message.timestamp)
  213. await self.signal.react(username=sender.username, recipient=self.chat_id,
  214. reaction=reaction)
  215. await self._upsert_reaction(existing, self.main_intent, event_id, sender, message,
  216. emoji)
  217. self.log.trace(f"{sender.mxid} reacted to {message.timestamp} with {emoji}")
  218. await self._send_delivery_receipt(event_id)
  219. async def handle_matrix_redaction(self, sender: 'u.User', event_id: EventID,
  220. redaction_event_id: EventID) -> None:
  221. if not self.mxid:
  222. return
  223. # TODO message redactions after https://gitlab.com/signald/signald/-/issues/37
  224. reaction = await DBReaction.get_by_mxid(event_id, self.mxid)
  225. if reaction:
  226. try:
  227. await reaction.delete()
  228. remove_reaction = Reaction(emoji=reaction.emoji, remove=True,
  229. target_author=reaction.msg_author,
  230. target_sent_timestamp=reaction.msg_timestamp)
  231. await self.signal.react(username=sender.username, recipient=self.chat_id,
  232. reaction=remove_reaction)
  233. await self._send_delivery_receipt(redaction_event_id)
  234. self.log.trace(f"Removed {reaction} after Matrix redaction")
  235. except Exception:
  236. self.log.exception("Removing reaction failed")
  237. async def handle_matrix_leave(self, user: 'u.User') -> None:
  238. if self.is_direct:
  239. self.log.info(f"{user.mxid} left private chat portal with {self.chat_id}")
  240. if user.username == self.receiver:
  241. self.log.info(f"{user.mxid} was the recipient of this portal. "
  242. "Cleaning up and deleting...")
  243. await self.cleanup_and_delete()
  244. else:
  245. self.log.debug(f"{user.mxid} left portal to {self.chat_id}")
  246. # TODO cleanup if empty
  247. # endregion
  248. # region Signal event handling
  249. @staticmethod
  250. async def _resolve_address(address: Address) -> Address:
  251. puppet = await p.Puppet.get_by_address(address, create=False)
  252. return puppet.address
  253. async def _find_quote_event_id(self, quote: Optional[Quote]
  254. ) -> Optional[Union[MessageEvent, EventID]]:
  255. if not quote:
  256. return None
  257. author_address = await self._resolve_address(quote.author)
  258. reply_msg = await DBMessage.get_by_signal_id(author_address, quote.id,
  259. self.chat_id, self.receiver)
  260. if not reply_msg:
  261. return None
  262. try:
  263. evt = await self.main_intent.get_event(self.mxid, reply_msg.mxid)
  264. if isinstance(evt, EncryptedEvent):
  265. return await self.matrix.e2ee.decrypt(evt, wait_session_timeout=0)
  266. return evt
  267. except MatrixError:
  268. return reply_msg.mxid
  269. async def handle_signal_message(self, source: 'u.User', sender: 'p.Puppet',
  270. message: MessageData) -> None:
  271. if (sender.address, message.timestamp) in self._msgts_dedup:
  272. self.log.debug(f"Ignoring message {message.timestamp} by {sender.uuid}"
  273. " as it was already handled (message.timestamp in dedup queue)")
  274. await self.signal.send_receipt(source.username, sender.address,
  275. timestamps=[message.timestamp])
  276. return
  277. old_message = await DBMessage.get_by_signal_id(sender.address, message.timestamp,
  278. self.chat_id, self.receiver)
  279. if old_message is not None:
  280. self.log.debug(f"Ignoring message {message.timestamp} by {sender.uuid}"
  281. " as it was already handled (message.id found in database)")
  282. await self.signal.send_receipt(source.username, sender.address,
  283. timestamps=[message.timestamp])
  284. return
  285. self.log.debug(f"Started handling message {message.timestamp} by {sender.uuid}")
  286. self.log.trace(f"Message content: {message}")
  287. self._msgts_dedup.appendleft((sender.address, message.timestamp))
  288. intent = sender.intent_for(self)
  289. await intent.set_typing(self.mxid, False)
  290. event_id = None
  291. reply_to = await self._find_quote_event_id(message.quote)
  292. if message.sticker:
  293. if message.sticker.attachment.incoming_filename:
  294. content = await self._handle_signal_attachment(intent, message.sticker.attachment)
  295. elif StickersClient:
  296. content = await self._handle_signal_sticker(intent, message.sticker)
  297. else:
  298. self.log.debug(f"Not handling sticker in {message.timestamp}: no incoming_filename"
  299. " and signalstickers-client not installed.")
  300. return
  301. if content:
  302. if message.sticker.attachment.blurhash:
  303. content.info["blurhash"] = message.sticker.attachment.blurhash
  304. content.info["xyz.amorgan.blurhash"] = message.sticker.attachment.blurhash
  305. await self._add_sticker_meta(message.sticker, content)
  306. if reply_to and not message.body:
  307. content.set_reply(reply_to)
  308. reply_to = None
  309. event_id = await self._send_message(intent, content, timestamp=message.timestamp,
  310. event_type=EventType.STICKER)
  311. for attachment in message.attachments:
  312. if not attachment.incoming_filename:
  313. self.log.warning("Failed to bridge attachment, no incoming filename: %s",
  314. attachment)
  315. continue
  316. content = await self._handle_signal_attachment(intent, attachment)
  317. if reply_to and not message.body:
  318. # If there's no text, set the first image as the reply
  319. content.set_reply(reply_to)
  320. reply_to = None
  321. event_id = await self._send_message(intent, content, timestamp=message.timestamp)
  322. if message.body:
  323. content = await signal_to_matrix(message)
  324. if reply_to:
  325. content.set_reply(reply_to)
  326. event_id = await self._send_message(intent, content, timestamp=message.timestamp)
  327. if event_id:
  328. msg = DBMessage(mxid=event_id, mx_room=self.mxid,
  329. sender=sender.address, timestamp=message.timestamp,
  330. signal_chat_id=self.chat_id, signal_receiver=self.receiver)
  331. await msg.insert()
  332. await self.signal.send_receipt(source.username, sender.address,
  333. timestamps=[message.timestamp])
  334. await self._send_delivery_receipt(event_id)
  335. self.log.debug(f"Handled Signal message {message.timestamp} -> {event_id}")
  336. else:
  337. self.log.debug(f"Didn't get event ID for {message.timestamp}")
  338. @staticmethod
  339. def _make_media_content(attachment: Attachment) -> MediaMessageEventContent:
  340. if attachment.content_type.startswith("image/"):
  341. msgtype = MessageType.IMAGE
  342. info = ImageInfo(mimetype=attachment.content_type,
  343. width=attachment.width, height=attachment.height)
  344. elif attachment.content_type.startswith("video/"):
  345. msgtype = MessageType.VIDEO
  346. info = VideoInfo(mimetype=attachment.content_type,
  347. width=attachment.width, height=attachment.height)
  348. elif attachment.voice_note or attachment.content_type.startswith("audio/"):
  349. msgtype = MessageType.AUDIO
  350. info = AudioInfo(mimetype=attachment.content_type)
  351. else:
  352. msgtype = MessageType.FILE
  353. info = FileInfo(mimetype=attachment.content_type)
  354. if not attachment.custom_filename:
  355. ext = mimetypes.guess_extension(attachment.content_type) or ""
  356. attachment.custom_filename = attachment.id + ext
  357. if attachment.blurhash:
  358. info["blurhash"] = attachment.blurhash
  359. info["xyz.amorgan.blurhash"] = attachment.blurhash
  360. return MediaMessageEventContent(msgtype=msgtype, info=info,
  361. body=attachment.custom_filename)
  362. async def _handle_signal_attachment(self, intent: IntentAPI, attachment: Attachment
  363. ) -> MediaMessageEventContent:
  364. self.log.trace(f"Reuploading attachment {attachment}")
  365. if not attachment.content_type:
  366. attachment.content_type = (magic.from_file(attachment.incoming_filename, mime=True)
  367. if magic is not None else "application/octet-stream")
  368. content = self._make_media_content(attachment)
  369. with open(attachment.incoming_filename, "rb") as file:
  370. data = file.read()
  371. if self.config["signal.remove_file_after_handling"]:
  372. os.remove(attachment.incoming_filename)
  373. await self._upload_attachment(intent, content, data, attachment.id)
  374. return content
  375. async def _add_sticker_meta(self, sticker: Sticker, content: MediaMessageEventContent) -> None:
  376. try:
  377. pack = self._sticker_meta_cache[sticker.pack_id]
  378. except KeyError:
  379. self.log.debug(f"Fetching sticker pack metadata for {sticker.pack_id}")
  380. try:
  381. async with StickersClient() as client:
  382. pack = await client.get_pack_metadata(sticker.pack_id, sticker.pack_key)
  383. self._sticker_meta_cache[sticker.pack_id] = pack
  384. except Exception:
  385. self.log.warning(f"Failed to fetch pack metadata for {sticker.pack_id}",
  386. exc_info=True)
  387. pack = None
  388. if not pack:
  389. content.info["fi.mau.signal.sticker"] = {
  390. "id": sticker.sticker_id,
  391. "pack": {
  392. "id": sticker.pack_id,
  393. "key": sticker.pack_key,
  394. },
  395. }
  396. return
  397. sticker_meta = pack.stickers[sticker.sticker_id]
  398. content.body = sticker_meta.emoji
  399. content.info["fi.mau.signal.sticker"] = {
  400. "id": sticker.sticker_id,
  401. "emoji": sticker_meta.emoji,
  402. "pack": {
  403. "id": pack.id,
  404. "key": pack.key,
  405. "title": pack.title,
  406. "author": pack.author,
  407. },
  408. }
  409. async def _handle_signal_sticker(self, intent: IntentAPI, sticker: Sticker
  410. ) -> Optional[MediaMessageEventContent]:
  411. try:
  412. self.log.debug(f"Fetching sticker {sticker.pack_id}#{sticker.sticker_id}")
  413. async with StickersClient() as client:
  414. data = await client.download_sticker(sticker.sticker_id,
  415. sticker.pack_id, sticker.pack_key)
  416. except Exception:
  417. self.log.warning(f"Failed to download sticker {sticker.sticker_id}", exc_info=True)
  418. return None
  419. info = ImageInfo(mimetype=sticker.attachment.content_type, size=len(data),
  420. width=sticker.attachment.width, height=sticker.attachment.height)
  421. if info.width > 256 or info.height > 256:
  422. if info.width == info.height:
  423. info.width = info.height = 256
  424. elif info.width > info.height:
  425. info.height = int(info.height / (info.width / 256))
  426. info.width = 256
  427. else:
  428. info.width = int(info.width / (info.height / 256))
  429. info.height = 256
  430. if magic:
  431. info.mimetype = magic.from_buffer(data, mime=True)
  432. ext = mimetypes.guess_extension(info.mimetype)
  433. if not ext and info.mimetype == "image/webp":
  434. ext = ".webp"
  435. content = MediaMessageEventContent(msgtype=MessageType.IMAGE, info=info,
  436. body=f"sticker{ext}")
  437. await self._upload_attachment(intent, content, data, sticker.attachment.id)
  438. return content
  439. async def _upload_attachment(self, intent: IntentAPI, content: MediaMessageEventContent,
  440. data: bytes, id: str) -> None:
  441. upload_mime_type = content.info.mimetype
  442. if self.encrypted and encrypt_attachment:
  443. data, content.file = encrypt_attachment(data)
  444. upload_mime_type = "application/octet-stream"
  445. content.url = await intent.upload_media(data, mime_type=upload_mime_type, filename=id)
  446. if content.file:
  447. content.file.url = content.url
  448. # fix ios bug
  449. if content.info.mimetype.startswith("image/"):
  450. content.info.thumbnail_file = content.file
  451. content.url = None
  452. async def handle_signal_reaction(self, sender: 'p.Puppet', reaction: Reaction) -> None:
  453. author_address = await self._resolve_address(reaction.target_author)
  454. target_id = reaction.target_sent_timestamp
  455. async with self._reaction_lock:
  456. dedup_id = (author_address, target_id, reaction.emoji)
  457. if dedup_id in self._reaction_dedup:
  458. return
  459. self._reaction_dedup.appendleft(dedup_id)
  460. existing = await DBReaction.get_by_signal_id(self.chat_id, self.receiver,
  461. author_address, target_id, sender.address)
  462. if reaction.remove:
  463. if existing:
  464. try:
  465. await sender.intent_for(self).redact(existing.mx_room, existing.mxid)
  466. except MForbidden:
  467. await self.main_intent.redact(existing.mx_room, existing.mxid)
  468. await existing.delete()
  469. self.log.trace(f"Removed {existing} after Signal removal")
  470. return
  471. elif existing and existing.emoji == reaction.emoji:
  472. return
  473. message = await DBMessage.get_by_signal_id(author_address, target_id,
  474. self.chat_id, self.receiver)
  475. if not message:
  476. self.log.debug(f"Ignoring reaction to unknown message {target_id}")
  477. return
  478. intent = sender.intent_for(self)
  479. # TODO add variation selectors to emoji before sending to Matrix
  480. mxid = await intent.react(message.mx_room, message.mxid, reaction.emoji)
  481. self.log.debug(f"{sender.address} reacted to {message.mxid} -> {mxid}")
  482. await self._upsert_reaction(existing, intent, mxid, sender, message, reaction.emoji)
  483. async def handle_signal_delete(self, sender: 'p.Puppet', message_ts: int) -> None:
  484. message = await DBMessage.get_by_signal_id(sender.address, message_ts,
  485. self.chat_id, self.receiver)
  486. if not message:
  487. return
  488. await message.delete()
  489. try:
  490. await sender.intent_for(self).redact(message.mx_room, message.mxid)
  491. except MForbidden:
  492. await self.main_intent.redact(message.mx_room, message.mxid)
  493. # endregion
  494. # region Updating portal info
  495. async def update_info(self, source: 'u.User', info: ChatInfo) -> None:
  496. if self.is_direct:
  497. if not isinstance(info, (Contact, Profile, Address)):
  498. raise ValueError(f"Unexpected type for direct chat update_info: {type(info)}")
  499. if not self.name:
  500. puppet = await p.Puppet.get_by_address(self.chat_id)
  501. if not puppet.name:
  502. await puppet.update_info(info)
  503. self.name = puppet.name
  504. return
  505. if isinstance(info, Group):
  506. changed = await self._update_name(info.name)
  507. elif isinstance(info, GroupV2):
  508. changed = await self._update_name(info.title)
  509. elif isinstance(info, GroupV2ID):
  510. return
  511. else:
  512. raise ValueError(f"Unexpected type for group update_info: {type(info)}")
  513. changed = await self._update_avatar(info) or changed
  514. await self._update_participants(source, info.members)
  515. if changed:
  516. await self.update_bridge_info()
  517. await self.update()
  518. async def update_puppet_avatar(self, new_hash: str, avatar_url: ContentURI) -> None:
  519. if not self.encrypted and not self.private_chat_portal_meta:
  520. return
  521. if self.avatar_hash != new_hash:
  522. self.avatar_hash = new_hash
  523. self.avatar_url = avatar_url
  524. if self.mxid:
  525. await self.main_intent.set_room_avatar(self.mxid, avatar_url)
  526. await self.update_bridge_info()
  527. await self.update()
  528. async def update_puppet_name(self, name: str) -> None:
  529. if not self.encrypted and not self.private_chat_portal_meta:
  530. return
  531. changed = await self._update_name(name)
  532. if changed:
  533. await self.update_bridge_info()
  534. await self.update()
  535. async def _update_name(self, name: str) -> bool:
  536. if self.name != name:
  537. self.name = name
  538. if self.mxid:
  539. await self.main_intent.set_room_name(self.mxid, name)
  540. return True
  541. return False
  542. async def _update_avatar(self, info: ChatInfo) -> bool:
  543. path = None
  544. if isinstance(info, GroupV2):
  545. path = info.avatar
  546. elif isinstance(info, Group):
  547. path = os.path.join(self.config["signal.avatar_dir"], f"group-{self.chat_id}")
  548. if not path:
  549. return False
  550. try:
  551. with open(path, "rb") as file:
  552. data = file.read()
  553. except FileNotFoundError:
  554. return False
  555. new_hash = hashlib.sha256(data).hexdigest()
  556. if self.avatar_hash and new_hash == self.avatar_hash:
  557. return False
  558. mxc = await self.main_intent.upload_media(data)
  559. if self.mxid:
  560. await self.main_intent.set_room_avatar(self.mxid, mxc)
  561. self.avatar_url = mxc
  562. self.avatar_hash = new_hash
  563. return True
  564. async def _update_participants(self, source: 'u.User', participants: List[Address]) -> None:
  565. # TODO add support for pending_members and maybe requesting_members?
  566. if not self.mxid or not participants:
  567. return
  568. for address in participants:
  569. puppet = await p.Puppet.get_by_address(address)
  570. if not puppet.name:
  571. await source.sync_contact(address)
  572. await puppet.intent_for(self).ensure_joined(self.mxid)
  573. # endregion
  574. # region Bridge info state event
  575. @property
  576. def bridge_info_state_key(self) -> str:
  577. return f"net.maunium.signal://signal/{self.chat_id}"
  578. @property
  579. def bridge_info(self) -> Dict[str, Any]:
  580. return {
  581. "bridgebot": self.az.bot_mxid,
  582. "creator": self.main_intent.mxid,
  583. "protocol": {
  584. "id": "signal",
  585. "displayname": "Signal",
  586. "avatar_url": self.config["appservice.bot_avatar"],
  587. },
  588. "channel": {
  589. "id": str(self.chat_id),
  590. "displayname": self.name,
  591. "avatar_url": self.avatar_url,
  592. }
  593. }
  594. async def update_bridge_info(self) -> None:
  595. if not self.mxid:
  596. self.log.debug("Not updating bridge info: no Matrix room created")
  597. return
  598. try:
  599. self.log.debug("Updating bridge info...")
  600. await self.main_intent.send_state_event(self.mxid, StateBridge,
  601. self.bridge_info, self.bridge_info_state_key)
  602. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  603. await self.main_intent.send_state_event(self.mxid, StateHalfShotBridge,
  604. self.bridge_info, self.bridge_info_state_key)
  605. except Exception:
  606. self.log.warning("Failed to update bridge info", exc_info=True)
  607. # endregion
  608. # region Creating Matrix rooms
  609. async def update_matrix_room(self, source: 'u.User', info: ChatInfo) -> None:
  610. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  611. raise ValueError(f"Unexpected type for updating group portal: {type(info)}")
  612. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  613. raise ValueError(f"Unexpected type for updating direct chat portal: {type(info)}")
  614. try:
  615. await self._update_matrix_room(source, info)
  616. except Exception:
  617. self.log.exception("Failed to update portal")
  618. async def create_matrix_room(self, source: 'u.User', info: ChatInfo) -> Optional[RoomID]:
  619. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  620. raise ValueError(f"Unexpected type for creating group portal: {type(info)}")
  621. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  622. raise ValueError(f"Unexpected type for creating direct chat portal: {type(info)}")
  623. if isinstance(info, Group) and not info.members:
  624. groups = await self.signal.list_groups(source.username)
  625. info = next((g for g in groups
  626. if isinstance(g, Group) and g.group_id == info.group_id), info)
  627. elif isinstance(info, GroupV2ID):
  628. groups = await self.signal.list_groups(source.username)
  629. try:
  630. info = next(g for g in groups if isinstance(g, GroupV2) and g.id == info.id)
  631. except StopIteration as e:
  632. raise ValueError("Couldn't get full group v2 info") from e
  633. if self.mxid:
  634. await self.update_matrix_room(source, info)
  635. return self.mxid
  636. async with self._create_room_lock:
  637. return await self._create_matrix_room(source, info)
  638. async def _update_matrix_room(self, source: 'u.User', info: ChatInfo) -> None:
  639. await self.main_intent.invite_user(self.mxid, source.mxid, check_cache=True)
  640. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  641. if puppet:
  642. did_join = await puppet.intent.ensure_joined(self.mxid)
  643. if did_join and self.is_direct:
  644. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  645. await self.update_info(source, info)
  646. # TODO
  647. # up = DBUserPortal.get(source.fbid, self.fbid, self.fb_receiver)
  648. # if not up:
  649. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  650. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  651. # in_community=in_community).insert()
  652. # elif not up.in_community:
  653. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  654. # up.edit(in_community=in_community)
  655. async def _create_matrix_room(self, source: 'u.User', info: ChatInfo) -> Optional[RoomID]:
  656. if self.mxid:
  657. await self._update_matrix_room(source, info)
  658. return self.mxid
  659. await self.update_info(source, info)
  660. self.log.debug("Creating Matrix room")
  661. name: Optional[str] = None
  662. initial_state = [{
  663. "type": str(StateBridge),
  664. "state_key": self.bridge_info_state_key,
  665. "content": self.bridge_info,
  666. }, {
  667. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  668. "type": str(StateHalfShotBridge),
  669. "state_key": self.bridge_info_state_key,
  670. "content": self.bridge_info,
  671. }]
  672. invites = [source.mxid]
  673. if self.config["bridge.encryption.default"] and self.matrix.e2ee:
  674. self.encrypted = True
  675. initial_state.append({
  676. "type": str(EventType.ROOM_ENCRYPTION),
  677. "content": {"algorithm": "m.megolm.v1.aes-sha2"},
  678. })
  679. if self.is_direct:
  680. invites.append(self.az.bot_mxid)
  681. if self.is_direct and source.address == self.chat_id:
  682. name = self.name = "Signal Note to Self"
  683. elif self.encrypted or self.private_chat_portal_meta or not self.is_direct:
  684. name = self.name
  685. if self.avatar_url:
  686. initial_state.append({
  687. "type": str(EventType.ROOM_AVATAR),
  688. "content": {"url": self.avatar_url},
  689. })
  690. if self.config["appservice.community_id"]:
  691. initial_state.append({
  692. "type": "m.room.related_groups",
  693. "content": {"groups": [self.config["appservice.community_id"]]},
  694. })
  695. if self.is_direct:
  696. initial_state.append({
  697. "type": str(EventType.ROOM_POWER_LEVELS),
  698. "content": {"users": {self.main_intent.mxid: 100},
  699. "events": {"m.room.avatar": 0, "m.room.name": 0}}
  700. })
  701. self.mxid = await self.main_intent.create_room(name=name, is_direct=self.is_direct,
  702. initial_state=initial_state,
  703. invitees=invites)
  704. if not self.mxid:
  705. raise Exception("Failed to create room: no mxid returned")
  706. if self.encrypted and self.matrix.e2ee and self.is_direct:
  707. try:
  708. await self.az.intent.ensure_joined(self.mxid)
  709. except Exception:
  710. self.log.warning("Failed to add bridge bot "
  711. f"to new private chat {self.mxid}")
  712. await self.update()
  713. self.log.debug(f"Matrix room created: {self.mxid}")
  714. self.by_mxid[self.mxid] = self
  715. if not self.is_direct:
  716. await self._update_participants(source, info.members)
  717. else:
  718. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  719. if puppet:
  720. try:
  721. await puppet.intent.join_room_by_id(self.mxid)
  722. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  723. except MatrixError:
  724. self.log.debug("Failed to join custom puppet into newly created portal",
  725. exc_info=True)
  726. # TODO
  727. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  728. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  729. # in_community=in_community).upsert()
  730. return self.mxid
  731. # endregion
  732. # region Database getters
  733. async def _postinit(self) -> None:
  734. self.by_chat_id[(self.chat_id, self.receiver)] = self
  735. if self.mxid:
  736. self.by_mxid[self.mxid] = self
  737. if self.is_direct:
  738. puppet = await p.Puppet.get_by_address(self.chat_id)
  739. self._main_intent = puppet.default_mxid_intent
  740. elif not self.is_direct:
  741. self._main_intent = self.az.intent
  742. async def delete(self) -> None:
  743. await DBMessage.delete_all(self.mxid)
  744. self.by_mxid.pop(self.mxid, None)
  745. self.mxid = None
  746. self.encrypted = False
  747. await self.update()
  748. async def save(self) -> None:
  749. await self.update()
  750. @classmethod
  751. def all_with_room(cls) -> AsyncGenerator['Portal', None]:
  752. return cls._db_to_portals(super().all_with_room())
  753. @classmethod
  754. def find_private_chats_with(cls, other_user: Address) -> AsyncGenerator['Portal', None]:
  755. return cls._db_to_portals(super().find_private_chats_with(other_user))
  756. @classmethod
  757. async def _db_to_portals(cls, query: Awaitable[List['Portal']]
  758. ) -> AsyncGenerator['Portal', None]:
  759. portals = await query
  760. for index, portal in enumerate(portals):
  761. try:
  762. yield cls.by_chat_id[(portal.chat_id_str, portal.receiver)]
  763. except KeyError:
  764. await portal._postinit()
  765. yield portal
  766. @classmethod
  767. async def get_by_mxid(cls, mxid: RoomID) -> Optional['Portal']:
  768. try:
  769. return cls.by_mxid[mxid]
  770. except KeyError:
  771. pass
  772. portal = cast(cls, await super().get_by_mxid(mxid))
  773. if portal is not None:
  774. await portal._postinit()
  775. return portal
  776. return None
  777. @classmethod
  778. async def get_by_chat_id(cls, chat_id: Union[GroupID, Address], receiver: str = "",
  779. create: bool = False) -> Optional['Portal']:
  780. if isinstance(chat_id, str):
  781. receiver = ""
  782. elif not isinstance(chat_id, Address):
  783. raise ValueError(f"Invalid chat ID type {type(chat_id)}")
  784. elif not receiver:
  785. raise ValueError("Direct chats must have a receiver")
  786. try:
  787. best_id = chat_id.best_identifier if isinstance(chat_id, Address) else chat_id
  788. return cls.by_chat_id[(best_id, receiver)]
  789. except KeyError:
  790. pass
  791. portal = cast(cls, await super().get_by_chat_id(chat_id, receiver))
  792. if portal is not None:
  793. await portal._postinit()
  794. return portal
  795. if create:
  796. portal = cls(chat_id, receiver)
  797. await portal.insert()
  798. await portal._postinit()
  799. return portal
  800. return None
  801. # endregion