portal.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  1. # mautrix-signal - A Matrix-Signal puppeting bridge
  2. # Copyright (C) 2021 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 __future__ import annotations
  17. from typing import TYPE_CHECKING, Any, AsyncGenerator, Awaitable, Callable, Union, cast
  18. from collections import deque
  19. from uuid import UUID, uuid4
  20. import asyncio
  21. import hashlib
  22. import mimetypes
  23. import os
  24. import os.path
  25. import pathlib
  26. import time
  27. from mausignald.errors import ResponseError, RPCError
  28. from mausignald.types import (
  29. AccessControlMode,
  30. Address,
  31. Attachment,
  32. Contact,
  33. Group,
  34. GroupAccessControl,
  35. GroupID,
  36. GroupMemberRole,
  37. GroupV2,
  38. GroupV2ID,
  39. Mention,
  40. MessageData,
  41. Profile,
  42. Quote,
  43. Reaction,
  44. Sticker,
  45. )
  46. from mautrix.appservice import AppService, IntentAPI
  47. from mautrix.bridge import BasePortal, async_getter_lock
  48. from mautrix.errors import IntentError, MatrixError, MForbidden
  49. from mautrix.types import (
  50. AudioInfo,
  51. ContentURI,
  52. EncryptedEvent,
  53. EventID,
  54. EventType,
  55. FileInfo,
  56. ImageInfo,
  57. MediaMessageEventContent,
  58. MessageEvent,
  59. MessageEventContent,
  60. MessageType,
  61. PowerLevelStateEventContent,
  62. RoomID,
  63. SingleReceiptEventContent,
  64. TextMessageEventContent,
  65. UserID,
  66. VideoInfo,
  67. )
  68. from mautrix.util.bridge_state import BridgeStateEvent
  69. from mautrix.util.format_duration import format_duration
  70. from mautrix.util.message_send_checkpoint import MessageSendCheckpointStatus
  71. from . import matrix as m, puppet as p, signal as s, user as u
  72. from .config import Config
  73. from .db import (
  74. DisappearingMessage,
  75. Message as DBMessage,
  76. Portal as DBPortal,
  77. Reaction as DBReaction,
  78. )
  79. from .formatter import matrix_to_signal, signal_to_matrix
  80. from .util import id_to_str
  81. if TYPE_CHECKING:
  82. from .__main__ import SignalBridge
  83. try:
  84. from mautrix.crypto.attachments import decrypt_attachment, encrypt_attachment
  85. except ImportError:
  86. encrypt_attachment = decrypt_attachment = None
  87. try:
  88. from signalstickers_client import StickersClient
  89. from signalstickers_client.models import StickerPack
  90. except ImportError:
  91. StickersClient = StickerPack = None
  92. try:
  93. import magic
  94. except ImportError:
  95. magic = None
  96. StateBridge = EventType.find("m.bridge", EventType.Class.STATE)
  97. StateHalfShotBridge = EventType.find("uk.half-shot.bridge", EventType.Class.STATE)
  98. ChatInfo = Union[Group, GroupV2, GroupV2ID, Contact, Profile, Address]
  99. class Portal(DBPortal, BasePortal):
  100. by_mxid: dict[RoomID, Portal] = {}
  101. by_chat_id: dict[tuple[str, str], Portal] = {}
  102. _sticker_meta_cache: dict[str, StickerPack] = {}
  103. config: Config
  104. matrix: m.MatrixHandler
  105. signal: s.SignalHandler
  106. az: AppService
  107. private_chat_portal_meta: bool
  108. expiration_time: int | None
  109. _main_intent: IntentAPI | None
  110. _create_room_lock: asyncio.Lock
  111. _msgts_dedup: deque[tuple[Address, int]]
  112. _reaction_dedup: deque[tuple[Address, int, str]]
  113. _reaction_lock: asyncio.Lock
  114. _pending_members: set[UUID] | None
  115. _expiration_lock: asyncio.Lock
  116. def __init__(
  117. self,
  118. chat_id: GroupID | Address,
  119. receiver: str,
  120. mxid: RoomID | None = None,
  121. name: str | None = None,
  122. avatar_hash: str | None = None,
  123. avatar_url: ContentURI | None = None,
  124. name_set: bool = False,
  125. avatar_set: bool = False,
  126. revision: int = 0,
  127. encrypted: bool = False,
  128. relay_user_id: UserID | None = None,
  129. expiration_time: int | None = None,
  130. ) -> None:
  131. super().__init__(
  132. chat_id,
  133. receiver,
  134. mxid,
  135. name,
  136. avatar_hash,
  137. avatar_url,
  138. name_set,
  139. avatar_set,
  140. revision,
  141. encrypted,
  142. relay_user_id,
  143. expiration_time,
  144. )
  145. self._create_room_lock = asyncio.Lock()
  146. self.log = self.log.getChild(self.chat_id_str)
  147. self._main_intent = None
  148. self._msgts_dedup = deque(maxlen=100)
  149. self._reaction_dedup = deque(maxlen=100)
  150. self._last_participant_update = set()
  151. self._reaction_lock = asyncio.Lock()
  152. self._pending_members = None
  153. self._relay_user = None
  154. self._expiration_lock = asyncio.Lock()
  155. @property
  156. def main_intent(self) -> IntentAPI:
  157. if not self._main_intent:
  158. raise ValueError("Portal must be postinit()ed before main_intent can be used")
  159. return self._main_intent
  160. @property
  161. def is_direct(self) -> bool:
  162. return isinstance(self.chat_id, Address)
  163. def handle_uuid_receive(self, uuid: UUID) -> None:
  164. if not self.is_direct or self.chat_id.uuid:
  165. raise ValueError(
  166. "handle_uuid_receive can only be used for private chat portals with a phone "
  167. "number chat_id"
  168. )
  169. del self.by_chat_id[(self.chat_id_str, self.receiver)]
  170. self.chat_id = Address(uuid=uuid)
  171. self.by_chat_id[(self.chat_id_str, self.receiver)] = self
  172. @classmethod
  173. def init_cls(cls, bridge: "SignalBridge") -> None:
  174. cls.config = bridge.config
  175. cls.matrix = bridge.matrix
  176. cls.signal = bridge.signal
  177. cls.az = bridge.az
  178. cls.loop = bridge.loop
  179. BasePortal.bridge = bridge
  180. cls.private_chat_portal_meta = cls.config["bridge.private_chat_portal_meta"]
  181. @classmethod
  182. async def start_disappearing_message_expirations(cls):
  183. await asyncio.gather(
  184. *(
  185. cls._expire_event(dm.room_id, dm.mxid, restart=True)
  186. for dm in await DisappearingMessage.get_all()
  187. if dm.expiration_ts
  188. )
  189. )
  190. # region Misc
  191. async def _send_delivery_receipt(self, event_id: EventID) -> None:
  192. if event_id and self.config["bridge.delivery_receipts"]:
  193. try:
  194. await self.az.intent.mark_read(self.mxid, event_id)
  195. except Exception:
  196. self.log.exception("Failed to send delivery receipt for %s", event_id)
  197. async def _upsert_reaction(
  198. self,
  199. existing: DBReaction,
  200. intent: IntentAPI,
  201. mxid: EventID,
  202. sender: p.Puppet | u.User,
  203. message: DBMessage,
  204. emoji: str,
  205. ) -> None:
  206. if existing:
  207. self.log.debug(
  208. f"_upsert_reaction redacting {existing.mxid} and inserting {mxid}"
  209. f" (message: {message.mxid})"
  210. )
  211. try:
  212. await intent.redact(existing.mx_room, existing.mxid)
  213. except MForbidden:
  214. self.log.debug("Unexpected MForbidden redacting reaction", exc_info=True)
  215. await existing.edit(emoji=emoji, mxid=mxid, mx_room=message.mx_room)
  216. else:
  217. self.log.debug(f"_upsert_reaction inserting {mxid} (message: {message.mxid})")
  218. await DBReaction(
  219. mxid=mxid,
  220. mx_room=message.mx_room,
  221. emoji=emoji,
  222. signal_chat_id=self.chat_id,
  223. signal_receiver=self.receiver,
  224. msg_author=message.sender,
  225. msg_timestamp=message.timestamp,
  226. author=sender.address,
  227. ).insert()
  228. # endregion
  229. # region Matrix event handling
  230. @staticmethod
  231. def _make_attachment(message: MediaMessageEventContent, path: str) -> Attachment:
  232. attachment = Attachment(
  233. custom_filename=message.body,
  234. content_type=message.info.mimetype,
  235. outgoing_filename=path,
  236. )
  237. info = message.info
  238. attachment.width = info.get("w", info.get("width", 0))
  239. attachment.height = info.get("h", info.get("height", 0))
  240. attachment.voice_note = message.msgtype == MessageType.AUDIO
  241. return attachment
  242. def _write_outgoing_file(self, data: bytes) -> str:
  243. dir = pathlib.Path(self.config["signal.outgoing_attachment_dir"])
  244. path = dir.joinpath(f"mautrix-signal-{str(uuid4())}")
  245. try:
  246. with open(path, "wb") as file:
  247. file.write(data)
  248. except FileNotFoundError:
  249. dir.mkdir(mode=0o755, parents=True, exist_ok=True)
  250. with open(path, "wb") as file:
  251. file.write(data)
  252. return str(path)
  253. async def _download_matrix_media(self, message: MediaMessageEventContent) -> str:
  254. if message.file:
  255. data = await self.main_intent.download_media(message.file.url)
  256. data = decrypt_attachment(
  257. data, message.file.key.key, message.file.hashes.get("sha256"), message.file.iv
  258. )
  259. else:
  260. data = await self.main_intent.download_media(message.url)
  261. return self._write_outgoing_file(data)
  262. async def handle_matrix_message(
  263. self, sender: u.User, message: MessageEventContent, event_id: EventID
  264. ) -> None:
  265. try:
  266. await self._handle_matrix_message(sender, message, event_id)
  267. except Exception as e:
  268. sender.send_remote_checkpoint(
  269. MessageSendCheckpointStatus.PERM_FAILURE,
  270. event_id,
  271. self.mxid,
  272. EventType.ROOM_MESSAGE,
  273. message.msgtype,
  274. error=e,
  275. )
  276. auth_failed = (
  277. "org.whispersystems.signalservice.api.push.exceptions.AuthorizationFailedException"
  278. )
  279. if isinstance(e, ResponseError) and auth_failed in e.data.get("exceptions", []):
  280. await sender.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=str(e))
  281. await self._send_message(
  282. self.main_intent,
  283. TextMessageEventContent(
  284. msgtype=MessageType.NOTICE, body=f"\u26a0 Your message was not bridged: {e}"
  285. ),
  286. )
  287. async def _handle_matrix_message(
  288. self, sender: u.User, message: MessageEventContent, event_id: EventID
  289. ) -> None:
  290. orig_sender = sender
  291. sender, is_relay = await self.get_relay_sender(sender, f"message {event_id}")
  292. if not sender:
  293. orig_sender.send_remote_checkpoint(
  294. status=MessageSendCheckpointStatus.PERM_FAILURE,
  295. event_id=event_id,
  296. room_id=self.mxid,
  297. event_type=EventType.ROOM_MESSAGE,
  298. message_type=message.msgtype,
  299. error="user is not logged in",
  300. )
  301. return
  302. elif is_relay:
  303. await self.apply_relay_message_format(orig_sender, message)
  304. request_id = int(time.time() * 1000)
  305. self._msgts_dedup.appendleft((sender.address, request_id))
  306. quote = None
  307. if message.get_reply_to():
  308. reply = await DBMessage.get_by_mxid(message.get_reply_to(), self.mxid)
  309. # TODO include actual text? either store in db or fetch event from homeserver
  310. if reply is not None:
  311. quote = Quote(id=reply.timestamp, author=reply.sender, text="")
  312. attachments: list[Attachment] | None = None
  313. attachment_path: str | None = None
  314. mentions: list[Mention] | None = None
  315. if message.msgtype.is_text:
  316. text, mentions = await matrix_to_signal(message)
  317. elif message.msgtype.is_media:
  318. attachment_path = await self._download_matrix_media(message)
  319. attachment = self._make_attachment(message, attachment_path)
  320. attachments = [attachment]
  321. text = message.body if is_relay else None
  322. self.log.trace("Formed outgoing attachment %s", attachment)
  323. else:
  324. self.log.debug(f"Unknown msgtype {message.msgtype} in Matrix message {event_id}")
  325. return
  326. self.log.debug(f"Sending Matrix message {event_id} to Signal with timestamp {request_id}")
  327. try:
  328. await self.signal.send(
  329. username=sender.username,
  330. recipient=self.chat_id,
  331. body=text,
  332. mentions=mentions,
  333. quote=quote,
  334. attachments=attachments,
  335. timestamp=request_id,
  336. )
  337. except Exception:
  338. self.log.exception("Sending message failed")
  339. raise
  340. else:
  341. sender.send_remote_checkpoint(
  342. MessageSendCheckpointStatus.SUCCESS,
  343. event_id,
  344. self.mxid,
  345. EventType.ROOM_MESSAGE,
  346. message.msgtype,
  347. )
  348. await self._send_delivery_receipt(event_id)
  349. msg = DBMessage(
  350. mxid=event_id,
  351. mx_room=self.mxid,
  352. sender=sender.address,
  353. timestamp=request_id,
  354. signal_chat_id=self.chat_id,
  355. signal_receiver=self.receiver,
  356. )
  357. await msg.insert()
  358. self.log.debug(f"Handled Matrix message {event_id} -> {request_id}")
  359. if attachment_path and self.config["signal.remove_file_after_handling"]:
  360. try:
  361. os.remove(attachment_path)
  362. except FileNotFoundError:
  363. pass
  364. # Handle disappearing messages
  365. if self.expiration_time and (
  366. self.is_direct or self.config["signal.enable_disappearing_messages_in_groups"]
  367. ):
  368. dm = DisappearingMessage(self.mxid, event_id, self.expiration_time)
  369. await dm.insert()
  370. await Portal._expire_event(dm.room_id, dm.mxid)
  371. async def handle_matrix_reaction(
  372. self, sender: u.User, event_id: EventID, reacting_to: EventID, emoji: str
  373. ) -> None:
  374. if not await sender.is_logged_in():
  375. self.log.trace(f"Ignoring reaction by non-logged-in user {sender.mxid}")
  376. return
  377. # Signal doesn't seem to use variation selectors at all
  378. emoji = emoji.rstrip("\ufe0f")
  379. message = await DBMessage.get_by_mxid(reacting_to, self.mxid)
  380. if not message:
  381. self.log.debug(f"Ignoring reaction to unknown event {reacting_to}")
  382. return
  383. existing = await DBReaction.get_by_signal_id(
  384. self.chat_id, self.receiver, message.sender, message.timestamp, sender.address
  385. )
  386. if existing and existing.emoji == emoji:
  387. return
  388. dedup_id = (message.sender, message.timestamp, emoji)
  389. self._reaction_dedup.appendleft(dedup_id)
  390. async with self._reaction_lock:
  391. reaction = Reaction(
  392. emoji=emoji,
  393. remove=False,
  394. target_author=message.sender,
  395. target_sent_timestamp=message.timestamp,
  396. )
  397. try:
  398. await self.signal.react(
  399. username=sender.username, recipient=self.chat_id, reaction=reaction
  400. )
  401. except Exception as e:
  402. sender.send_remote_checkpoint(
  403. MessageSendCheckpointStatus.PERM_FAILURE,
  404. event_id,
  405. self.mxid,
  406. EventType.REACTION,
  407. error=e,
  408. )
  409. else:
  410. self.log.trace(f"{sender.mxid} reacted to {message.timestamp} with {emoji}")
  411. sender.send_remote_checkpoint(
  412. MessageSendCheckpointStatus.SUCCESS,
  413. event_id,
  414. self.mxid,
  415. EventType.REACTION,
  416. )
  417. await self._upsert_reaction(
  418. existing, self.main_intent, event_id, sender, message, emoji
  419. )
  420. await self._send_delivery_receipt(event_id)
  421. async def handle_matrix_redaction(
  422. self, sender: u.User, event_id: EventID, redaction_event_id: EventID
  423. ) -> None:
  424. if not await sender.is_logged_in():
  425. return
  426. message = await DBMessage.get_by_mxid(event_id, self.mxid)
  427. if message:
  428. try:
  429. await message.delete()
  430. await self.signal.remote_delete(
  431. sender.username, recipient=self.chat_id, timestamp=message.timestamp
  432. )
  433. except Exception as e:
  434. self.log.exception("Removing message failed")
  435. sender.send_remote_checkpoint(
  436. MessageSendCheckpointStatus.PERM_FAILURE,
  437. redaction_event_id,
  438. self.mxid,
  439. EventType.ROOM_REDACTION,
  440. error=e,
  441. )
  442. else:
  443. self.log.trace(f"Removed {message} after Matrix redaction")
  444. sender.send_remote_checkpoint(
  445. MessageSendCheckpointStatus.SUCCESS,
  446. redaction_event_id,
  447. self.mxid,
  448. EventType.ROOM_REDACTION,
  449. )
  450. await self._send_delivery_receipt(redaction_event_id)
  451. return
  452. reaction = await DBReaction.get_by_mxid(event_id, self.mxid)
  453. if reaction:
  454. try:
  455. await reaction.delete()
  456. remove_reaction = Reaction(
  457. emoji=reaction.emoji,
  458. remove=True,
  459. target_author=reaction.msg_author,
  460. target_sent_timestamp=reaction.msg_timestamp,
  461. )
  462. await self.signal.react(
  463. username=sender.username, recipient=self.chat_id, reaction=remove_reaction
  464. )
  465. except Exception as e:
  466. self.log.exception("Removing reaction failed")
  467. sender.send_remote_checkpoint(
  468. MessageSendCheckpointStatus.PERM_FAILURE,
  469. redaction_event_id,
  470. self.mxid,
  471. EventType.ROOM_REDACTION,
  472. error=e,
  473. )
  474. else:
  475. self.log.trace(f"Removed {reaction} after Matrix redaction")
  476. sender.send_remote_checkpoint(
  477. MessageSendCheckpointStatus.SUCCESS,
  478. redaction_event_id,
  479. self.mxid,
  480. EventType.ROOM_REDACTION,
  481. )
  482. await self._send_delivery_receipt(redaction_event_id)
  483. return
  484. sender.send_remote_checkpoint(
  485. MessageSendCheckpointStatus.PERM_FAILURE,
  486. redaction_event_id,
  487. self.mxid,
  488. EventType.ROOM_REDACTION,
  489. error=f"No message or reaction found for redaction",
  490. )
  491. async def handle_matrix_join(self, user: u.User) -> None:
  492. if self.is_direct or not await user.is_logged_in():
  493. return
  494. if self._pending_members is None:
  495. self.log.debug(
  496. f"{user.mxid} ({user.uuid}) joined room, but pending_members is None,"
  497. " updating chat info"
  498. )
  499. await self.update_info(user, GroupV2ID(id=self.chat_id))
  500. if self._pending_members is None:
  501. self.log.warning(
  502. f"Didn't get pending member list after info update, {user.mxid} ({user.uuid}) may"
  503. "not be in the group on Signal."
  504. )
  505. elif user.uuid in self._pending_members:
  506. self.log.debug(f"{user.mxid} ({user.uuid}) joined room, accepting invite on Signal")
  507. try:
  508. resp = await self.signal.accept_invitation(user.username, self.chat_id)
  509. self._pending_members.remove(user.uuid)
  510. except RPCError as e:
  511. await self.main_intent.send_notice(
  512. self.mxid, f"\u26a0 Failed to accept invite on Signal: {e}"
  513. )
  514. else:
  515. await self.update_info(user, resp)
  516. async def handle_matrix_leave(self, user: u.User) -> None:
  517. if not await user.is_logged_in():
  518. return
  519. if self.is_direct:
  520. self.log.info(f"{user.mxid} left private chat portal with {self.chat_id}")
  521. if user.username == self.receiver:
  522. self.log.info(
  523. f"{user.mxid} was the recipient of this portal. " "Cleaning up and deleting..."
  524. )
  525. await self.cleanup_and_delete()
  526. else:
  527. self.log.debug(f"{user.mxid} left portal to {self.chat_id}")
  528. # TODO cleanup if empty
  529. async def handle_matrix_name(self, user: u.User, name: str) -> None:
  530. if self.name == name or self.is_direct or not name:
  531. return
  532. sender, is_relay = await self.get_relay_sender(user, "name change")
  533. if not sender:
  534. return
  535. self.name = name
  536. self.log.debug(
  537. f"{user.mxid} changed the group name, sending to Signal through {sender.username}"
  538. )
  539. try:
  540. await self.signal.update_group(sender.username, self.chat_id, title=name)
  541. except Exception:
  542. self.log.exception("Failed to update Signal group name")
  543. self.name = None
  544. async def handle_matrix_avatar(self, user: u.User, url: ContentURI) -> None:
  545. if self.is_direct or not url:
  546. return
  547. sender, is_relay = await self.get_relay_sender(user, "avatar change")
  548. if not sender:
  549. return
  550. data = await self.main_intent.download_media(url)
  551. new_hash = hashlib.sha256(data).hexdigest()
  552. if new_hash == self.avatar_hash and self.avatar_set:
  553. self.log.debug(f"New avatar from Matrix set by {user.mxid} is same as current one")
  554. return
  555. self.avatar_url = url
  556. self.avatar_hash = new_hash
  557. path = self._write_outgoing_file(data)
  558. self.log.debug(
  559. f"{user.mxid} changed the group avatar, sending to Signal through {sender.username}"
  560. )
  561. try:
  562. await self.signal.update_group(sender.username, self.chat_id, avatar_path=path)
  563. self.avatar_set = True
  564. except Exception:
  565. self.log.exception("Failed to update Signal group avatar")
  566. self.avatar_set = False
  567. if self.config["signal.remove_file_after_handling"]:
  568. try:
  569. os.remove(path)
  570. except FileNotFoundError:
  571. pass
  572. @classmethod
  573. async def _expire_event(cls, room_id: RoomID, event_id: EventID, restart: bool = False):
  574. """
  575. Schedule a task to expire a an event. This should only be called once the message has been
  576. read, as the timer for redaction will start immediately, and there is no (supported)
  577. mechanism to stop the countdown, even after bridge restart.
  578. If there is already an expiration event for the given ``room_id`` and ``event_id``, it will
  579. not schedule a new task.
  580. """
  581. portal = await cls.get_by_mxid(room_id)
  582. if not portal:
  583. raise AttributeError(f"No portal found for {room_id}")
  584. # Need a lock around this critical section to make sure that we know if a task has been
  585. # created for this particular (room_id, event_id) combination.
  586. async with portal._expiration_lock:
  587. if (
  588. not portal.is_direct
  589. and not cls.config["signal.enable_disappearing_messages_in_groups"]
  590. ):
  591. portal.log.debug(
  592. "Not expiring event in group message since "
  593. "signal.enable_disappearing_messages_in_groups is not enabled."
  594. )
  595. await DisappearingMessage.delete(room_id, event_id)
  596. return
  597. disappearing_message = await DisappearingMessage.get(room_id, event_id)
  598. if disappearing_message is None:
  599. return
  600. wait = disappearing_message.expiration_seconds
  601. now = time.time()
  602. # If there is an expiration_ts, then there's already a task going, or it's a restart.
  603. # If it's a restart, then restart the countdown. This is fairly likely to occur if the
  604. # disappearance timeout is weeks.
  605. if disappearing_message.expiration_ts:
  606. if not restart:
  607. portal.log.debug(f"Expiration task already exists for {event_id} in {room_id}")
  608. return
  609. portal.log.debug(f"Resuming expiration for {event_id} in {room_id}")
  610. wait = (disappearing_message.expiration_ts / 1000) - now
  611. if wait < 0:
  612. wait = 0
  613. # Spawn the actual expiration task.
  614. asyncio.create_task(cls._expire_event_task(portal, event_id, wait))
  615. # Set the expiration_ts only after we have actually created the expiration task.
  616. if not disappearing_message.expiration_ts:
  617. disappearing_message.expiration_ts = int((now + wait) * 1000)
  618. await disappearing_message.update()
  619. @classmethod
  620. async def _expire_event_task(cls, portal: Portal, event_id: EventID, wait: float):
  621. portal.log.debug(f"Redacting {event_id} in {wait} seconds")
  622. await asyncio.sleep(wait)
  623. async with portal._expiration_lock:
  624. if not await DisappearingMessage.get(portal.mxid, event_id):
  625. portal.log.debug(
  626. f"{event_id} no longer in disappearing messages list, not redacting"
  627. )
  628. return
  629. portal.log.debug(f"Redacting {event_id} because it was expired")
  630. try:
  631. await portal.main_intent.redact(portal.mxid, event_id)
  632. portal.log.debug(f"Redacted {event_id} successfully")
  633. except Exception as e:
  634. portal.log.warning(f"Redacting expired event {event_id} failed", e)
  635. finally:
  636. await DisappearingMessage.delete(portal.mxid, event_id)
  637. async def handle_read_receipt(self, event_id: EventID, data: SingleReceiptEventContent):
  638. # Start the redaction timers for all of the disappearing messages in the room when the user
  639. # reads the room. This is the behavior of the Signal clients.
  640. await asyncio.gather(
  641. *(
  642. Portal._expire_event(dm.room_id, dm.mxid)
  643. for dm in await DisappearingMessage.get_all_for_room(self.mxid)
  644. )
  645. )
  646. # endregion
  647. # region Signal event handling
  648. @staticmethod
  649. async def _resolve_address(address: Address) -> Address:
  650. puppet = await p.Puppet.get_by_address(address, create=False)
  651. return puppet.address
  652. async def _find_quote_event_id(self, quote: Quote | None) -> MessageEvent | EventID | None:
  653. if not quote:
  654. return None
  655. author_address = await self._resolve_address(quote.author)
  656. reply_msg = await DBMessage.get_by_signal_id(
  657. author_address, quote.id, self.chat_id, self.receiver
  658. )
  659. if not reply_msg:
  660. return None
  661. try:
  662. evt = await self.main_intent.get_event(self.mxid, reply_msg.mxid)
  663. if isinstance(evt, EncryptedEvent):
  664. return await self.matrix.e2ee.decrypt(evt, wait_session_timeout=0)
  665. return evt
  666. except MatrixError:
  667. return reply_msg.mxid
  668. async def handle_signal_message(
  669. self, source: u.User, sender: p.Puppet, message: MessageData
  670. ) -> None:
  671. if (sender.address, message.timestamp) in self._msgts_dedup:
  672. self.log.debug(
  673. f"Ignoring message {message.timestamp} by {sender.uuid} as it was already handled "
  674. "(message.timestamp in dedup queue)"
  675. )
  676. await self.signal.send_receipt(
  677. source.username, sender.address, timestamps=[message.timestamp]
  678. )
  679. return
  680. old_message = await DBMessage.get_by_signal_id(
  681. sender.address, message.timestamp, self.chat_id, self.receiver
  682. )
  683. if old_message is not None:
  684. self.log.debug(
  685. f"Ignoring message {message.timestamp} by {sender.uuid} as it was already handled "
  686. "(message.id found in database)"
  687. )
  688. await self.signal.send_receipt(
  689. source.username, sender.address, timestamps=[message.timestamp]
  690. )
  691. return
  692. self.log.debug(f"Started handling message {message.timestamp} by {sender.uuid}")
  693. self.log.trace(f"Message content: {message}")
  694. self._msgts_dedup.appendleft((sender.address, message.timestamp))
  695. intent = sender.intent_for(self)
  696. await intent.set_typing(self.mxid, False)
  697. event_id = None
  698. reply_to = await self._find_quote_event_id(message.quote)
  699. if message.sticker:
  700. if message.sticker.attachment.incoming_filename:
  701. content = await self._handle_signal_attachment(
  702. intent, message.sticker.attachment, sticker=True
  703. )
  704. elif StickersClient:
  705. content = await self._handle_signal_sticker(intent, message.sticker)
  706. else:
  707. self.log.debug(
  708. f"Not handling sticker in {message.timestamp}: no incoming_filename and "
  709. "signalstickers-client not installed."
  710. )
  711. return
  712. if content:
  713. if message.sticker.attachment.blurhash:
  714. content.info["blurhash"] = message.sticker.attachment.blurhash
  715. content.info["xyz.amorgan.blurhash"] = message.sticker.attachment.blurhash
  716. await self._add_sticker_meta(message.sticker, content)
  717. if reply_to and not message.body:
  718. content.set_reply(reply_to)
  719. reply_to = None
  720. event_id = await self._send_message(
  721. intent, content, timestamp=message.timestamp, event_type=EventType.STICKER
  722. )
  723. for attachment in message.attachments:
  724. if not attachment.incoming_filename:
  725. self.log.warning(
  726. "Failed to bridge attachment, no incoming filename: %s", attachment
  727. )
  728. continue
  729. content = await self._handle_signal_attachment(intent, attachment)
  730. if reply_to and not message.body:
  731. # If there's no text, set the first image as the reply
  732. content.set_reply(reply_to)
  733. reply_to = None
  734. event_id = await self._send_message(intent, content, timestamp=message.timestamp)
  735. if message.body:
  736. content = await signal_to_matrix(message)
  737. if reply_to:
  738. content.set_reply(reply_to)
  739. event_id = await self._send_message(intent, content, timestamp=message.timestamp)
  740. if event_id:
  741. msg = DBMessage(
  742. mxid=event_id,
  743. mx_room=self.mxid,
  744. sender=sender.address,
  745. timestamp=message.timestamp,
  746. signal_chat_id=self.chat_id,
  747. signal_receiver=self.receiver,
  748. )
  749. await msg.insert()
  750. await self.signal.send_receipt(
  751. source.username, sender.address, timestamps=[message.timestamp]
  752. )
  753. await self._send_delivery_receipt(event_id)
  754. self.log.debug(f"Handled Signal message {message.timestamp} -> {event_id}")
  755. if message.expires_in_seconds and (
  756. self.is_direct or self.config["signal.enable_disappearing_messages_in_groups"]
  757. ):
  758. disappearing_message = DisappearingMessage(
  759. self.mxid, event_id, message.expires_in_seconds
  760. )
  761. await disappearing_message.insert()
  762. self.log.debug(
  763. f"{event_id} set to be redacted {message.expires_in_seconds} seconds after "
  764. "room is read"
  765. )
  766. else:
  767. self.log.debug(f"Didn't get event ID for {message.timestamp}")
  768. @staticmethod
  769. def _make_media_content(attachment: Attachment) -> MediaMessageEventContent:
  770. if attachment.content_type.startswith("image/"):
  771. msgtype = MessageType.IMAGE
  772. info = ImageInfo(
  773. mimetype=attachment.content_type, width=attachment.width, height=attachment.height
  774. )
  775. elif attachment.content_type.startswith("video/"):
  776. msgtype = MessageType.VIDEO
  777. info = VideoInfo(
  778. mimetype=attachment.content_type, width=attachment.width, height=attachment.height
  779. )
  780. elif attachment.voice_note or attachment.content_type.startswith("audio/"):
  781. msgtype = MessageType.AUDIO
  782. info = AudioInfo(mimetype=attachment.content_type)
  783. else:
  784. msgtype = MessageType.FILE
  785. info = FileInfo(mimetype=attachment.content_type)
  786. if not attachment.custom_filename:
  787. ext = mimetypes.guess_extension(attachment.content_type) or ""
  788. attachment.custom_filename = attachment.id + ext
  789. if attachment.blurhash:
  790. info["blurhash"] = attachment.blurhash
  791. info["xyz.amorgan.blurhash"] = attachment.blurhash
  792. return MediaMessageEventContent(
  793. msgtype=msgtype, info=info, body=attachment.custom_filename
  794. )
  795. async def _handle_signal_attachment(
  796. self, intent: IntentAPI, attachment: Attachment, sticker: bool = False
  797. ) -> MediaMessageEventContent:
  798. self.log.trace(f"Reuploading attachment {attachment}")
  799. if not attachment.content_type:
  800. attachment.content_type = (
  801. magic.from_file(attachment.incoming_filename, mime=True)
  802. if magic is not None
  803. else "application/octet-stream"
  804. )
  805. content = self._make_media_content(attachment)
  806. if sticker:
  807. self._adjust_sticker_size(content.info)
  808. with open(attachment.incoming_filename, "rb") as file:
  809. data = file.read()
  810. if self.config["signal.remove_file_after_handling"]:
  811. os.remove(attachment.incoming_filename)
  812. await self._upload_attachment(intent, content, data, attachment.id)
  813. return content
  814. async def _add_sticker_meta(self, sticker: Sticker, content: MediaMessageEventContent) -> None:
  815. try:
  816. pack = self._sticker_meta_cache[sticker.pack_id]
  817. except KeyError:
  818. self.log.debug(f"Fetching sticker pack metadata for {sticker.pack_id}")
  819. try:
  820. async with StickersClient() as client:
  821. pack = await client.get_pack_metadata(sticker.pack_id, sticker.pack_key)
  822. self._sticker_meta_cache[sticker.pack_id] = pack
  823. except Exception:
  824. self.log.warning(
  825. f"Failed to fetch pack metadata for {sticker.pack_id}", exc_info=True
  826. )
  827. pack = None
  828. if not pack:
  829. content.info["fi.mau.signal.sticker"] = {
  830. "id": sticker.sticker_id,
  831. "pack": {
  832. "id": sticker.pack_id,
  833. "key": sticker.pack_key,
  834. },
  835. }
  836. return
  837. sticker_meta = pack.stickers[sticker.sticker_id]
  838. content.body = sticker_meta.emoji
  839. content.info["fi.mau.signal.sticker"] = {
  840. "id": sticker.sticker_id,
  841. "emoji": sticker_meta.emoji,
  842. "pack": {
  843. "id": pack.id,
  844. "key": pack.key,
  845. "title": pack.title,
  846. "author": pack.author,
  847. },
  848. }
  849. @staticmethod
  850. def _adjust_sticker_size(info: ImageInfo) -> None:
  851. if info.width > 256 or info.height > 256:
  852. if info.width == info.height:
  853. info.width = info.height = 256
  854. elif info.width > info.height:
  855. info.height = int(info.height / (info.width / 256))
  856. info.width = 256
  857. else:
  858. info.width = int(info.width / (info.height / 256))
  859. info.height = 256
  860. async def _handle_signal_sticker(
  861. self, intent: IntentAPI, sticker: Sticker
  862. ) -> MediaMessageEventContent | None:
  863. try:
  864. self.log.debug(f"Fetching sticker {sticker.pack_id}#{sticker.sticker_id}")
  865. async with StickersClient() as client:
  866. data = await client.download_sticker(
  867. sticker.sticker_id, sticker.pack_id, sticker.pack_key
  868. )
  869. except Exception:
  870. self.log.warning(f"Failed to download sticker {sticker.sticker_id}", exc_info=True)
  871. return None
  872. info = ImageInfo(
  873. mimetype=sticker.attachment.content_type,
  874. size=len(data),
  875. width=sticker.attachment.width,
  876. height=sticker.attachment.height,
  877. )
  878. self._adjust_sticker_size(info)
  879. if magic:
  880. info.mimetype = magic.from_buffer(data, mime=True)
  881. ext = mimetypes.guess_extension(info.mimetype)
  882. if not ext and info.mimetype == "image/webp":
  883. ext = ".webp"
  884. content = MediaMessageEventContent(
  885. msgtype=MessageType.IMAGE, info=info, body=f"sticker{ext}"
  886. )
  887. await self._upload_attachment(intent, content, data, sticker.attachment.id)
  888. return content
  889. async def _upload_attachment(
  890. self, intent: IntentAPI, content: MediaMessageEventContent, data: bytes, id: str
  891. ) -> None:
  892. upload_mime_type = content.info.mimetype
  893. if self.encrypted and encrypt_attachment:
  894. data, content.file = encrypt_attachment(data)
  895. upload_mime_type = "application/octet-stream"
  896. content.url = await intent.upload_media(data, mime_type=upload_mime_type, filename=id)
  897. if content.file:
  898. content.file.url = content.url
  899. content.url = None
  900. # This is a hack for bad clients like Element iOS that require a thumbnail
  901. if content.info.mimetype.startswith("image/"):
  902. if content.file:
  903. content.info.thumbnail_file = content.file
  904. elif content.url:
  905. content.info.thumbnail_url = content.url
  906. async def handle_signal_reaction(
  907. self, sender: p.Puppet, reaction: Reaction, timestamp: int
  908. ) -> None:
  909. author_address = await self._resolve_address(reaction.target_author)
  910. target_id = reaction.target_sent_timestamp
  911. async with self._reaction_lock:
  912. dedup_id = (author_address, target_id, reaction.emoji)
  913. if dedup_id in self._reaction_dedup:
  914. return
  915. self._reaction_dedup.appendleft(dedup_id)
  916. existing = await DBReaction.get_by_signal_id(
  917. self.chat_id, self.receiver, author_address, target_id, sender.address
  918. )
  919. if reaction.remove:
  920. if existing:
  921. try:
  922. await sender.intent_for(self).redact(existing.mx_room, existing.mxid)
  923. except IntentError:
  924. await self.main_intent.redact(existing.mx_room, existing.mxid)
  925. await existing.delete()
  926. self.log.trace(f"Removed {existing} after Signal removal")
  927. return
  928. elif existing and existing.emoji == reaction.emoji:
  929. return
  930. message = await DBMessage.get_by_signal_id(
  931. author_address, target_id, self.chat_id, self.receiver
  932. )
  933. if not message:
  934. self.log.debug(f"Ignoring reaction to unknown message {target_id}")
  935. return
  936. intent = sender.intent_for(self)
  937. # TODO add variation selectors to emoji before sending to Matrix
  938. mxid = await intent.react(
  939. message.mx_room, message.mxid, reaction.emoji, timestamp=timestamp
  940. )
  941. self.log.debug(f"{sender.address} reacted to {message.mxid} -> {mxid}")
  942. await self._upsert_reaction(existing, intent, mxid, sender, message, reaction.emoji)
  943. async def handle_signal_delete(self, sender: p.Puppet, message_ts: int) -> None:
  944. message = await DBMessage.get_by_signal_id(
  945. sender.address, message_ts, self.chat_id, self.receiver
  946. )
  947. if not message:
  948. return
  949. await message.delete()
  950. try:
  951. await sender.intent_for(self).redact(message.mx_room, message.mxid)
  952. except MForbidden:
  953. await self.main_intent.redact(message.mx_room, message.mxid)
  954. # endregion
  955. # region Updating portal info
  956. async def update_info(
  957. self, source: u.User, info: ChatInfo, sender: p.Puppet | None = None
  958. ) -> None:
  959. if self.is_direct:
  960. if not isinstance(info, (Contact, Profile, Address)):
  961. raise ValueError(f"Unexpected type for direct chat update_info: {type(info)}")
  962. if not self.name:
  963. puppet = await p.Puppet.get_by_address(self.chat_id)
  964. if not puppet.name:
  965. await puppet.update_info(info)
  966. self.name = puppet.name
  967. return
  968. if isinstance(info, GroupV2ID):
  969. info = await self.signal.get_group(source.username, info.id, info.revision or -1)
  970. if not info:
  971. self.log.debug(
  972. f"Failed to get full group v2 info through {source.username}, "
  973. "cancelling update"
  974. )
  975. return
  976. changed = False
  977. if isinstance(info, Group):
  978. changed = await self._update_name(info.name, sender) or changed
  979. elif isinstance(info, GroupV2):
  980. if self.revision < info.revision:
  981. self.revision = info.revision
  982. changed = True
  983. elif self.revision > info.revision:
  984. self.log.warning(
  985. f"Got outdated info when syncing through {source.username} "
  986. f"({info.revision} < {self.revision}), ignoring..."
  987. )
  988. return
  989. changed = await self._update_name(info.title, sender) or changed
  990. elif isinstance(info, GroupV2ID):
  991. return
  992. else:
  993. raise ValueError(f"Unexpected type for group update_info: {type(info)}")
  994. changed = await self._update_avatar(info, sender) or changed
  995. await self._update_participants(source, info)
  996. try:
  997. await self._update_power_levels(info)
  998. except Exception:
  999. self.log.warning("Error updating power levels", exc_info=True)
  1000. if changed:
  1001. await self.update_bridge_info()
  1002. await self.update()
  1003. async def update_expires_in_seconds(self, sender: p.Puppet, expires_in_seconds: int) -> None:
  1004. if expires_in_seconds == 0:
  1005. expires_in_seconds = None
  1006. if self.expiration_time == expires_in_seconds:
  1007. return
  1008. assert self.mxid
  1009. self.expiration_time = expires_in_seconds
  1010. await self.update()
  1011. time_str = "Off" if expires_in_seconds is None else format_duration(expires_in_seconds)
  1012. await self.main_intent.send_notice(
  1013. self.mxid,
  1014. html=f'<a href="https://matrix.to/#/{sender.mxid}">{sender.name}</a> set the '
  1015. f"disappearing message timer to {time_str}.",
  1016. )
  1017. async def update_puppet_avatar(self, new_hash: str, avatar_url: ContentURI) -> None:
  1018. if not self.encrypted and not self.private_chat_portal_meta:
  1019. return
  1020. if self.avatar_hash != new_hash or not self.avatar_set:
  1021. self.avatar_hash = new_hash
  1022. self.avatar_url = avatar_url
  1023. if self.mxid:
  1024. try:
  1025. await self.main_intent.set_room_avatar(self.mxid, avatar_url)
  1026. self.avatar_set = True
  1027. except Exception:
  1028. self.log.exception("Error setting avatar")
  1029. self.avatar_set = False
  1030. await self.update_bridge_info()
  1031. await self.update()
  1032. async def update_puppet_name(self, name: str) -> None:
  1033. if not self.encrypted and not self.private_chat_portal_meta:
  1034. return
  1035. changed = await self._update_name(name)
  1036. if changed:
  1037. await self.update_bridge_info()
  1038. await self.update()
  1039. async def _update_name(self, name: str, sender: p.Puppet | None = None) -> bool:
  1040. if self.name != name or not self.name_set:
  1041. self.name = name
  1042. if self.mxid:
  1043. try:
  1044. await self._try_with_puppet(
  1045. lambda i: i.set_room_name(self.mxid, self.name), puppet=sender
  1046. )
  1047. self.name_set = True
  1048. except Exception:
  1049. self.log.exception("Error setting name")
  1050. self.name_set = False
  1051. return True
  1052. return False
  1053. async def _try_with_puppet(
  1054. self, action: Callable[[IntentAPI], Awaitable[Any]], puppet: p.Puppet | None = None
  1055. ) -> None:
  1056. if puppet:
  1057. try:
  1058. await action(puppet.intent_for(self))
  1059. except (MForbidden, IntentError):
  1060. await action(self.main_intent)
  1061. else:
  1062. await action(self.main_intent)
  1063. async def _update_avatar(self, info: ChatInfo, sender: p.Puppet | None = None) -> bool:
  1064. path = None
  1065. if isinstance(info, GroupV2):
  1066. path = info.avatar
  1067. elif isinstance(info, Group):
  1068. path = f"group-{self.chat_id}"
  1069. res = await p.Puppet.upload_avatar(self, path, self.main_intent)
  1070. if res is False:
  1071. return False
  1072. self.avatar_hash, self.avatar_url = res
  1073. if not self.mxid:
  1074. return True
  1075. try:
  1076. await self._try_with_puppet(
  1077. lambda i: i.set_room_avatar(self.mxid, self.avatar_url), puppet=sender
  1078. )
  1079. self.avatar_set = True
  1080. except Exception:
  1081. self.log.exception("Error setting avatar")
  1082. self.avatar_set = False
  1083. return True
  1084. async def _update_participants(self, source: u.User, info: ChatInfo) -> None:
  1085. if not self.mxid or not isinstance(info, (Group, GroupV2)):
  1086. return
  1087. pending_members = info.pending_members if isinstance(info, GroupV2) else []
  1088. self._pending_members = {addr.uuid for addr in pending_members}
  1089. for address in info.members:
  1090. user = await u.User.get_by_address(address)
  1091. if user:
  1092. await self.main_intent.invite_user(self.mxid, user.mxid)
  1093. puppet = await p.Puppet.get_by_address(address)
  1094. await source.sync_contact(address)
  1095. await puppet.intent_for(self).ensure_joined(self.mxid)
  1096. for address in pending_members:
  1097. user = await u.User.get_by_address(address)
  1098. if user:
  1099. await self.main_intent.invite_user(self.mxid, user.mxid)
  1100. puppet = await p.Puppet.get_by_address(address)
  1101. await source.sync_contact(address)
  1102. await self.main_intent.invite_user(self.mxid, puppet.intent_for(self).mxid)
  1103. async def _update_power_levels(self, info: ChatInfo) -> None:
  1104. if not self.mxid:
  1105. return
  1106. power_levels = await self.main_intent.get_power_levels(self.mxid)
  1107. power_levels = await self._get_power_levels(power_levels, info=info, is_initial=False)
  1108. await self.main_intent.set_power_levels(self.mxid, power_levels)
  1109. # endregion
  1110. # region Bridge info state event
  1111. @property
  1112. def bridge_info_state_key(self) -> str:
  1113. return f"net.maunium.signal://signal/{self.chat_id}"
  1114. @property
  1115. def bridge_info(self) -> dict[str, Any]:
  1116. return {
  1117. "bridgebot": self.az.bot_mxid,
  1118. "creator": self.main_intent.mxid,
  1119. "protocol": {
  1120. "id": "signal",
  1121. "displayname": "Signal",
  1122. "avatar_url": self.config["appservice.bot_avatar"],
  1123. },
  1124. "channel": {
  1125. "id": str(self.chat_id),
  1126. "displayname": self.name,
  1127. "avatar_url": self.avatar_url,
  1128. },
  1129. }
  1130. async def update_bridge_info(self) -> None:
  1131. if not self.mxid:
  1132. self.log.debug("Not updating bridge info: no Matrix room created")
  1133. return
  1134. try:
  1135. self.log.debug("Updating bridge info...")
  1136. await self.main_intent.send_state_event(
  1137. self.mxid, StateBridge, self.bridge_info, self.bridge_info_state_key
  1138. )
  1139. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  1140. await self.main_intent.send_state_event(
  1141. self.mxid, StateHalfShotBridge, self.bridge_info, self.bridge_info_state_key
  1142. )
  1143. except Exception:
  1144. self.log.warning("Failed to update bridge info", exc_info=True)
  1145. # endregion
  1146. # region Creating Matrix rooms
  1147. async def update_matrix_room(self, source: u.User, info: ChatInfo) -> None:
  1148. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  1149. raise ValueError(f"Unexpected type for updating group portal: {type(info)}")
  1150. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  1151. raise ValueError(f"Unexpected type for updating direct chat portal: {type(info)}")
  1152. try:
  1153. await self._update_matrix_room(source, info)
  1154. except Exception:
  1155. self.log.exception("Failed to update portal")
  1156. async def create_matrix_room(self, source: u.User, info: ChatInfo) -> RoomID | None:
  1157. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  1158. raise ValueError(f"Unexpected type for creating group portal: {type(info)}")
  1159. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  1160. raise ValueError(f"Unexpected type for creating direct chat portal: {type(info)}")
  1161. if isinstance(info, Group) and not info.members:
  1162. groups = await self.signal.list_groups(source.username)
  1163. info = next(
  1164. (g for g in groups if isinstance(g, Group) and g.group_id == info.group_id), info
  1165. )
  1166. elif isinstance(info, GroupV2ID) and not isinstance(info, GroupV2):
  1167. self.log.debug(
  1168. f"create_matrix_room() called with {info}, " "fetching full info from signald"
  1169. )
  1170. info = await self.signal.get_group(source.username, info.id, info.revision or -1)
  1171. if not info:
  1172. self.log.warning(f"Full info not found, canceling room creation")
  1173. return None
  1174. else:
  1175. self.log.trace("get_group() returned full info: %s", info)
  1176. if self.mxid:
  1177. await self.update_matrix_room(source, info)
  1178. return self.mxid
  1179. async with self._create_room_lock:
  1180. return await self._create_matrix_room(source, info)
  1181. def _get_invite_content(self, double_puppet: p.Puppet | None) -> dict[str, Any]:
  1182. invite_content = {}
  1183. if double_puppet:
  1184. invite_content["fi.mau.will_auto_accept"] = True
  1185. if self.is_direct:
  1186. invite_content["is_direct"] = True
  1187. return invite_content
  1188. async def _update_matrix_room(self, source: u.User, info: ChatInfo) -> None:
  1189. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  1190. await self.main_intent.invite_user(
  1191. self.mxid,
  1192. source.mxid,
  1193. check_cache=True,
  1194. extra_content=self._get_invite_content(puppet),
  1195. )
  1196. if puppet:
  1197. did_join = await puppet.intent.ensure_joined(self.mxid)
  1198. if did_join and self.is_direct:
  1199. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  1200. await self.update_info(source, info)
  1201. async def _get_power_levels(
  1202. self,
  1203. levels: PowerLevelStateEventContent | None = None,
  1204. info: ChatInfo | None = None,
  1205. is_initial: bool = False,
  1206. ) -> PowerLevelStateEventContent:
  1207. levels = levels or PowerLevelStateEventContent()
  1208. if self.is_direct:
  1209. levels.ban = 99
  1210. levels.kick = 99
  1211. levels.invite = 99
  1212. levels.state_default = 0
  1213. meta_edit_level = 0
  1214. else:
  1215. if isinstance(info, GroupV2):
  1216. ac = info.access_control
  1217. for detail in info.member_detail + info.pending_member_detail:
  1218. puppet = await p.Puppet.get_by_address(Address(uuid=detail.uuid))
  1219. level = 50 if detail.role == GroupMemberRole.ADMINISTRATOR else 0
  1220. levels.users[puppet.intent_for(self).mxid] = level
  1221. else:
  1222. ac = GroupAccessControl()
  1223. levels.ban = 50
  1224. levels.kick = 50
  1225. levels.invite = 50 if ac.members == AccessControlMode.ADMINISTRATOR else 0
  1226. levels.state_default = 50
  1227. meta_edit_level = 50 if ac.attributes == AccessControlMode.ADMINISTRATOR else 0
  1228. levels.events[EventType.ROOM_NAME] = meta_edit_level
  1229. levels.events[EventType.ROOM_AVATAR] = meta_edit_level
  1230. levels.events[EventType.ROOM_TOPIC] = meta_edit_level
  1231. levels.events[EventType.ROOM_ENCRYPTION] = 50 if self.matrix.e2ee else 99
  1232. levels.events[EventType.ROOM_TOMBSTONE] = 99
  1233. levels.users_default = 0
  1234. levels.events_default = 0
  1235. # Remote delete is only for your own messages
  1236. levels.redact = 99
  1237. if self.main_intent.mxid not in levels.users:
  1238. levels.users[self.main_intent.mxid] = 9001 if is_initial else 100
  1239. return levels
  1240. async def _create_matrix_room(self, source: u.User, info: ChatInfo) -> RoomID | None:
  1241. if self.mxid:
  1242. await self._update_matrix_room(source, info)
  1243. return self.mxid
  1244. await self.update_info(source, info)
  1245. self.log.debug("Creating Matrix room")
  1246. name: str | None = None
  1247. power_levels = await self._get_power_levels(info=info, is_initial=True)
  1248. initial_state = [
  1249. {
  1250. "type": str(StateBridge),
  1251. "state_key": self.bridge_info_state_key,
  1252. "content": self.bridge_info,
  1253. },
  1254. {
  1255. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  1256. "type": str(StateHalfShotBridge),
  1257. "state_key": self.bridge_info_state_key,
  1258. "content": self.bridge_info,
  1259. },
  1260. {
  1261. "type": str(EventType.ROOM_POWER_LEVELS),
  1262. "content": power_levels.serialize(),
  1263. },
  1264. ]
  1265. invites = []
  1266. if self.config["bridge.encryption.default"] and self.matrix.e2ee:
  1267. self.encrypted = True
  1268. initial_state.append(
  1269. {
  1270. "type": str(EventType.ROOM_ENCRYPTION),
  1271. "content": {"algorithm": "m.megolm.v1.aes-sha2"},
  1272. }
  1273. )
  1274. if self.is_direct:
  1275. invites.append(self.az.bot_mxid)
  1276. if self.is_direct and source.address == self.chat_id:
  1277. name = self.name = "Signal Note to Self"
  1278. elif self.encrypted or self.private_chat_portal_meta or not self.is_direct:
  1279. name = self.name
  1280. if self.avatar_url:
  1281. initial_state.append(
  1282. {
  1283. "type": str(EventType.ROOM_AVATAR),
  1284. "content": {"url": self.avatar_url},
  1285. }
  1286. )
  1287. if self.config["appservice.community_id"]:
  1288. initial_state.append(
  1289. {
  1290. "type": "m.room.related_groups",
  1291. "content": {"groups": [self.config["appservice.community_id"]]},
  1292. }
  1293. )
  1294. creation_content = {}
  1295. if not self.config["bridge.federate_rooms"]:
  1296. creation_content["m.federate"] = False
  1297. self.mxid = await self.main_intent.create_room(
  1298. name=name,
  1299. is_direct=self.is_direct,
  1300. initial_state=initial_state,
  1301. invitees=invites,
  1302. creation_content=creation_content,
  1303. )
  1304. if not self.mxid:
  1305. raise Exception("Failed to create room: no mxid returned")
  1306. self.name_set = bool(name)
  1307. self.avatar_set = bool(self.avatar_url)
  1308. if self.encrypted and self.matrix.e2ee and self.is_direct:
  1309. try:
  1310. await self.az.intent.ensure_joined(self.mxid)
  1311. except Exception:
  1312. self.log.warning("Failed to add bridge bot to new private chat {self.mxid}")
  1313. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  1314. await self.main_intent.invite_user(
  1315. self.mxid, source.mxid, extra_content=self._get_invite_content(puppet)
  1316. )
  1317. if puppet:
  1318. try:
  1319. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  1320. await puppet.intent.join_room_by_id(self.mxid)
  1321. except MatrixError:
  1322. self.log.debug(
  1323. "Failed to join custom puppet into newly created portal", exc_info=True
  1324. )
  1325. await self.update()
  1326. self.log.debug(f"Matrix room created: {self.mxid}")
  1327. self.by_mxid[self.mxid] = self
  1328. if not self.is_direct:
  1329. await self._update_participants(source, info)
  1330. # TODO
  1331. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  1332. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  1333. # in_community=in_community).upsert()
  1334. return self.mxid
  1335. # endregion
  1336. # region Database getters
  1337. async def _postinit(self) -> None:
  1338. self.by_chat_id[(self.chat_id_str, self.receiver)] = self
  1339. if self.mxid:
  1340. self.by_mxid[self.mxid] = self
  1341. if self.is_direct:
  1342. puppet = await p.Puppet.get_by_address(self.chat_id)
  1343. self._main_intent = puppet.default_mxid_intent
  1344. elif not self.is_direct:
  1345. self._main_intent = self.az.intent
  1346. async def delete(self) -> None:
  1347. await DBMessage.delete_all(self.mxid)
  1348. self.by_mxid.pop(self.mxid, None)
  1349. self.mxid = None
  1350. self.encrypted = False
  1351. await self.update()
  1352. async def save(self) -> None:
  1353. await self.update()
  1354. @classmethod
  1355. def all_with_room(cls) -> AsyncGenerator[Portal, None]:
  1356. return cls._db_to_portals(super().all_with_room())
  1357. @classmethod
  1358. def find_private_chats_with(cls, other_user: Address) -> AsyncGenerator[Portal, None]:
  1359. return cls._db_to_portals(super().find_private_chats_with(other_user))
  1360. @classmethod
  1361. async def _db_to_portals(cls, query: Awaitable[list[Portal]]) -> AsyncGenerator[Portal, None]:
  1362. portals = await query
  1363. for index, portal in enumerate(portals):
  1364. try:
  1365. yield cls.by_chat_id[(portal.chat_id_str, portal.receiver)]
  1366. except KeyError:
  1367. await portal._postinit()
  1368. yield portal
  1369. @classmethod
  1370. @async_getter_lock
  1371. async def get_by_mxid(cls, mxid: RoomID) -> Portal | None:
  1372. try:
  1373. return cls.by_mxid[mxid]
  1374. except KeyError:
  1375. pass
  1376. portal = cast(cls, await super().get_by_mxid(mxid))
  1377. if portal is not None:
  1378. await portal._postinit()
  1379. return portal
  1380. return None
  1381. @classmethod
  1382. async def get_by_chat_id(
  1383. cls, chat_id: GroupID | Address, *, receiver: str = "", create: bool = False
  1384. ) -> Portal | None:
  1385. if isinstance(chat_id, str):
  1386. receiver = ""
  1387. elif not isinstance(chat_id, Address):
  1388. raise ValueError(f"Invalid chat ID type {type(chat_id)}")
  1389. elif not receiver:
  1390. raise ValueError("Direct chats must have a receiver")
  1391. best_id = id_to_str(chat_id)
  1392. portal = await cls._get_by_chat_id(best_id, receiver, create=create, chat_id=chat_id)
  1393. if portal:
  1394. portal.log.debug(f"get_by_chat_id({chat_id}, {receiver}) -> {hex(id(portal))}")
  1395. return portal
  1396. @classmethod
  1397. @async_getter_lock
  1398. async def _get_by_chat_id(
  1399. cls, best_id: str, receiver: str, *, create: bool, chat_id: GroupID | Address
  1400. ) -> Portal | None:
  1401. try:
  1402. return cls.by_chat_id[(best_id, receiver)]
  1403. except KeyError:
  1404. pass
  1405. portal = cast(cls, await super().get_by_chat_id(chat_id, receiver))
  1406. if portal is not None:
  1407. await portal._postinit()
  1408. return portal
  1409. if create:
  1410. portal = cls(chat_id, receiver)
  1411. await portal.insert()
  1412. await portal._postinit()
  1413. return portal
  1414. return None
  1415. # endregion