portal.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  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. content.url = None
  449. async def handle_signal_reaction(self, sender: 'p.Puppet', reaction: Reaction) -> None:
  450. author_address = await self._resolve_address(reaction.target_author)
  451. target_id = reaction.target_sent_timestamp
  452. async with self._reaction_lock:
  453. dedup_id = (author_address, target_id, reaction.emoji)
  454. if dedup_id in self._reaction_dedup:
  455. return
  456. self._reaction_dedup.appendleft(dedup_id)
  457. existing = await DBReaction.get_by_signal_id(self.chat_id, self.receiver,
  458. author_address, target_id, sender.address)
  459. if reaction.remove:
  460. if existing:
  461. try:
  462. await sender.intent_for(self).redact(existing.mx_room, existing.mxid)
  463. except MForbidden:
  464. await self.main_intent.redact(existing.mx_room, existing.mxid)
  465. await existing.delete()
  466. self.log.trace(f"Removed {existing} after Signal removal")
  467. return
  468. elif existing and existing.emoji == reaction.emoji:
  469. return
  470. message = await DBMessage.get_by_signal_id(author_address, target_id,
  471. self.chat_id, self.receiver)
  472. if not message:
  473. self.log.debug(f"Ignoring reaction to unknown message {target_id}")
  474. return
  475. intent = sender.intent_for(self)
  476. # TODO add variation selectors to emoji before sending to Matrix
  477. mxid = await intent.react(message.mx_room, message.mxid, reaction.emoji)
  478. self.log.debug(f"{sender.address} reacted to {message.mxid} -> {mxid}")
  479. await self._upsert_reaction(existing, intent, mxid, sender, message, reaction.emoji)
  480. async def handle_signal_delete(self, sender: 'p.Puppet', message_ts: int) -> None:
  481. message = await DBMessage.get_by_signal_id(sender.address, message_ts,
  482. self.chat_id, self.receiver)
  483. if not message:
  484. return
  485. await message.delete()
  486. try:
  487. await sender.intent_for(self).redact(message.mx_room, message.mxid)
  488. except MForbidden:
  489. await self.main_intent.redact(message.mx_room, message.mxid)
  490. # endregion
  491. # region Updating portal info
  492. async def update_info(self, source: 'u.User', info: ChatInfo) -> None:
  493. if self.is_direct:
  494. if not isinstance(info, (Contact, Profile, Address)):
  495. raise ValueError(f"Unexpected type for direct chat update_info: {type(info)}")
  496. if not self.name:
  497. puppet = await p.Puppet.get_by_address(self.chat_id)
  498. if not puppet.name:
  499. await puppet.update_info(info)
  500. self.name = puppet.name
  501. return
  502. if isinstance(info, Group):
  503. changed = await self._update_name(info.name)
  504. elif isinstance(info, GroupV2):
  505. changed = await self._update_name(info.title)
  506. elif isinstance(info, GroupV2ID):
  507. return
  508. else:
  509. raise ValueError(f"Unexpected type for group update_info: {type(info)}")
  510. changed = await self._update_avatar(info) or changed
  511. await self._update_participants(source, info.members)
  512. if changed:
  513. await self.update_bridge_info()
  514. await self.update()
  515. async def update_puppet_avatar(self, new_hash: str, avatar_url: ContentURI) -> None:
  516. if not self.encrypted and not self.private_chat_portal_meta:
  517. return
  518. if self.avatar_hash != new_hash:
  519. self.avatar_hash = new_hash
  520. self.avatar_url = avatar_url
  521. if self.mxid:
  522. await self.main_intent.set_room_avatar(self.mxid, avatar_url)
  523. await self.update_bridge_info()
  524. await self.update()
  525. async def update_puppet_name(self, name: str) -> None:
  526. if not self.encrypted and not self.private_chat_portal_meta:
  527. return
  528. changed = await self._update_name(name)
  529. if changed:
  530. await self.update_bridge_info()
  531. await self.update()
  532. async def _update_name(self, name: str) -> bool:
  533. if self.name != name:
  534. self.name = name
  535. if self.mxid:
  536. await self.main_intent.set_room_name(self.mxid, name)
  537. return True
  538. return False
  539. async def _update_avatar(self, info: ChatInfo) -> bool:
  540. path = None
  541. if isinstance(info, GroupV2):
  542. path = info.avatar
  543. elif isinstance(info, Group):
  544. path = os.path.join(self.config["signal.avatar_dir"], f"group-{self.chat_id}")
  545. if not path:
  546. return False
  547. try:
  548. with open(path, "rb") as file:
  549. data = file.read()
  550. except FileNotFoundError:
  551. return False
  552. new_hash = hashlib.sha256(data).hexdigest()
  553. if self.avatar_hash and new_hash == self.avatar_hash:
  554. return False
  555. mxc = await self.main_intent.upload_media(data)
  556. if self.mxid:
  557. await self.main_intent.set_room_avatar(self.mxid, mxc)
  558. self.avatar_url = mxc
  559. self.avatar_hash = new_hash
  560. return True
  561. async def _update_participants(self, source: 'u.User', participants: List[Address]) -> None:
  562. # TODO add support for pending_members and maybe requesting_members?
  563. if not self.mxid or not participants:
  564. return
  565. for address in participants:
  566. puppet = await p.Puppet.get_by_address(address)
  567. if not puppet.name:
  568. await source.sync_contact(address)
  569. await puppet.intent_for(self).ensure_joined(self.mxid)
  570. # endregion
  571. # region Bridge info state event
  572. @property
  573. def bridge_info_state_key(self) -> str:
  574. return f"net.maunium.signal://signal/{self.chat_id}"
  575. @property
  576. def bridge_info(self) -> Dict[str, Any]:
  577. return {
  578. "bridgebot": self.az.bot_mxid,
  579. "creator": self.main_intent.mxid,
  580. "protocol": {
  581. "id": "signal",
  582. "displayname": "Signal",
  583. "avatar_url": self.config["appservice.bot_avatar"],
  584. },
  585. "channel": {
  586. "id": str(self.chat_id),
  587. "displayname": self.name,
  588. "avatar_url": self.avatar_url,
  589. }
  590. }
  591. async def update_bridge_info(self) -> None:
  592. if not self.mxid:
  593. self.log.debug("Not updating bridge info: no Matrix room created")
  594. return
  595. try:
  596. self.log.debug("Updating bridge info...")
  597. await self.main_intent.send_state_event(self.mxid, StateBridge,
  598. self.bridge_info, self.bridge_info_state_key)
  599. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  600. await self.main_intent.send_state_event(self.mxid, StateHalfShotBridge,
  601. self.bridge_info, self.bridge_info_state_key)
  602. except Exception:
  603. self.log.warning("Failed to update bridge info", exc_info=True)
  604. # endregion
  605. # region Creating Matrix rooms
  606. async def update_matrix_room(self, source: 'u.User', info: ChatInfo) -> None:
  607. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  608. raise ValueError(f"Unexpected type for updating group portal: {type(info)}")
  609. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  610. raise ValueError(f"Unexpected type for updating direct chat portal: {type(info)}")
  611. try:
  612. await self._update_matrix_room(source, info)
  613. except Exception:
  614. self.log.exception("Failed to update portal")
  615. async def create_matrix_room(self, source: 'u.User', info: ChatInfo) -> Optional[RoomID]:
  616. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  617. raise ValueError(f"Unexpected type for creating group portal: {type(info)}")
  618. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  619. raise ValueError(f"Unexpected type for creating direct chat portal: {type(info)}")
  620. if isinstance(info, Group) and not info.members:
  621. groups = await self.signal.list_groups(source.username)
  622. info = next((g for g in groups
  623. if isinstance(g, Group) and g.group_id == info.group_id), info)
  624. elif isinstance(info, GroupV2ID):
  625. groups = await self.signal.list_groups(source.username)
  626. try:
  627. info = next(g for g in groups if isinstance(g, GroupV2) and g.id == info.id)
  628. except StopIteration as e:
  629. raise ValueError("Couldn't get full group v2 info") from e
  630. if self.mxid:
  631. await self.update_matrix_room(source, info)
  632. return self.mxid
  633. async with self._create_room_lock:
  634. return await self._create_matrix_room(source, info)
  635. async def _update_matrix_room(self, source: 'u.User', info: ChatInfo) -> None:
  636. await self.main_intent.invite_user(self.mxid, source.mxid, check_cache=True)
  637. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  638. if puppet:
  639. did_join = await puppet.intent.ensure_joined(self.mxid)
  640. if did_join and self.is_direct:
  641. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  642. await self.update_info(source, info)
  643. # TODO
  644. # up = DBUserPortal.get(source.fbid, self.fbid, self.fb_receiver)
  645. # if not up:
  646. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  647. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  648. # in_community=in_community).insert()
  649. # elif not up.in_community:
  650. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  651. # up.edit(in_community=in_community)
  652. async def _create_matrix_room(self, source: 'u.User', info: ChatInfo) -> Optional[RoomID]:
  653. if self.mxid:
  654. await self._update_matrix_room(source, info)
  655. return self.mxid
  656. await self.update_info(source, info)
  657. self.log.debug("Creating Matrix room")
  658. name: Optional[str] = None
  659. initial_state = [{
  660. "type": str(StateBridge),
  661. "state_key": self.bridge_info_state_key,
  662. "content": self.bridge_info,
  663. }, {
  664. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  665. "type": str(StateHalfShotBridge),
  666. "state_key": self.bridge_info_state_key,
  667. "content": self.bridge_info,
  668. }]
  669. invites = [source.mxid]
  670. if self.config["bridge.encryption.default"] and self.matrix.e2ee:
  671. self.encrypted = True
  672. initial_state.append({
  673. "type": str(EventType.ROOM_ENCRYPTION),
  674. "content": {"algorithm": "m.megolm.v1.aes-sha2"},
  675. })
  676. if self.is_direct:
  677. invites.append(self.az.bot_mxid)
  678. if self.is_direct and source.address == self.chat_id:
  679. name = self.name = "Signal Note to Self"
  680. elif self.encrypted or self.private_chat_portal_meta or not self.is_direct:
  681. name = self.name
  682. if self.avatar_url:
  683. initial_state.append({
  684. "type": str(EventType.ROOM_AVATAR),
  685. "content": {"url": self.avatar_url},
  686. })
  687. if self.config["appservice.community_id"]:
  688. initial_state.append({
  689. "type": "m.room.related_groups",
  690. "content": {"groups": [self.config["appservice.community_id"]]},
  691. })
  692. if self.is_direct:
  693. initial_state.append({
  694. "type": str(EventType.ROOM_POWER_LEVELS),
  695. "content": {"users": {self.main_intent.mxid: 100},
  696. "events": {"m.room.avatar": 0, "m.room.name": 0}}
  697. })
  698. self.mxid = await self.main_intent.create_room(name=name, is_direct=self.is_direct,
  699. initial_state=initial_state,
  700. invitees=invites)
  701. if not self.mxid:
  702. raise Exception("Failed to create room: no mxid returned")
  703. if self.encrypted and self.matrix.e2ee and self.is_direct:
  704. try:
  705. await self.az.intent.ensure_joined(self.mxid)
  706. except Exception:
  707. self.log.warning("Failed to add bridge bot "
  708. f"to new private chat {self.mxid}")
  709. await self.update()
  710. self.log.debug(f"Matrix room created: {self.mxid}")
  711. self.by_mxid[self.mxid] = self
  712. if not self.is_direct:
  713. await self._update_participants(source, info.members)
  714. else:
  715. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  716. if puppet:
  717. try:
  718. await puppet.intent.join_room_by_id(self.mxid)
  719. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  720. except MatrixError:
  721. self.log.debug("Failed to join custom puppet into newly created portal",
  722. exc_info=True)
  723. # TODO
  724. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  725. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  726. # in_community=in_community).upsert()
  727. return self.mxid
  728. # endregion
  729. # region Database getters
  730. async def _postinit(self) -> None:
  731. self.by_chat_id[(self.chat_id, self.receiver)] = self
  732. if self.mxid:
  733. self.by_mxid[self.mxid] = self
  734. if self.is_direct:
  735. puppet = await p.Puppet.get_by_address(self.chat_id)
  736. self._main_intent = puppet.default_mxid_intent
  737. elif not self.is_direct:
  738. self._main_intent = self.az.intent
  739. async def delete(self) -> None:
  740. await DBMessage.delete_all(self.mxid)
  741. self.by_mxid.pop(self.mxid, None)
  742. self.mxid = None
  743. self.encrypted = False
  744. await self.update()
  745. async def save(self) -> None:
  746. await self.update()
  747. @classmethod
  748. def all_with_room(cls) -> AsyncGenerator['Portal', None]:
  749. return cls._db_to_portals(super().all_with_room())
  750. @classmethod
  751. def find_private_chats_with(cls, other_user: Address) -> AsyncGenerator['Portal', None]:
  752. return cls._db_to_portals(super().find_private_chats_with(other_user))
  753. @classmethod
  754. async def _db_to_portals(cls, query: Awaitable[List['Portal']]
  755. ) -> AsyncGenerator['Portal', None]:
  756. portals = await query
  757. for index, portal in enumerate(portals):
  758. try:
  759. yield cls.by_chat_id[(portal.chat_id_str, portal.receiver)]
  760. except KeyError:
  761. await portal._postinit()
  762. yield portal
  763. @classmethod
  764. async def get_by_mxid(cls, mxid: RoomID) -> Optional['Portal']:
  765. try:
  766. return cls.by_mxid[mxid]
  767. except KeyError:
  768. pass
  769. portal = cast(cls, await super().get_by_mxid(mxid))
  770. if portal is not None:
  771. await portal._postinit()
  772. return portal
  773. return None
  774. @classmethod
  775. async def get_by_chat_id(cls, chat_id: Union[GroupID, Address], receiver: str = "",
  776. create: bool = False) -> Optional['Portal']:
  777. if isinstance(chat_id, str):
  778. receiver = ""
  779. elif not isinstance(chat_id, Address):
  780. raise ValueError(f"Invalid chat ID type {type(chat_id)}")
  781. elif not receiver:
  782. raise ValueError("Direct chats must have a receiver")
  783. try:
  784. best_id = chat_id.best_identifier if isinstance(chat_id, Address) else chat_id
  785. return cls.by_chat_id[(best_id, receiver)]
  786. except KeyError:
  787. pass
  788. portal = cast(cls, await super().get_by_chat_id(chat_id, receiver))
  789. if portal is not None:
  790. await portal._postinit()
  791. return portal
  792. if create:
  793. portal = cls(chat_id, receiver)
  794. await portal.insert()
  795. await portal._postinit()
  796. return portal
  797. return None
  798. # endregion