portal.py 68 KB

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