portal.py 34 KB

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