portal.py 65 KB

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