portal.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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. async def handle_matrix_name(self, user: 'u.User', name: str) -> None:
  248. if self.name == name or self.is_direct:
  249. return
  250. self.name = name
  251. self.log.debug(f"{user.mxid} changed the group name, sending to Signal")
  252. try:
  253. await self.signal.update_group(user.username, self.chat_id, title=name)
  254. except Exception:
  255. self.log.exception("Failed to update Signal group name")
  256. self.name = None
  257. async def handle_matrix_avatar(self, user: 'u.User', url: ContentURI) -> None:
  258. if self.is_direct:
  259. return
  260. data = await self.main_intent.download_media(url)
  261. new_hash = hashlib.sha256(data).hexdigest()
  262. if new_hash == self.avatar_hash:
  263. self.log.debug(f"New avatar from Matrix set by {user.mxid} is same as current one")
  264. return
  265. self.avatar_url = url
  266. self.avatar_hash = new_hash
  267. path = os.path.join(self.config["signal.outgoing_attachment_dir"],
  268. f"mautrix-signal-avatar-{str(uuid4())}")
  269. self.log.debug(f"{user.mxid} changed the group avatar, sending to Signal")
  270. try:
  271. with open(path, "wb") as file:
  272. file.write(data)
  273. await self.signal.update_group(user.username, self.chat_id, avatar_path=path)
  274. except Exception:
  275. self.log.exception("Failed to update Signal group avatar")
  276. self.avatar_hash = None
  277. if self.config["signal.remove_file_after_handling"]:
  278. try:
  279. os.remove(path)
  280. except FileNotFoundError:
  281. pass
  282. # endregion
  283. # region Signal event handling
  284. @staticmethod
  285. async def _resolve_address(address: Address) -> Address:
  286. puppet = await p.Puppet.get_by_address(address, create=False)
  287. return puppet.address
  288. async def _find_quote_event_id(self, quote: Optional[Quote]
  289. ) -> Optional[Union[MessageEvent, EventID]]:
  290. if not quote:
  291. return None
  292. author_address = await self._resolve_address(quote.author)
  293. reply_msg = await DBMessage.get_by_signal_id(author_address, quote.id,
  294. self.chat_id, self.receiver)
  295. if not reply_msg:
  296. return None
  297. try:
  298. evt = await self.main_intent.get_event(self.mxid, reply_msg.mxid)
  299. if isinstance(evt, EncryptedEvent):
  300. return await self.matrix.e2ee.decrypt(evt, wait_session_timeout=0)
  301. return evt
  302. except MatrixError:
  303. return reply_msg.mxid
  304. async def handle_signal_message(self, source: 'u.User', sender: 'p.Puppet',
  305. message: MessageData) -> None:
  306. if (sender.address, message.timestamp) in self._msgts_dedup:
  307. self.log.debug(f"Ignoring message {message.timestamp} by {sender.uuid}"
  308. " as it was already handled (message.timestamp in dedup queue)")
  309. await self.signal.send_receipt(source.username, sender.address,
  310. timestamps=[message.timestamp])
  311. return
  312. old_message = await DBMessage.get_by_signal_id(sender.address, message.timestamp,
  313. self.chat_id, self.receiver)
  314. if old_message is not None:
  315. self.log.debug(f"Ignoring message {message.timestamp} by {sender.uuid}"
  316. " as it was already handled (message.id found in database)")
  317. await self.signal.send_receipt(source.username, sender.address,
  318. timestamps=[message.timestamp])
  319. return
  320. self.log.debug(f"Started handling message {message.timestamp} by {sender.uuid}")
  321. self.log.trace(f"Message content: {message}")
  322. self._msgts_dedup.appendleft((sender.address, message.timestamp))
  323. intent = sender.intent_for(self)
  324. await intent.set_typing(self.mxid, False)
  325. event_id = None
  326. reply_to = await self._find_quote_event_id(message.quote)
  327. if message.sticker:
  328. if message.sticker.attachment.incoming_filename:
  329. content = await self._handle_signal_attachment(intent, message.sticker.attachment)
  330. elif StickersClient:
  331. content = await self._handle_signal_sticker(intent, message.sticker)
  332. else:
  333. self.log.debug(f"Not handling sticker in {message.timestamp}: no incoming_filename"
  334. " and signalstickers-client not installed.")
  335. return
  336. if content:
  337. if message.sticker.attachment.blurhash:
  338. content.info["blurhash"] = message.sticker.attachment.blurhash
  339. content.info["xyz.amorgan.blurhash"] = message.sticker.attachment.blurhash
  340. await self._add_sticker_meta(message.sticker, content)
  341. if reply_to and not message.body:
  342. content.set_reply(reply_to)
  343. reply_to = None
  344. event_id = await self._send_message(intent, content, timestamp=message.timestamp,
  345. event_type=EventType.STICKER)
  346. for attachment in message.attachments:
  347. if not attachment.incoming_filename:
  348. self.log.warning("Failed to bridge attachment, no incoming filename: %s",
  349. attachment)
  350. continue
  351. content = await self._handle_signal_attachment(intent, attachment)
  352. if reply_to and not message.body:
  353. # If there's no text, set the first image as the reply
  354. content.set_reply(reply_to)
  355. reply_to = None
  356. event_id = await self._send_message(intent, content, timestamp=message.timestamp)
  357. if message.body:
  358. content = await signal_to_matrix(message)
  359. if reply_to:
  360. content.set_reply(reply_to)
  361. event_id = await self._send_message(intent, content, timestamp=message.timestamp)
  362. if event_id:
  363. msg = DBMessage(mxid=event_id, mx_room=self.mxid,
  364. sender=sender.address, timestamp=message.timestamp,
  365. signal_chat_id=self.chat_id, signal_receiver=self.receiver)
  366. await msg.insert()
  367. await self.signal.send_receipt(source.username, sender.address,
  368. timestamps=[message.timestamp])
  369. await self._send_delivery_receipt(event_id)
  370. self.log.debug(f"Handled Signal message {message.timestamp} -> {event_id}")
  371. else:
  372. self.log.debug(f"Didn't get event ID for {message.timestamp}")
  373. @staticmethod
  374. def _make_media_content(attachment: Attachment) -> MediaMessageEventContent:
  375. if attachment.content_type.startswith("image/"):
  376. msgtype = MessageType.IMAGE
  377. info = ImageInfo(mimetype=attachment.content_type,
  378. width=attachment.width, height=attachment.height)
  379. elif attachment.content_type.startswith("video/"):
  380. msgtype = MessageType.VIDEO
  381. info = VideoInfo(mimetype=attachment.content_type,
  382. width=attachment.width, height=attachment.height)
  383. elif attachment.voice_note or attachment.content_type.startswith("audio/"):
  384. msgtype = MessageType.AUDIO
  385. info = AudioInfo(mimetype=attachment.content_type)
  386. else:
  387. msgtype = MessageType.FILE
  388. info = FileInfo(mimetype=attachment.content_type)
  389. if not attachment.custom_filename:
  390. ext = mimetypes.guess_extension(attachment.content_type) or ""
  391. attachment.custom_filename = attachment.id + ext
  392. if attachment.blurhash:
  393. info["blurhash"] = attachment.blurhash
  394. info["xyz.amorgan.blurhash"] = attachment.blurhash
  395. return MediaMessageEventContent(msgtype=msgtype, info=info,
  396. body=attachment.custom_filename)
  397. async def _handle_signal_attachment(self, intent: IntentAPI, attachment: Attachment
  398. ) -> MediaMessageEventContent:
  399. self.log.trace(f"Reuploading attachment {attachment}")
  400. if not attachment.content_type:
  401. attachment.content_type = (magic.from_file(attachment.incoming_filename, mime=True)
  402. if magic is not None else "application/octet-stream")
  403. content = self._make_media_content(attachment)
  404. with open(attachment.incoming_filename, "rb") as file:
  405. data = file.read()
  406. if self.config["signal.remove_file_after_handling"]:
  407. os.remove(attachment.incoming_filename)
  408. await self._upload_attachment(intent, content, data, attachment.id)
  409. return content
  410. async def _add_sticker_meta(self, sticker: Sticker, content: MediaMessageEventContent) -> None:
  411. try:
  412. pack = self._sticker_meta_cache[sticker.pack_id]
  413. except KeyError:
  414. self.log.debug(f"Fetching sticker pack metadata for {sticker.pack_id}")
  415. try:
  416. async with StickersClient() as client:
  417. pack = await client.get_pack_metadata(sticker.pack_id, sticker.pack_key)
  418. self._sticker_meta_cache[sticker.pack_id] = pack
  419. except Exception:
  420. self.log.warning(f"Failed to fetch pack metadata for {sticker.pack_id}",
  421. exc_info=True)
  422. pack = None
  423. if not pack:
  424. content.info["fi.mau.signal.sticker"] = {
  425. "id": sticker.sticker_id,
  426. "pack": {
  427. "id": sticker.pack_id,
  428. "key": sticker.pack_key,
  429. },
  430. }
  431. return
  432. sticker_meta = pack.stickers[sticker.sticker_id]
  433. content.body = sticker_meta.emoji
  434. content.info["fi.mau.signal.sticker"] = {
  435. "id": sticker.sticker_id,
  436. "emoji": sticker_meta.emoji,
  437. "pack": {
  438. "id": pack.id,
  439. "key": pack.key,
  440. "title": pack.title,
  441. "author": pack.author,
  442. },
  443. }
  444. async def _handle_signal_sticker(self, intent: IntentAPI, sticker: Sticker
  445. ) -> Optional[MediaMessageEventContent]:
  446. try:
  447. self.log.debug(f"Fetching sticker {sticker.pack_id}#{sticker.sticker_id}")
  448. async with StickersClient() as client:
  449. data = await client.download_sticker(sticker.sticker_id,
  450. sticker.pack_id, sticker.pack_key)
  451. except Exception:
  452. self.log.warning(f"Failed to download sticker {sticker.sticker_id}", exc_info=True)
  453. return None
  454. info = ImageInfo(mimetype=sticker.attachment.content_type, size=len(data),
  455. width=sticker.attachment.width, height=sticker.attachment.height)
  456. if info.width > 256 or info.height > 256:
  457. if info.width == info.height:
  458. info.width = info.height = 256
  459. elif info.width > info.height:
  460. info.height = int(info.height / (info.width / 256))
  461. info.width = 256
  462. else:
  463. info.width = int(info.width / (info.height / 256))
  464. info.height = 256
  465. if magic:
  466. info.mimetype = magic.from_buffer(data, mime=True)
  467. ext = mimetypes.guess_extension(info.mimetype)
  468. if not ext and info.mimetype == "image/webp":
  469. ext = ".webp"
  470. content = MediaMessageEventContent(msgtype=MessageType.IMAGE, info=info,
  471. body=f"sticker{ext}")
  472. await self._upload_attachment(intent, content, data, sticker.attachment.id)
  473. return content
  474. async def _upload_attachment(self, intent: IntentAPI, content: MediaMessageEventContent,
  475. data: bytes, id: str) -> None:
  476. upload_mime_type = content.info.mimetype
  477. if self.encrypted and encrypt_attachment:
  478. data, content.file = encrypt_attachment(data)
  479. upload_mime_type = "application/octet-stream"
  480. content.url = await intent.upload_media(data, mime_type=upload_mime_type, filename=id)
  481. if content.file:
  482. content.file.url = content.url
  483. content.url = None
  484. # This is a hack for bad clients like Element iOS that require a thumbnail
  485. if content.info.mimetype.startswith("image/"):
  486. if content.file:
  487. content.info.thumbnail_file = content.file
  488. elif content.url:
  489. content.info.thumbnail_url = content.url
  490. async def handle_signal_reaction(self, sender: 'p.Puppet', reaction: Reaction) -> None:
  491. author_address = await self._resolve_address(reaction.target_author)
  492. target_id = reaction.target_sent_timestamp
  493. async with self._reaction_lock:
  494. dedup_id = (author_address, target_id, reaction.emoji)
  495. if dedup_id in self._reaction_dedup:
  496. return
  497. self._reaction_dedup.appendleft(dedup_id)
  498. existing = await DBReaction.get_by_signal_id(self.chat_id, self.receiver,
  499. author_address, target_id, sender.address)
  500. if reaction.remove:
  501. if existing:
  502. try:
  503. await sender.intent_for(self).redact(existing.mx_room, existing.mxid)
  504. except MForbidden:
  505. await self.main_intent.redact(existing.mx_room, existing.mxid)
  506. await existing.delete()
  507. self.log.trace(f"Removed {existing} after Signal removal")
  508. return
  509. elif existing and existing.emoji == reaction.emoji:
  510. return
  511. message = await DBMessage.get_by_signal_id(author_address, target_id,
  512. self.chat_id, self.receiver)
  513. if not message:
  514. self.log.debug(f"Ignoring reaction to unknown message {target_id}")
  515. return
  516. intent = sender.intent_for(self)
  517. # TODO add variation selectors to emoji before sending to Matrix
  518. mxid = await intent.react(message.mx_room, message.mxid, reaction.emoji)
  519. self.log.debug(f"{sender.address} reacted to {message.mxid} -> {mxid}")
  520. await self._upsert_reaction(existing, intent, mxid, sender, message, reaction.emoji)
  521. async def handle_signal_delete(self, sender: 'p.Puppet', message_ts: int) -> None:
  522. message = await DBMessage.get_by_signal_id(sender.address, message_ts,
  523. self.chat_id, self.receiver)
  524. if not message:
  525. return
  526. await message.delete()
  527. try:
  528. await sender.intent_for(self).redact(message.mx_room, message.mxid)
  529. except MForbidden:
  530. await self.main_intent.redact(message.mx_room, message.mxid)
  531. # endregion
  532. # region Updating portal info
  533. async def update_info(self, source: 'u.User', info: ChatInfo) -> None:
  534. if self.is_direct:
  535. if not isinstance(info, (Contact, Profile, Address)):
  536. raise ValueError(f"Unexpected type for direct chat update_info: {type(info)}")
  537. if not self.name:
  538. puppet = await p.Puppet.get_by_address(self.chat_id)
  539. if not puppet.name:
  540. await puppet.update_info(info)
  541. self.name = puppet.name
  542. return
  543. if isinstance(info, Group):
  544. changed = await self._update_name(info.name)
  545. elif isinstance(info, GroupV2):
  546. changed = await self._update_name(info.title)
  547. elif isinstance(info, GroupV2ID):
  548. return
  549. else:
  550. raise ValueError(f"Unexpected type for group update_info: {type(info)}")
  551. changed = await self._update_avatar(info) or changed
  552. await self._update_participants(source, info.members)
  553. if changed:
  554. await self.update_bridge_info()
  555. await self.update()
  556. async def update_puppet_avatar(self, new_hash: str, avatar_url: ContentURI) -> None:
  557. if not self.encrypted and not self.private_chat_portal_meta:
  558. return
  559. if self.avatar_hash != new_hash:
  560. self.avatar_hash = new_hash
  561. self.avatar_url = avatar_url
  562. if self.mxid:
  563. await self.main_intent.set_room_avatar(self.mxid, avatar_url)
  564. await self.update_bridge_info()
  565. await self.update()
  566. async def update_puppet_name(self, name: str) -> None:
  567. if not self.encrypted and not self.private_chat_portal_meta:
  568. return
  569. changed = await self._update_name(name)
  570. if changed:
  571. await self.update_bridge_info()
  572. await self.update()
  573. async def _update_name(self, name: str) -> bool:
  574. if self.name != name:
  575. self.name = name
  576. if self.mxid:
  577. await self.main_intent.set_room_name(self.mxid, name)
  578. return True
  579. return False
  580. @property
  581. def avatar_set(self) -> bool:
  582. return bool(self.avatar_hash)
  583. async def _update_avatar(self, info: ChatInfo) -> bool:
  584. path = None
  585. if isinstance(info, GroupV2):
  586. path = info.avatar
  587. elif isinstance(info, Group):
  588. path = f"group-{self.chat_id}"
  589. res = await p.Puppet.upload_avatar(self, path)
  590. if res is False:
  591. return False
  592. self.avatar_hash, self.avatar_url = res
  593. if self.mxid:
  594. try:
  595. await self.main_intent.set_room_avatar(self.mxid, self.avatar_url)
  596. except Exception:
  597. self.log.exception("Error setting avatar")
  598. self.avatar_hash = None
  599. return True
  600. async def _update_participants(self, source: 'u.User', participants: List[Address]) -> None:
  601. # TODO add support for pending_members and maybe requesting_members?
  602. if not self.mxid or not participants:
  603. return
  604. for address in participants:
  605. puppet = await p.Puppet.get_by_address(address)
  606. if not puppet.name:
  607. await source.sync_contact(address)
  608. await puppet.intent_for(self).ensure_joined(self.mxid)
  609. # endregion
  610. # region Bridge info state event
  611. @property
  612. def bridge_info_state_key(self) -> str:
  613. return f"net.maunium.signal://signal/{self.chat_id}"
  614. @property
  615. def bridge_info(self) -> Dict[str, Any]:
  616. return {
  617. "bridgebot": self.az.bot_mxid,
  618. "creator": self.main_intent.mxid,
  619. "protocol": {
  620. "id": "signal",
  621. "displayname": "Signal",
  622. "avatar_url": self.config["appservice.bot_avatar"],
  623. },
  624. "channel": {
  625. "id": str(self.chat_id),
  626. "displayname": self.name,
  627. "avatar_url": self.avatar_url,
  628. }
  629. }
  630. async def update_bridge_info(self) -> None:
  631. if not self.mxid:
  632. self.log.debug("Not updating bridge info: no Matrix room created")
  633. return
  634. try:
  635. self.log.debug("Updating bridge info...")
  636. await self.main_intent.send_state_event(self.mxid, StateBridge,
  637. self.bridge_info, self.bridge_info_state_key)
  638. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  639. await self.main_intent.send_state_event(self.mxid, StateHalfShotBridge,
  640. self.bridge_info, self.bridge_info_state_key)
  641. except Exception:
  642. self.log.warning("Failed to update bridge info", exc_info=True)
  643. # endregion
  644. # region Creating Matrix rooms
  645. async def update_matrix_room(self, source: 'u.User', info: ChatInfo) -> None:
  646. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  647. raise ValueError(f"Unexpected type for updating group portal: {type(info)}")
  648. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  649. raise ValueError(f"Unexpected type for updating direct chat portal: {type(info)}")
  650. try:
  651. await self._update_matrix_room(source, info)
  652. except Exception:
  653. self.log.exception("Failed to update portal")
  654. async def create_matrix_room(self, source: 'u.User', info: ChatInfo) -> Optional[RoomID]:
  655. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  656. raise ValueError(f"Unexpected type for creating group portal: {type(info)}")
  657. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  658. raise ValueError(f"Unexpected type for creating direct chat portal: {type(info)}")
  659. if isinstance(info, Group) and not info.members:
  660. groups = await self.signal.list_groups(source.username)
  661. info = next((g for g in groups
  662. if isinstance(g, Group) and g.group_id == info.group_id), info)
  663. elif isinstance(info, GroupV2ID):
  664. groups = await self.signal.list_groups(source.username)
  665. try:
  666. info = next(g for g in groups if isinstance(g, GroupV2) and g.id == info.id)
  667. except StopIteration as e:
  668. raise ValueError("Couldn't get full group v2 info") from e
  669. if self.mxid:
  670. await self.update_matrix_room(source, info)
  671. return self.mxid
  672. async with self._create_room_lock:
  673. return await self._create_matrix_room(source, info)
  674. async def _update_matrix_room(self, source: 'u.User', info: ChatInfo) -> None:
  675. await self.main_intent.invite_user(self.mxid, source.mxid, check_cache=True)
  676. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  677. if puppet:
  678. did_join = await puppet.intent.ensure_joined(self.mxid)
  679. if did_join and self.is_direct:
  680. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  681. await self.update_info(source, info)
  682. # TODO
  683. # up = DBUserPortal.get(source.fbid, self.fbid, self.fb_receiver)
  684. # if not up:
  685. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  686. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  687. # in_community=in_community).insert()
  688. # elif not up.in_community:
  689. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  690. # up.edit(in_community=in_community)
  691. async def _create_matrix_room(self, source: 'u.User', info: ChatInfo) -> Optional[RoomID]:
  692. if self.mxid:
  693. await self._update_matrix_room(source, info)
  694. return self.mxid
  695. await self.update_info(source, info)
  696. self.log.debug("Creating Matrix room")
  697. name: Optional[str] = None
  698. initial_state = [{
  699. "type": str(StateBridge),
  700. "state_key": self.bridge_info_state_key,
  701. "content": self.bridge_info,
  702. }, {
  703. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  704. "type": str(StateHalfShotBridge),
  705. "state_key": self.bridge_info_state_key,
  706. "content": self.bridge_info,
  707. }]
  708. invites = [source.mxid]
  709. if self.config["bridge.encryption.default"] and self.matrix.e2ee:
  710. self.encrypted = True
  711. initial_state.append({
  712. "type": str(EventType.ROOM_ENCRYPTION),
  713. "content": {"algorithm": "m.megolm.v1.aes-sha2"},
  714. })
  715. if self.is_direct:
  716. invites.append(self.az.bot_mxid)
  717. if self.is_direct and source.address == self.chat_id:
  718. name = self.name = "Signal Note to Self"
  719. elif self.encrypted or self.private_chat_portal_meta or not self.is_direct:
  720. name = self.name
  721. if self.avatar_url:
  722. initial_state.append({
  723. "type": str(EventType.ROOM_AVATAR),
  724. "content": {"url": self.avatar_url},
  725. })
  726. if self.config["appservice.community_id"]:
  727. initial_state.append({
  728. "type": "m.room.related_groups",
  729. "content": {"groups": [self.config["appservice.community_id"]]},
  730. })
  731. if self.is_direct:
  732. initial_state.append({
  733. "type": str(EventType.ROOM_POWER_LEVELS),
  734. "content": {"users": {self.main_intent.mxid: 100},
  735. "events": {"m.room.avatar": 0, "m.room.name": 0}}
  736. })
  737. self.mxid = await self.main_intent.create_room(name=name, is_direct=self.is_direct,
  738. initial_state=initial_state,
  739. invitees=invites)
  740. if not self.mxid:
  741. raise Exception("Failed to create room: no mxid returned")
  742. if self.encrypted and self.matrix.e2ee and self.is_direct:
  743. try:
  744. await self.az.intent.ensure_joined(self.mxid)
  745. except Exception:
  746. self.log.warning("Failed to add bridge bot "
  747. f"to new private chat {self.mxid}")
  748. await self.update()
  749. self.log.debug(f"Matrix room created: {self.mxid}")
  750. self.by_mxid[self.mxid] = self
  751. if not self.is_direct:
  752. await self._update_participants(source, info.members)
  753. else:
  754. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  755. if puppet:
  756. try:
  757. await puppet.intent.join_room_by_id(self.mxid)
  758. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  759. except MatrixError:
  760. self.log.debug("Failed to join custom puppet into newly created portal",
  761. exc_info=True)
  762. # TODO
  763. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  764. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  765. # in_community=in_community).upsert()
  766. return self.mxid
  767. # endregion
  768. # region Database getters
  769. async def _postinit(self) -> None:
  770. self.by_chat_id[(self.chat_id, self.receiver)] = self
  771. if self.mxid:
  772. self.by_mxid[self.mxid] = self
  773. if self.is_direct:
  774. puppet = await p.Puppet.get_by_address(self.chat_id)
  775. self._main_intent = puppet.default_mxid_intent
  776. elif not self.is_direct:
  777. self._main_intent = self.az.intent
  778. async def delete(self) -> None:
  779. await DBMessage.delete_all(self.mxid)
  780. self.by_mxid.pop(self.mxid, None)
  781. self.mxid = None
  782. self.encrypted = False
  783. await self.update()
  784. async def save(self) -> None:
  785. await self.update()
  786. @classmethod
  787. def all_with_room(cls) -> AsyncGenerator['Portal', None]:
  788. return cls._db_to_portals(super().all_with_room())
  789. @classmethod
  790. def find_private_chats_with(cls, other_user: Address) -> AsyncGenerator['Portal', None]:
  791. return cls._db_to_portals(super().find_private_chats_with(other_user))
  792. @classmethod
  793. async def _db_to_portals(cls, query: Awaitable[List['Portal']]
  794. ) -> AsyncGenerator['Portal', None]:
  795. portals = await query
  796. for index, portal in enumerate(portals):
  797. try:
  798. yield cls.by_chat_id[(portal.chat_id_str, portal.receiver)]
  799. except KeyError:
  800. await portal._postinit()
  801. yield portal
  802. @classmethod
  803. async def get_by_mxid(cls, mxid: RoomID) -> Optional['Portal']:
  804. try:
  805. return cls.by_mxid[mxid]
  806. except KeyError:
  807. pass
  808. portal = cast(cls, await super().get_by_mxid(mxid))
  809. if portal is not None:
  810. await portal._postinit()
  811. return portal
  812. return None
  813. @classmethod
  814. async def get_by_chat_id(cls, chat_id: Union[GroupID, Address], receiver: str = "",
  815. create: bool = False) -> Optional['Portal']:
  816. if isinstance(chat_id, str):
  817. receiver = ""
  818. elif not isinstance(chat_id, Address):
  819. raise ValueError(f"Invalid chat ID type {type(chat_id)}")
  820. elif not receiver:
  821. raise ValueError("Direct chats must have a receiver")
  822. try:
  823. best_id = chat_id.best_identifier if isinstance(chat_id, Address) else chat_id
  824. return cls.by_chat_id[(best_id, receiver)]
  825. except KeyError:
  826. pass
  827. portal = cast(cls, await super().get_by_chat_id(chat_id, receiver))
  828. if portal is not None:
  829. await portal._postinit()
  830. return portal
  831. if create:
  832. portal = cls(chat_id, receiver)
  833. await portal.insert()
  834. await portal._postinit()
  835. return portal
  836. return None
  837. # endregion