portal.py 63 KB

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