portal.py 61 KB

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