portal.py 60 KB

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