portal.py 33 KB

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