portal.py 67 KB

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