portal.py 36 KB

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