portal.py 63 KB

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