portal.py 61 KB

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