portal.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567
  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. content = MediaMessageEventContent(
  793. msgtype=msgtype, info=info, body=attachment.custom_filename
  794. )
  795. # Add the additional voice message metadata.
  796. if attachment.voice_note:
  797. content["org.matrix.msc1767.file"] = {
  798. "url": content.url,
  799. "name": content.body,
  800. **(content.file.serialize() if content.file else {}),
  801. **(content.info.serialize() if content.info else {}),
  802. }
  803. content["org.matrix.msc3245.voice"] = {}
  804. return content
  805. async def _handle_signal_attachment(
  806. self, intent: IntentAPI, attachment: Attachment, sticker: bool = False
  807. ) -> MediaMessageEventContent:
  808. self.log.trace(f"Reuploading attachment {attachment}")
  809. if not attachment.content_type:
  810. attachment.content_type = (
  811. magic.from_file(attachment.incoming_filename, mime=True)
  812. if magic is not None
  813. else "application/octet-stream"
  814. )
  815. content = self._make_media_content(attachment)
  816. if sticker:
  817. self._adjust_sticker_size(content.info)
  818. with open(attachment.incoming_filename, "rb") as file:
  819. data = file.read()
  820. if self.config["signal.remove_file_after_handling"]:
  821. os.remove(attachment.incoming_filename)
  822. await self._upload_attachment(intent, content, data, attachment.id)
  823. return content
  824. async def _add_sticker_meta(self, sticker: Sticker, content: MediaMessageEventContent) -> None:
  825. try:
  826. pack = self._sticker_meta_cache[sticker.pack_id]
  827. except KeyError:
  828. self.log.debug(f"Fetching sticker pack metadata for {sticker.pack_id}")
  829. try:
  830. async with StickersClient() as client:
  831. pack = await client.get_pack_metadata(sticker.pack_id, sticker.pack_key)
  832. self._sticker_meta_cache[sticker.pack_id] = pack
  833. except Exception:
  834. self.log.warning(
  835. f"Failed to fetch pack metadata for {sticker.pack_id}", exc_info=True
  836. )
  837. pack = None
  838. if not pack:
  839. content.info["fi.mau.signal.sticker"] = {
  840. "id": sticker.sticker_id,
  841. "pack": {
  842. "id": sticker.pack_id,
  843. "key": sticker.pack_key,
  844. },
  845. }
  846. return
  847. sticker_meta = pack.stickers[sticker.sticker_id]
  848. content.body = sticker_meta.emoji
  849. content.info["fi.mau.signal.sticker"] = {
  850. "id": sticker.sticker_id,
  851. "emoji": sticker_meta.emoji,
  852. "pack": {
  853. "id": pack.id,
  854. "key": pack.key,
  855. "title": pack.title,
  856. "author": pack.author,
  857. },
  858. }
  859. @staticmethod
  860. def _adjust_sticker_size(info: ImageInfo) -> None:
  861. if info.width > 256 or info.height > 256:
  862. if info.width == info.height:
  863. info.width = info.height = 256
  864. elif info.width > info.height:
  865. info.height = int(info.height / (info.width / 256))
  866. info.width = 256
  867. else:
  868. info.width = int(info.width / (info.height / 256))
  869. info.height = 256
  870. async def _handle_signal_sticker(
  871. self, intent: IntentAPI, sticker: Sticker
  872. ) -> MediaMessageEventContent | None:
  873. try:
  874. self.log.debug(f"Fetching sticker {sticker.pack_id}#{sticker.sticker_id}")
  875. async with StickersClient() as client:
  876. data = await client.download_sticker(
  877. sticker.sticker_id, sticker.pack_id, sticker.pack_key
  878. )
  879. except Exception:
  880. self.log.warning(f"Failed to download sticker {sticker.sticker_id}", exc_info=True)
  881. return None
  882. info = ImageInfo(
  883. mimetype=sticker.attachment.content_type,
  884. size=len(data),
  885. width=sticker.attachment.width,
  886. height=sticker.attachment.height,
  887. )
  888. self._adjust_sticker_size(info)
  889. if magic:
  890. info.mimetype = magic.from_buffer(data, mime=True)
  891. ext = mimetypes.guess_extension(info.mimetype)
  892. if not ext and info.mimetype == "image/webp":
  893. ext = ".webp"
  894. content = MediaMessageEventContent(
  895. msgtype=MessageType.IMAGE, info=info, body=f"sticker{ext}"
  896. )
  897. await self._upload_attachment(intent, content, data, sticker.attachment.id)
  898. return content
  899. async def _upload_attachment(
  900. self, intent: IntentAPI, content: MediaMessageEventContent, data: bytes, id: str
  901. ) -> None:
  902. upload_mime_type = content.info.mimetype
  903. if self.encrypted and encrypt_attachment:
  904. data, content.file = encrypt_attachment(data)
  905. upload_mime_type = "application/octet-stream"
  906. content.url = await intent.upload_media(data, mime_type=upload_mime_type, filename=id)
  907. if content.file:
  908. content.file.url = content.url
  909. content.url = None
  910. # This is a hack for bad clients like Element iOS that require a thumbnail
  911. if content.info.mimetype.startswith("image/"):
  912. if content.file:
  913. content.info.thumbnail_file = content.file
  914. elif content.url:
  915. content.info.thumbnail_url = content.url
  916. async def handle_signal_reaction(
  917. self, sender: p.Puppet, reaction: Reaction, timestamp: int
  918. ) -> None:
  919. author_address = await self._resolve_address(reaction.target_author)
  920. target_id = reaction.target_sent_timestamp
  921. async with self._reaction_lock:
  922. dedup_id = (author_address, target_id, reaction.emoji)
  923. if dedup_id in self._reaction_dedup:
  924. return
  925. self._reaction_dedup.appendleft(dedup_id)
  926. existing = await DBReaction.get_by_signal_id(
  927. self.chat_id, self.receiver, author_address, target_id, sender.address
  928. )
  929. if reaction.remove:
  930. if existing:
  931. try:
  932. await sender.intent_for(self).redact(existing.mx_room, existing.mxid)
  933. except IntentError:
  934. await self.main_intent.redact(existing.mx_room, existing.mxid)
  935. await existing.delete()
  936. self.log.trace(f"Removed {existing} after Signal removal")
  937. return
  938. elif existing and existing.emoji == reaction.emoji:
  939. return
  940. message = await DBMessage.get_by_signal_id(
  941. author_address, target_id, self.chat_id, self.receiver
  942. )
  943. if not message:
  944. self.log.debug(f"Ignoring reaction to unknown message {target_id}")
  945. return
  946. intent = sender.intent_for(self)
  947. # TODO add variation selectors to emoji before sending to Matrix
  948. mxid = await intent.react(
  949. message.mx_room, message.mxid, reaction.emoji, timestamp=timestamp
  950. )
  951. self.log.debug(f"{sender.address} reacted to {message.mxid} -> {mxid}")
  952. await self._upsert_reaction(existing, intent, mxid, sender, message, reaction.emoji)
  953. async def handle_signal_delete(self, sender: p.Puppet, message_ts: int) -> None:
  954. message = await DBMessage.get_by_signal_id(
  955. sender.address, message_ts, self.chat_id, self.receiver
  956. )
  957. if not message:
  958. return
  959. await message.delete()
  960. try:
  961. await sender.intent_for(self).redact(message.mx_room, message.mxid)
  962. except MForbidden:
  963. await self.main_intent.redact(message.mx_room, message.mxid)
  964. # endregion
  965. # region Updating portal info
  966. async def update_info(
  967. self, source: u.User, info: ChatInfo, sender: p.Puppet | None = None
  968. ) -> None:
  969. if self.is_direct:
  970. if not isinstance(info, (Contact, Profile, Address)):
  971. raise ValueError(f"Unexpected type for direct chat update_info: {type(info)}")
  972. if not self.name:
  973. puppet = await p.Puppet.get_by_address(self.chat_id)
  974. if not puppet.name:
  975. await puppet.update_info(info)
  976. self.name = puppet.name
  977. return
  978. if isinstance(info, GroupV2ID):
  979. info = await self.signal.get_group(source.username, info.id, info.revision or -1)
  980. if not info:
  981. self.log.debug(
  982. f"Failed to get full group v2 info through {source.username}, "
  983. "cancelling update"
  984. )
  985. return
  986. changed = False
  987. if isinstance(info, Group):
  988. changed = await self._update_name(info.name, sender) or changed
  989. elif isinstance(info, GroupV2):
  990. if self.revision < info.revision:
  991. self.revision = info.revision
  992. changed = True
  993. elif self.revision > info.revision:
  994. self.log.warning(
  995. f"Got outdated info when syncing through {source.username} "
  996. f"({info.revision} < {self.revision}), ignoring..."
  997. )
  998. return
  999. changed = await self._update_name(info.title, sender) or changed
  1000. elif isinstance(info, GroupV2ID):
  1001. return
  1002. else:
  1003. raise ValueError(f"Unexpected type for group update_info: {type(info)}")
  1004. changed = await self._update_avatar(info, sender) or changed
  1005. await self._update_participants(source, info)
  1006. try:
  1007. await self._update_power_levels(info)
  1008. except Exception:
  1009. self.log.warning("Error updating power levels", exc_info=True)
  1010. if changed:
  1011. await self.update_bridge_info()
  1012. await self.update()
  1013. async def update_expires_in_seconds(self, sender: p.Puppet, expires_in_seconds: int) -> None:
  1014. if expires_in_seconds == 0:
  1015. expires_in_seconds = None
  1016. if self.expiration_time == expires_in_seconds:
  1017. return
  1018. assert self.mxid
  1019. self.expiration_time = expires_in_seconds
  1020. await self.update()
  1021. time_str = "Off" if expires_in_seconds is None else format_duration(expires_in_seconds)
  1022. await self.main_intent.send_notice(
  1023. self.mxid,
  1024. html=f'<a href="https://matrix.to/#/{sender.mxid}">{sender.name}</a> set the '
  1025. f"disappearing message timer to {time_str}.",
  1026. )
  1027. async def update_puppet_avatar(self, new_hash: str, avatar_url: ContentURI) -> None:
  1028. if not self.encrypted and not self.private_chat_portal_meta:
  1029. return
  1030. if self.avatar_hash != new_hash or not self.avatar_set:
  1031. self.avatar_hash = new_hash
  1032. self.avatar_url = avatar_url
  1033. if self.mxid:
  1034. try:
  1035. await self.main_intent.set_room_avatar(self.mxid, avatar_url)
  1036. self.avatar_set = True
  1037. except Exception:
  1038. self.log.exception("Error setting avatar")
  1039. self.avatar_set = False
  1040. await self.update_bridge_info()
  1041. await self.update()
  1042. async def update_puppet_name(self, name: str) -> None:
  1043. if not self.encrypted and not self.private_chat_portal_meta:
  1044. return
  1045. changed = await self._update_name(name)
  1046. if changed:
  1047. await self.update_bridge_info()
  1048. await self.update()
  1049. async def _update_name(self, name: str, sender: p.Puppet | None = None) -> bool:
  1050. if self.name != name or not self.name_set:
  1051. self.name = name
  1052. if self.mxid:
  1053. try:
  1054. await self._try_with_puppet(
  1055. lambda i: i.set_room_name(self.mxid, self.name), puppet=sender
  1056. )
  1057. self.name_set = True
  1058. except Exception:
  1059. self.log.exception("Error setting name")
  1060. self.name_set = False
  1061. return True
  1062. return False
  1063. async def _try_with_puppet(
  1064. self, action: Callable[[IntentAPI], Awaitable[Any]], puppet: p.Puppet | None = None
  1065. ) -> None:
  1066. if puppet:
  1067. try:
  1068. await action(puppet.intent_for(self))
  1069. except (MForbidden, IntentError):
  1070. await action(self.main_intent)
  1071. else:
  1072. await action(self.main_intent)
  1073. async def _update_avatar(self, info: ChatInfo, sender: p.Puppet | None = None) -> bool:
  1074. path = None
  1075. if isinstance(info, GroupV2):
  1076. path = info.avatar
  1077. elif isinstance(info, Group):
  1078. path = f"group-{self.chat_id}"
  1079. res = await p.Puppet.upload_avatar(self, path, self.main_intent)
  1080. if res is False:
  1081. return False
  1082. self.avatar_hash, self.avatar_url = res
  1083. if not self.mxid:
  1084. return True
  1085. try:
  1086. await self._try_with_puppet(
  1087. lambda i: i.set_room_avatar(self.mxid, self.avatar_url), puppet=sender
  1088. )
  1089. self.avatar_set = True
  1090. except Exception:
  1091. self.log.exception("Error setting avatar")
  1092. self.avatar_set = False
  1093. return True
  1094. async def _update_participants(self, source: u.User, info: ChatInfo) -> None:
  1095. if not self.mxid or not isinstance(info, (Group, GroupV2)):
  1096. return
  1097. pending_members = info.pending_members if isinstance(info, GroupV2) else []
  1098. self._pending_members = {addr.uuid for addr in pending_members}
  1099. for address in info.members:
  1100. user = await u.User.get_by_address(address)
  1101. if user:
  1102. await self.main_intent.invite_user(self.mxid, user.mxid)
  1103. puppet = await p.Puppet.get_by_address(address)
  1104. await source.sync_contact(address)
  1105. await puppet.intent_for(self).ensure_joined(self.mxid)
  1106. for address in pending_members:
  1107. user = await u.User.get_by_address(address)
  1108. if user:
  1109. await self.main_intent.invite_user(self.mxid, user.mxid)
  1110. puppet = await p.Puppet.get_by_address(address)
  1111. await source.sync_contact(address)
  1112. await self.main_intent.invite_user(self.mxid, puppet.intent_for(self).mxid)
  1113. async def _update_power_levels(self, info: ChatInfo) -> None:
  1114. if not self.mxid:
  1115. return
  1116. power_levels = await self.main_intent.get_power_levels(self.mxid)
  1117. power_levels = await self._get_power_levels(power_levels, info=info, is_initial=False)
  1118. await self.main_intent.set_power_levels(self.mxid, power_levels)
  1119. # endregion
  1120. # region Bridge info state event
  1121. @property
  1122. def bridge_info_state_key(self) -> str:
  1123. return f"net.maunium.signal://signal/{self.chat_id}"
  1124. @property
  1125. def bridge_info(self) -> dict[str, Any]:
  1126. return {
  1127. "bridgebot": self.az.bot_mxid,
  1128. "creator": self.main_intent.mxid,
  1129. "protocol": {
  1130. "id": "signal",
  1131. "displayname": "Signal",
  1132. "avatar_url": self.config["appservice.bot_avatar"],
  1133. },
  1134. "channel": {
  1135. "id": str(self.chat_id),
  1136. "displayname": self.name,
  1137. "avatar_url": self.avatar_url,
  1138. },
  1139. }
  1140. async def update_bridge_info(self) -> None:
  1141. if not self.mxid:
  1142. self.log.debug("Not updating bridge info: no Matrix room created")
  1143. return
  1144. try:
  1145. self.log.debug("Updating bridge info...")
  1146. await self.main_intent.send_state_event(
  1147. self.mxid, StateBridge, self.bridge_info, self.bridge_info_state_key
  1148. )
  1149. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  1150. await self.main_intent.send_state_event(
  1151. self.mxid, StateHalfShotBridge, self.bridge_info, self.bridge_info_state_key
  1152. )
  1153. except Exception:
  1154. self.log.warning("Failed to update bridge info", exc_info=True)
  1155. # endregion
  1156. # region Creating Matrix rooms
  1157. async def update_matrix_room(self, source: u.User, info: ChatInfo) -> None:
  1158. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  1159. raise ValueError(f"Unexpected type for updating group portal: {type(info)}")
  1160. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  1161. raise ValueError(f"Unexpected type for updating direct chat portal: {type(info)}")
  1162. try:
  1163. await self._update_matrix_room(source, info)
  1164. except Exception:
  1165. self.log.exception("Failed to update portal")
  1166. async def create_matrix_room(self, source: u.User, info: ChatInfo) -> RoomID | None:
  1167. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  1168. raise ValueError(f"Unexpected type for creating group portal: {type(info)}")
  1169. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  1170. raise ValueError(f"Unexpected type for creating direct chat portal: {type(info)}")
  1171. if isinstance(info, Group) and not info.members:
  1172. groups = await self.signal.list_groups(source.username)
  1173. info = next(
  1174. (g for g in groups if isinstance(g, Group) and g.group_id == info.group_id), info
  1175. )
  1176. elif isinstance(info, GroupV2ID) and not isinstance(info, GroupV2):
  1177. self.log.debug(
  1178. f"create_matrix_room() called with {info}, " "fetching full info from signald"
  1179. )
  1180. info = await self.signal.get_group(source.username, info.id, info.revision or -1)
  1181. if not info:
  1182. self.log.warning(f"Full info not found, canceling room creation")
  1183. return None
  1184. else:
  1185. self.log.trace("get_group() returned full info: %s", info)
  1186. if self.mxid:
  1187. await self.update_matrix_room(source, info)
  1188. return self.mxid
  1189. async with self._create_room_lock:
  1190. return await self._create_matrix_room(source, info)
  1191. def _get_invite_content(self, double_puppet: p.Puppet | None) -> dict[str, Any]:
  1192. invite_content = {}
  1193. if double_puppet:
  1194. invite_content["fi.mau.will_auto_accept"] = True
  1195. if self.is_direct:
  1196. invite_content["is_direct"] = True
  1197. return invite_content
  1198. async def _update_matrix_room(self, source: u.User, info: ChatInfo) -> None:
  1199. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  1200. await self.main_intent.invite_user(
  1201. self.mxid,
  1202. source.mxid,
  1203. check_cache=True,
  1204. extra_content=self._get_invite_content(puppet),
  1205. )
  1206. if puppet:
  1207. did_join = await puppet.intent.ensure_joined(self.mxid)
  1208. if did_join and self.is_direct:
  1209. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  1210. await self.update_info(source, info)
  1211. async def _get_power_levels(
  1212. self,
  1213. levels: PowerLevelStateEventContent | None = None,
  1214. info: ChatInfo | None = None,
  1215. is_initial: bool = False,
  1216. ) -> PowerLevelStateEventContent:
  1217. levels = levels or PowerLevelStateEventContent()
  1218. if self.is_direct:
  1219. levels.ban = 99
  1220. levels.kick = 99
  1221. levels.invite = 99
  1222. levels.state_default = 0
  1223. meta_edit_level = 0
  1224. else:
  1225. if isinstance(info, GroupV2):
  1226. ac = info.access_control
  1227. for detail in info.member_detail + info.pending_member_detail:
  1228. puppet = await p.Puppet.get_by_address(Address(uuid=detail.uuid))
  1229. level = 50 if detail.role == GroupMemberRole.ADMINISTRATOR else 0
  1230. levels.users[puppet.intent_for(self).mxid] = level
  1231. else:
  1232. ac = GroupAccessControl()
  1233. levels.ban = 50
  1234. levels.kick = 50
  1235. levels.invite = 50 if ac.members == AccessControlMode.ADMINISTRATOR else 0
  1236. levels.state_default = 50
  1237. meta_edit_level = 50 if ac.attributes == AccessControlMode.ADMINISTRATOR else 0
  1238. levels.events[EventType.ROOM_NAME] = meta_edit_level
  1239. levels.events[EventType.ROOM_AVATAR] = meta_edit_level
  1240. levels.events[EventType.ROOM_TOPIC] = meta_edit_level
  1241. levels.events[EventType.ROOM_ENCRYPTION] = 50 if self.matrix.e2ee else 99
  1242. levels.events[EventType.ROOM_TOMBSTONE] = 99
  1243. levels.users_default = 0
  1244. levels.events_default = 0
  1245. # Remote delete is only for your own messages
  1246. levels.redact = 99
  1247. if self.main_intent.mxid not in levels.users:
  1248. levels.users[self.main_intent.mxid] = 9001 if is_initial else 100
  1249. return levels
  1250. async def _create_matrix_room(self, source: u.User, info: ChatInfo) -> RoomID | None:
  1251. if self.mxid:
  1252. await self._update_matrix_room(source, info)
  1253. return self.mxid
  1254. await self.update_info(source, info)
  1255. self.log.debug("Creating Matrix room")
  1256. name: str | None = None
  1257. power_levels = await self._get_power_levels(info=info, is_initial=True)
  1258. initial_state = [
  1259. {
  1260. "type": str(StateBridge),
  1261. "state_key": self.bridge_info_state_key,
  1262. "content": self.bridge_info,
  1263. },
  1264. {
  1265. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  1266. "type": str(StateHalfShotBridge),
  1267. "state_key": self.bridge_info_state_key,
  1268. "content": self.bridge_info,
  1269. },
  1270. {
  1271. "type": str(EventType.ROOM_POWER_LEVELS),
  1272. "content": power_levels.serialize(),
  1273. },
  1274. ]
  1275. invites = []
  1276. if self.config["bridge.encryption.default"] and self.matrix.e2ee:
  1277. self.encrypted = True
  1278. initial_state.append(
  1279. {
  1280. "type": str(EventType.ROOM_ENCRYPTION),
  1281. "content": {"algorithm": "m.megolm.v1.aes-sha2"},
  1282. }
  1283. )
  1284. if self.is_direct:
  1285. invites.append(self.az.bot_mxid)
  1286. if self.is_direct and source.address == self.chat_id:
  1287. name = self.name = "Signal Note to Self"
  1288. elif self.encrypted or self.private_chat_portal_meta or not self.is_direct:
  1289. name = self.name
  1290. if self.avatar_url:
  1291. initial_state.append(
  1292. {
  1293. "type": str(EventType.ROOM_AVATAR),
  1294. "content": {"url": self.avatar_url},
  1295. }
  1296. )
  1297. if self.config["appservice.community_id"]:
  1298. initial_state.append(
  1299. {
  1300. "type": "m.room.related_groups",
  1301. "content": {"groups": [self.config["appservice.community_id"]]},
  1302. }
  1303. )
  1304. creation_content = {}
  1305. if not self.config["bridge.federate_rooms"]:
  1306. creation_content["m.federate"] = False
  1307. self.mxid = await self.main_intent.create_room(
  1308. name=name,
  1309. is_direct=self.is_direct,
  1310. initial_state=initial_state,
  1311. invitees=invites,
  1312. creation_content=creation_content,
  1313. )
  1314. if not self.mxid:
  1315. raise Exception("Failed to create room: no mxid returned")
  1316. self.name_set = bool(name)
  1317. self.avatar_set = bool(self.avatar_url)
  1318. if self.encrypted and self.matrix.e2ee and self.is_direct:
  1319. try:
  1320. await self.az.intent.ensure_joined(self.mxid)
  1321. except Exception:
  1322. self.log.warning("Failed to add bridge bot to new private chat {self.mxid}")
  1323. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  1324. await self.main_intent.invite_user(
  1325. self.mxid, source.mxid, extra_content=self._get_invite_content(puppet)
  1326. )
  1327. if puppet:
  1328. try:
  1329. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  1330. await puppet.intent.join_room_by_id(self.mxid)
  1331. except MatrixError:
  1332. self.log.debug(
  1333. "Failed to join custom puppet into newly created portal", exc_info=True
  1334. )
  1335. await self.update()
  1336. self.log.debug(f"Matrix room created: {self.mxid}")
  1337. self.by_mxid[self.mxid] = self
  1338. if not self.is_direct:
  1339. await self._update_participants(source, info)
  1340. # TODO
  1341. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  1342. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  1343. # in_community=in_community).upsert()
  1344. return self.mxid
  1345. # endregion
  1346. # region Database getters
  1347. async def _postinit(self) -> None:
  1348. self.by_chat_id[(self.chat_id_str, self.receiver)] = self
  1349. if self.mxid:
  1350. self.by_mxid[self.mxid] = self
  1351. if self.is_direct:
  1352. puppet = await p.Puppet.get_by_address(self.chat_id)
  1353. self._main_intent = puppet.default_mxid_intent
  1354. elif not self.is_direct:
  1355. self._main_intent = self.az.intent
  1356. async def delete(self) -> None:
  1357. await DBMessage.delete_all(self.mxid)
  1358. self.by_mxid.pop(self.mxid, None)
  1359. self.mxid = None
  1360. self.encrypted = False
  1361. await self.update()
  1362. async def save(self) -> None:
  1363. await self.update()
  1364. @classmethod
  1365. def all_with_room(cls) -> AsyncGenerator[Portal, None]:
  1366. return cls._db_to_portals(super().all_with_room())
  1367. @classmethod
  1368. def find_private_chats_with(cls, other_user: Address) -> AsyncGenerator[Portal, None]:
  1369. return cls._db_to_portals(super().find_private_chats_with(other_user))
  1370. @classmethod
  1371. async def _db_to_portals(cls, query: Awaitable[list[Portal]]) -> AsyncGenerator[Portal, None]:
  1372. portals = await query
  1373. for index, portal in enumerate(portals):
  1374. try:
  1375. yield cls.by_chat_id[(portal.chat_id_str, portal.receiver)]
  1376. except KeyError:
  1377. await portal._postinit()
  1378. yield portal
  1379. @classmethod
  1380. @async_getter_lock
  1381. async def get_by_mxid(cls, mxid: RoomID) -> Portal | None:
  1382. try:
  1383. return cls.by_mxid[mxid]
  1384. except KeyError:
  1385. pass
  1386. portal = cast(cls, await super().get_by_mxid(mxid))
  1387. if portal is not None:
  1388. await portal._postinit()
  1389. return portal
  1390. return None
  1391. @classmethod
  1392. async def get_by_chat_id(
  1393. cls, chat_id: GroupID | Address, *, receiver: str = "", create: bool = False
  1394. ) -> Portal | None:
  1395. if isinstance(chat_id, str):
  1396. receiver = ""
  1397. elif not isinstance(chat_id, Address):
  1398. raise ValueError(f"Invalid chat ID type {type(chat_id)}")
  1399. elif not receiver:
  1400. raise ValueError("Direct chats must have a receiver")
  1401. best_id = id_to_str(chat_id)
  1402. portal = await cls._get_by_chat_id(best_id, receiver, create=create, chat_id=chat_id)
  1403. if portal:
  1404. portal.log.debug(f"get_by_chat_id({chat_id}, {receiver}) -> {hex(id(portal))}")
  1405. return portal
  1406. @classmethod
  1407. @async_getter_lock
  1408. async def _get_by_chat_id(
  1409. cls, best_id: str, receiver: str, *, create: bool, chat_id: GroupID | Address
  1410. ) -> Portal | None:
  1411. try:
  1412. return cls.by_chat_id[(best_id, receiver)]
  1413. except KeyError:
  1414. pass
  1415. portal = cast(cls, await super().get_by_chat_id(chat_id, receiver))
  1416. if portal is not None:
  1417. await portal._postinit()
  1418. return portal
  1419. if create:
  1420. portal = cls(chat_id, receiver)
  1421. await portal.insert()
  1422. await portal._postinit()
  1423. return portal
  1424. return None
  1425. # endregion