portal.py 63 KB

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