portal.py 35 KB

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