portal.py 62 KB

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