portal.py 37 KB

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