portal.py 31 KB

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