portal.py 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  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. for dm in await DisappearingMessage.get_all():
  143. if dm.expiration_ts:
  144. asyncio.create_task(cls._expire_event(dm))
  145. # region Misc
  146. async def _send_delivery_receipt(self, event_id: EventID) -> None:
  147. if event_id and self.config["bridge.delivery_receipts"]:
  148. try:
  149. await self.az.intent.mark_read(self.mxid, event_id)
  150. except Exception:
  151. self.log.exception("Failed to send delivery receipt for %s", event_id)
  152. async def _upsert_reaction(self, existing: DBReaction, intent: IntentAPI, mxid: EventID,
  153. sender: Union['p.Puppet', 'u.User'], message: DBMessage, emoji: str
  154. ) -> None:
  155. if existing:
  156. self.log.debug(f"_upsert_reaction redacting {existing.mxid} and inserting {mxid}"
  157. f" (message: {message.mxid})")
  158. try:
  159. await intent.redact(existing.mx_room, existing.mxid)
  160. except MForbidden:
  161. self.log.debug("Unexpected MForbidden redacting reaction", exc_info=True)
  162. await existing.edit(emoji=emoji, mxid=mxid, mx_room=message.mx_room)
  163. else:
  164. self.log.debug(f"_upsert_reaction inserting {mxid} (message: {message.mxid})")
  165. await DBReaction(mxid=mxid, mx_room=message.mx_room, emoji=emoji,
  166. signal_chat_id=self.chat_id, signal_receiver=self.receiver,
  167. msg_author=message.sender, msg_timestamp=message.timestamp,
  168. author=sender.address).insert()
  169. # endregion
  170. # region Matrix event handling
  171. @staticmethod
  172. def _make_attachment(message: MediaMessageEventContent, path: str) -> Attachment:
  173. attachment = Attachment(custom_filename=message.body, content_type=message.info.mimetype,
  174. outgoing_filename=path)
  175. info = message.info
  176. attachment.width = info.get("w", info.get("width", 0))
  177. attachment.height = info.get("h", info.get("height", 0))
  178. attachment.voice_note = message.msgtype == MessageType.AUDIO
  179. return attachment
  180. def _write_outgoing_file(self, data: bytes) -> str:
  181. dir = pathlib.Path(self.config["signal.outgoing_attachment_dir"])
  182. path = dir.joinpath(f"mautrix-signal-{str(uuid4())}")
  183. try:
  184. with open(path, "wb") as file:
  185. file.write(data)
  186. except FileNotFoundError:
  187. dir.mkdir(mode=0o755, parents=True, exist_ok=True)
  188. with open(path, "wb") as file:
  189. file.write(data)
  190. return str(path)
  191. async def _download_matrix_media(self, message: MediaMessageEventContent) -> str:
  192. if message.file:
  193. data = await self.main_intent.download_media(message.file.url)
  194. data = decrypt_attachment(data, message.file.key.key,
  195. message.file.hashes.get("sha256"), message.file.iv)
  196. else:
  197. data = await self.main_intent.download_media(message.url)
  198. return self._write_outgoing_file(data)
  199. async def get_displayname(self, user: 'u.User') -> str:
  200. return await self.main_intent.get_room_displayname(self.mxid, user.mxid) or user.mxid
  201. async def _apply_msg_format(self, sender: 'u.User', content: MessageEventContent) -> None:
  202. if not isinstance(content, TextMessageEventContent) or content.format != Format.HTML:
  203. content.format = Format.HTML
  204. content.formatted_body = escape_html(content.body).replace("\n", "<br/>")
  205. tpl = (self.config[f"relaybot.message_formats.[{content.msgtype.value}]"]
  206. or "$sender_displayname: $message")
  207. displayname = await self.get_displayname(sender)
  208. username, _ = self.az.intent.parse_user_id(sender.mxid)
  209. tpl_args = dict(sender_mxid=sender.mxid,
  210. sender_username=username,
  211. sender_displayname=escape_html(displayname),
  212. message=content.formatted_body,
  213. body=content.body,
  214. formatted_body=content.formatted_body)
  215. content.formatted_body = Template(tpl).safe_substitute(tpl_args)
  216. content.body = Template(tpl).safe_substitute(tpl_args)
  217. if content.msgtype == MessageType.EMOTE:
  218. content.msgtype = MessageType.TEXT
  219. async def _get_relay_sender(self, sender: 'u.User', evt_identifier: str
  220. ) -> Tuple[Optional['u.User'], bool]:
  221. if await sender.is_logged_in():
  222. return sender, False
  223. if not self.has_relay:
  224. self.log.debug(f"Ignoring {evt_identifier} from non-logged-in user {sender.mxid}"
  225. " in chat with no relay user")
  226. return None, True
  227. relay_sender = await self.get_relay_user()
  228. if not relay_sender:
  229. self.log.debug(f"Ignoring {evt_identifier} from non-logged-in user {sender.mxid}: "
  230. f"relay user {self.relay_user_id} is not set up correctly")
  231. return None, True
  232. return relay_sender, True
  233. async def handle_matrix_message(self, sender: 'u.User', message: MessageEventContent,
  234. event_id: EventID) -> None:
  235. orig_sender = sender
  236. sender, is_relay = await self._get_relay_sender(sender, f"message {event_id}")
  237. if not sender:
  238. return
  239. elif is_relay:
  240. await self._apply_msg_format(orig_sender, message)
  241. request_id = int(time.time() * 1000)
  242. self._msgts_dedup.appendleft((sender.address, request_id))
  243. quote = None
  244. if message.get_reply_to():
  245. reply = await DBMessage.get_by_mxid(message.get_reply_to(), self.mxid)
  246. # TODO include actual text? either store in db or fetch event from homeserver
  247. if reply is not None:
  248. quote = Quote(id=reply.timestamp, author=reply.sender, text="")
  249. attachments: Optional[List[Attachment]] = None
  250. attachment_path: Optional[str] = None
  251. mentions: Optional[List[Mention]] = None
  252. if message.msgtype.is_text:
  253. text, mentions = await matrix_to_signal(message)
  254. elif message.msgtype.is_media:
  255. attachment_path = await self._download_matrix_media(message)
  256. attachment = self._make_attachment(message, attachment_path)
  257. attachments = [attachment]
  258. text = message.body if is_relay else None
  259. self.log.trace("Formed outgoing attachment %s", attachment)
  260. else:
  261. self.log.debug(f"Unknown msgtype {message.msgtype} in Matrix message {event_id}")
  262. return
  263. self.log.debug(f"Sending Matrix message {event_id} to Signal with timestamp {request_id}")
  264. try:
  265. await self.signal.send(username=sender.username, recipient=self.chat_id, body=text,
  266. mentions=mentions, quote=quote, attachments=attachments,
  267. timestamp=request_id)
  268. except Exception as e:
  269. sender.send_remote_checkpoint(
  270. MessageSendCheckpointStatus.PERM_FAILURE,
  271. event_id,
  272. self.mxid,
  273. EventType.ROOM_MESSAGE,
  274. message.msgtype,
  275. error=e,
  276. )
  277. auth_failed = (
  278. "org.whispersystems.signalservice.api.push.exceptions.AuthorizationFailedException"
  279. )
  280. if isinstance(e, ResponseError) and auth_failed in e.data.get("exceptions", []):
  281. await sender.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=str(e))
  282. await self._send_message(
  283. self.main_intent,
  284. TextMessageEventContent(
  285. msgtype=MessageType.NOTICE,
  286. body=f"\u26a0 Your message was not bridged: {e}"))
  287. else:
  288. sender.send_remote_checkpoint(
  289. MessageSendCheckpointStatus.SUCCESS,
  290. event_id,
  291. self.mxid,
  292. EventType.ROOM_MESSAGE,
  293. message.msgtype,
  294. )
  295. await self._send_delivery_receipt(event_id)
  296. msg = DBMessage(mxid=event_id, mx_room=self.mxid, sender=sender.address,
  297. timestamp=request_id,
  298. signal_chat_id=self.chat_id, signal_receiver=self.receiver)
  299. await msg.insert()
  300. self.log.debug(f"Handled Matrix message {event_id} -> {request_id}")
  301. if attachment_path and self.config["signal.remove_file_after_handling"]:
  302. try:
  303. os.remove(attachment_path)
  304. except FileNotFoundError:
  305. pass
  306. # Handle disappearing messages
  307. if (
  308. self.expiration_time
  309. and (
  310. self.is_direct
  311. or self.config["signal.enable_disappearing_messages_in_groups"]
  312. )
  313. ):
  314. disappearing_message = DisappearingMessage(
  315. self.mxid, event_id, self.expiration_time
  316. )
  317. await disappearing_message.insert()
  318. asyncio.create_task(Portal._expire_event(disappearing_message))
  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, disappearing_message: DisappearingMessage):
  501. """
  502. Expire a :class:`DisappearingMessage`. 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. """
  506. room_id = disappearing_message.room_id
  507. event_id = disappearing_message.mxid
  508. portal = await cls.get_by_mxid(room_id)
  509. if not portal:
  510. raise AttributeError(f"No portal found for {room_id}")
  511. if (
  512. not portal.is_direct and not
  513. cls.config["signal.enable_disappearing_messages_in_groups"]
  514. ):
  515. portal.log.debug(
  516. "Not expiring event in group message since "
  517. "signal.enable_disappearing_messages_in_groups is not enabled."
  518. )
  519. await disappearing_message.delete(room_id, event_id)
  520. return
  521. wait = disappearing_message.expiration_seconds
  522. # If there is an expiration_ts, then there was probably a bridge restart, so we have to
  523. # resume the countdown. This is fairly likely to occur if the disappearance timeout is
  524. # weeks.
  525. # If there is not an expiration_ts, then set one.
  526. now = time.time()
  527. if disappearing_message.expiration_ts is not None:
  528. wait = (disappearing_message.expiration_ts / 1000) - now
  529. else:
  530. disappearing_message.expiration_ts = int((now + wait) * 1000)
  531. await disappearing_message.update()
  532. if wait < 0:
  533. wait = 0
  534. portal.log.debug(f"Redacting {event_id} in {wait} seconds")
  535. await asyncio.sleep(wait)
  536. async with portal._expiration_lock:
  537. if not await DisappearingMessage.get(room_id, event_id):
  538. portal.log.debug(
  539. f"{event_id} no longer in disappearing messages list, not redacting"
  540. )
  541. return
  542. portal.log.debug(f"Redacting {event_id} because it was expired")
  543. try:
  544. await portal.main_intent.redact(room_id, event_id)
  545. portal.log.debug(f"Redacted {event_id} successfully")
  546. except Exception as e:
  547. portal.log.warning("Redacting expired event didn't work", e)
  548. finally:
  549. await DisappearingMessage.delete(room_id, event_id)
  550. async def handle_read_receipt(self, event_id: EventID, data: SingleReceiptEventContent):
  551. # Start the redaction timers for all of the disappearing messages in the room when the user
  552. # reads the room. This is the behavior of the Signal clients.
  553. for disappearing_message in await DisappearingMessage.get_all_for_room(self.mxid):
  554. asyncio.create_task(Portal._expire_event(disappearing_message))
  555. # endregion
  556. # region Signal event handling
  557. @staticmethod
  558. async def _resolve_address(address: Address) -> Address:
  559. puppet = await p.Puppet.get_by_address(address, create=False)
  560. return puppet.address
  561. async def _find_quote_event_id(self, quote: Optional[Quote]
  562. ) -> Optional[Union[MessageEvent, EventID]]:
  563. if not quote:
  564. return None
  565. author_address = await self._resolve_address(quote.author)
  566. reply_msg = await DBMessage.get_by_signal_id(author_address, quote.id,
  567. self.chat_id, self.receiver)
  568. if not reply_msg:
  569. return None
  570. try:
  571. evt = await self.main_intent.get_event(self.mxid, reply_msg.mxid)
  572. if isinstance(evt, EncryptedEvent):
  573. return await self.matrix.e2ee.decrypt(evt, wait_session_timeout=0)
  574. return evt
  575. except MatrixError:
  576. return reply_msg.mxid
  577. async def handle_signal_message(self, source: 'u.User', sender: 'p.Puppet',
  578. message: MessageData) -> None:
  579. if (sender.address, message.timestamp) in self._msgts_dedup:
  580. self.log.debug(f"Ignoring message {message.timestamp} by {sender.uuid}"
  581. " as it was already handled (message.timestamp in dedup queue)")
  582. await self.signal.send_receipt(source.username, sender.address,
  583. timestamps=[message.timestamp])
  584. return
  585. old_message = await DBMessage.get_by_signal_id(sender.address, message.timestamp,
  586. self.chat_id, self.receiver)
  587. if old_message is not None:
  588. self.log.debug(f"Ignoring message {message.timestamp} by {sender.uuid}"
  589. " as it was already handled (message.id found in database)")
  590. await self.signal.send_receipt(source.username, sender.address,
  591. timestamps=[message.timestamp])
  592. return
  593. self.log.debug(f"Started handling message {message.timestamp} by {sender.uuid}")
  594. self.log.trace(f"Message content: {message}")
  595. self._msgts_dedup.appendleft((sender.address, message.timestamp))
  596. intent = sender.intent_for(self)
  597. await intent.set_typing(self.mxid, False)
  598. event_id = None
  599. reply_to = await self._find_quote_event_id(message.quote)
  600. if message.sticker:
  601. if message.sticker.attachment.incoming_filename:
  602. content = await self._handle_signal_attachment(intent, message.sticker.attachment,
  603. sticker=True)
  604. elif StickersClient:
  605. content = await self._handle_signal_sticker(intent, message.sticker)
  606. else:
  607. self.log.debug(f"Not handling sticker in {message.timestamp}: no incoming_filename"
  608. " and signalstickers-client not installed.")
  609. return
  610. if content:
  611. if message.sticker.attachment.blurhash:
  612. content.info["blurhash"] = message.sticker.attachment.blurhash
  613. content.info["xyz.amorgan.blurhash"] = message.sticker.attachment.blurhash
  614. await self._add_sticker_meta(message.sticker, content)
  615. if reply_to and not message.body:
  616. content.set_reply(reply_to)
  617. reply_to = None
  618. event_id = await self._send_message(intent, content, timestamp=message.timestamp,
  619. event_type=EventType.STICKER)
  620. for attachment in message.attachments:
  621. if not attachment.incoming_filename:
  622. self.log.warning("Failed to bridge attachment, no incoming filename: %s",
  623. attachment)
  624. continue
  625. content = await self._handle_signal_attachment(intent, attachment)
  626. if reply_to and not message.body:
  627. # If there's no text, set the first image as the reply
  628. content.set_reply(reply_to)
  629. reply_to = None
  630. event_id = await self._send_message(intent, content, timestamp=message.timestamp)
  631. if message.body:
  632. content = await signal_to_matrix(message)
  633. if reply_to:
  634. content.set_reply(reply_to)
  635. event_id = await self._send_message(intent, content, timestamp=message.timestamp)
  636. if event_id:
  637. msg = DBMessage(mxid=event_id, mx_room=self.mxid,
  638. sender=sender.address, timestamp=message.timestamp,
  639. signal_chat_id=self.chat_id, signal_receiver=self.receiver)
  640. await msg.insert()
  641. await self.signal.send_receipt(source.username, sender.address,
  642. timestamps=[message.timestamp])
  643. await self._send_delivery_receipt(event_id)
  644. self.log.debug(f"Handled Signal message {message.timestamp} -> {event_id}")
  645. if (
  646. message.expires_in_seconds
  647. and (
  648. self.is_direct
  649. or self.config["signal.enable_disappearing_messages_in_groups"]
  650. )
  651. ):
  652. disappearing_message = DisappearingMessage(
  653. self.mxid, event_id, message.expires_in_seconds
  654. )
  655. await disappearing_message.insert()
  656. self.log.debug(
  657. f"{event_id} set to be redacted {message.expires_in_seconds} seconds after "
  658. "room is read"
  659. )
  660. else:
  661. self.log.debug(f"Didn't get event ID for {message.timestamp}")
  662. @staticmethod
  663. def _make_media_content(attachment: Attachment) -> MediaMessageEventContent:
  664. if attachment.content_type.startswith("image/"):
  665. msgtype = MessageType.IMAGE
  666. info = ImageInfo(mimetype=attachment.content_type,
  667. width=attachment.width, height=attachment.height)
  668. elif attachment.content_type.startswith("video/"):
  669. msgtype = MessageType.VIDEO
  670. info = VideoInfo(mimetype=attachment.content_type,
  671. width=attachment.width, height=attachment.height)
  672. elif attachment.voice_note or attachment.content_type.startswith("audio/"):
  673. msgtype = MessageType.AUDIO
  674. info = AudioInfo(mimetype=attachment.content_type)
  675. else:
  676. msgtype = MessageType.FILE
  677. info = FileInfo(mimetype=attachment.content_type)
  678. if not attachment.custom_filename:
  679. ext = mimetypes.guess_extension(attachment.content_type) or ""
  680. attachment.custom_filename = attachment.id + ext
  681. if attachment.blurhash:
  682. info["blurhash"] = attachment.blurhash
  683. info["xyz.amorgan.blurhash"] = attachment.blurhash
  684. return MediaMessageEventContent(msgtype=msgtype, info=info,
  685. body=attachment.custom_filename)
  686. async def _handle_signal_attachment(self, intent: IntentAPI, attachment: Attachment,
  687. sticker: bool = False) -> MediaMessageEventContent:
  688. self.log.trace(f"Reuploading attachment {attachment}")
  689. if not attachment.content_type:
  690. attachment.content_type = (magic.from_file(attachment.incoming_filename, mime=True)
  691. if magic is not None else "application/octet-stream")
  692. content = self._make_media_content(attachment)
  693. if sticker:
  694. self._adjust_sticker_size(content.info)
  695. with open(attachment.incoming_filename, "rb") as file:
  696. data = file.read()
  697. if self.config["signal.remove_file_after_handling"]:
  698. os.remove(attachment.incoming_filename)
  699. await self._upload_attachment(intent, content, data, attachment.id)
  700. return content
  701. async def _add_sticker_meta(self, sticker: Sticker, content: MediaMessageEventContent) -> None:
  702. try:
  703. pack = self._sticker_meta_cache[sticker.pack_id]
  704. except KeyError:
  705. self.log.debug(f"Fetching sticker pack metadata for {sticker.pack_id}")
  706. try:
  707. async with StickersClient() as client:
  708. pack = await client.get_pack_metadata(sticker.pack_id, sticker.pack_key)
  709. self._sticker_meta_cache[sticker.pack_id] = pack
  710. except Exception:
  711. self.log.warning(f"Failed to fetch pack metadata for {sticker.pack_id}",
  712. exc_info=True)
  713. pack = None
  714. if not pack:
  715. content.info["fi.mau.signal.sticker"] = {
  716. "id": sticker.sticker_id,
  717. "pack": {
  718. "id": sticker.pack_id,
  719. "key": sticker.pack_key,
  720. },
  721. }
  722. return
  723. sticker_meta = pack.stickers[sticker.sticker_id]
  724. content.body = sticker_meta.emoji
  725. content.info["fi.mau.signal.sticker"] = {
  726. "id": sticker.sticker_id,
  727. "emoji": sticker_meta.emoji,
  728. "pack": {
  729. "id": pack.id,
  730. "key": pack.key,
  731. "title": pack.title,
  732. "author": pack.author,
  733. },
  734. }
  735. @staticmethod
  736. def _adjust_sticker_size(info: ImageInfo) -> None:
  737. if info.width > 256 or info.height > 256:
  738. if info.width == info.height:
  739. info.width = info.height = 256
  740. elif info.width > info.height:
  741. info.height = int(info.height / (info.width / 256))
  742. info.width = 256
  743. else:
  744. info.width = int(info.width / (info.height / 256))
  745. info.height = 256
  746. async def _handle_signal_sticker(self, intent: IntentAPI, sticker: Sticker
  747. ) -> Optional[MediaMessageEventContent]:
  748. try:
  749. self.log.debug(f"Fetching sticker {sticker.pack_id}#{sticker.sticker_id}")
  750. async with StickersClient() as client:
  751. data = await client.download_sticker(sticker.sticker_id,
  752. sticker.pack_id, sticker.pack_key)
  753. except Exception:
  754. self.log.warning(f"Failed to download sticker {sticker.sticker_id}", exc_info=True)
  755. return None
  756. info = ImageInfo(mimetype=sticker.attachment.content_type, size=len(data),
  757. width=sticker.attachment.width, height=sticker.attachment.height)
  758. self._adjust_sticker_size(info)
  759. if magic:
  760. info.mimetype = magic.from_buffer(data, mime=True)
  761. ext = mimetypes.guess_extension(info.mimetype)
  762. if not ext and info.mimetype == "image/webp":
  763. ext = ".webp"
  764. content = MediaMessageEventContent(msgtype=MessageType.IMAGE, info=info,
  765. body=f"sticker{ext}")
  766. await self._upload_attachment(intent, content, data, sticker.attachment.id)
  767. return content
  768. async def _upload_attachment(self, intent: IntentAPI, content: MediaMessageEventContent,
  769. data: bytes, id: str) -> None:
  770. upload_mime_type = content.info.mimetype
  771. if self.encrypted and encrypt_attachment:
  772. data, content.file = encrypt_attachment(data)
  773. upload_mime_type = "application/octet-stream"
  774. content.url = await intent.upload_media(data, mime_type=upload_mime_type, filename=id)
  775. if content.file:
  776. content.file.url = content.url
  777. content.url = None
  778. # This is a hack for bad clients like Element iOS that require a thumbnail
  779. if content.info.mimetype.startswith("image/"):
  780. if content.file:
  781. content.info.thumbnail_file = content.file
  782. elif content.url:
  783. content.info.thumbnail_url = content.url
  784. async def handle_signal_reaction(self, sender: 'p.Puppet', reaction: Reaction,
  785. timestamp: int) -> None:
  786. author_address = await self._resolve_address(reaction.target_author)
  787. target_id = reaction.target_sent_timestamp
  788. async with self._reaction_lock:
  789. dedup_id = (author_address, target_id, reaction.emoji)
  790. if dedup_id in self._reaction_dedup:
  791. return
  792. self._reaction_dedup.appendleft(dedup_id)
  793. existing = await DBReaction.get_by_signal_id(self.chat_id, self.receiver,
  794. author_address, target_id, sender.address)
  795. if reaction.remove:
  796. if existing:
  797. try:
  798. await sender.intent_for(self).redact(existing.mx_room, existing.mxid)
  799. except IntentError:
  800. await self.main_intent.redact(existing.mx_room, existing.mxid)
  801. await existing.delete()
  802. self.log.trace(f"Removed {existing} after Signal removal")
  803. return
  804. elif existing and existing.emoji == reaction.emoji:
  805. return
  806. message = await DBMessage.get_by_signal_id(author_address, target_id,
  807. self.chat_id, self.receiver)
  808. if not message:
  809. self.log.debug(f"Ignoring reaction to unknown message {target_id}")
  810. return
  811. intent = sender.intent_for(self)
  812. # TODO add variation selectors to emoji before sending to Matrix
  813. mxid = await intent.react(message.mx_room, message.mxid, reaction.emoji,
  814. timestamp=timestamp)
  815. self.log.debug(f"{sender.address} reacted to {message.mxid} -> {mxid}")
  816. await self._upsert_reaction(existing, intent, mxid, sender, message, reaction.emoji)
  817. async def handle_signal_delete(self, sender: 'p.Puppet', message_ts: int) -> None:
  818. message = await DBMessage.get_by_signal_id(sender.address, message_ts,
  819. self.chat_id, self.receiver)
  820. if not message:
  821. return
  822. await message.delete()
  823. try:
  824. await sender.intent_for(self).redact(message.mx_room, message.mxid)
  825. except MForbidden:
  826. await self.main_intent.redact(message.mx_room, message.mxid)
  827. # endregion
  828. # region Updating portal info
  829. async def update_info(self, source: 'u.User', info: ChatInfo,
  830. sender: Optional['p.Puppet'] = None) -> None:
  831. if self.is_direct:
  832. if not isinstance(info, (Contact, Profile, Address)):
  833. raise ValueError(f"Unexpected type for direct chat update_info: {type(info)}")
  834. if not self.name:
  835. puppet = await p.Puppet.get_by_address(self.chat_id)
  836. if not puppet.name:
  837. await puppet.update_info(info)
  838. self.name = puppet.name
  839. return
  840. if isinstance(info, GroupV2ID):
  841. info = await self.signal.get_group(source.username, info.id, info.revision or -1)
  842. if not info:
  843. self.log.debug(f"Failed to get full group v2 info through {source.username}, "
  844. "cancelling update")
  845. return
  846. changed = False
  847. if isinstance(info, Group):
  848. changed = await self._update_name(info.name, sender) or changed
  849. elif isinstance(info, GroupV2):
  850. if self.revision < info.revision:
  851. self.revision = info.revision
  852. changed = True
  853. elif self.revision > info.revision:
  854. self.log.warning(f"Got outdated info when syncing through {source.username} "
  855. f"({info.revision} < {self.revision}), ignoring...")
  856. return
  857. changed = await self._update_name(info.title, sender) or changed
  858. elif isinstance(info, GroupV2ID):
  859. return
  860. else:
  861. raise ValueError(f"Unexpected type for group update_info: {type(info)}")
  862. changed = await self._update_avatar(info, sender) or changed
  863. await self._update_participants(source, info)
  864. try:
  865. await self._update_power_levels(info)
  866. except Exception:
  867. self.log.warning("Error updating power levels", exc_info=True)
  868. if changed:
  869. await self.update_bridge_info()
  870. await self.update()
  871. async def update_expires_in_seconds(self, sender: 'p.Puppet', expires_in_seconds: int) -> None:
  872. if expires_in_seconds == 0:
  873. expires_in_seconds = None
  874. if self.expiration_time == expires_in_seconds:
  875. return
  876. assert self.mxid
  877. self.expiration_time = expires_in_seconds
  878. await self.update()
  879. time_str = "Off" if expires_in_seconds is None else format_duration(expires_in_seconds)
  880. await self.main_intent.send_notice(
  881. self.mxid,
  882. html=f'<a href="https://matrix.to/#/{sender.mxid}">{sender.name}</a> set the '
  883. f'disappearing message timer to {time_str}.'
  884. )
  885. async def update_puppet_avatar(self, new_hash: str, avatar_url: ContentURI) -> None:
  886. if not self.encrypted and not self.private_chat_portal_meta:
  887. return
  888. if self.avatar_hash != new_hash or not self.avatar_set:
  889. self.avatar_hash = new_hash
  890. self.avatar_url = avatar_url
  891. if self.mxid:
  892. try:
  893. await self.main_intent.set_room_avatar(self.mxid, avatar_url)
  894. self.avatar_set = True
  895. except Exception:
  896. self.log.exception("Error setting avatar")
  897. self.avatar_set = False
  898. await self.update_bridge_info()
  899. await self.update()
  900. async def update_puppet_name(self, name: str) -> None:
  901. if not self.encrypted and not self.private_chat_portal_meta:
  902. return
  903. changed = await self._update_name(name)
  904. if changed:
  905. await self.update_bridge_info()
  906. await self.update()
  907. async def _update_name(self, name: str, sender: Optional['p.Puppet'] = None) -> bool:
  908. if self.name != name or not self.name_set:
  909. self.name = name
  910. if self.mxid:
  911. try:
  912. await self._try_with_puppet(lambda i: i.set_room_name(self.mxid, self.name),
  913. puppet=sender)
  914. self.name_set = True
  915. except Exception:
  916. self.log.exception("Error setting name")
  917. self.name_set = False
  918. return True
  919. return False
  920. async def _try_with_puppet(self, action: Callable[[IntentAPI], Awaitable[Any]],
  921. puppet: Optional['p.Puppet'] = None) -> None:
  922. if puppet:
  923. try:
  924. await action(puppet.intent_for(self))
  925. except (MForbidden, IntentError):
  926. await action(self.main_intent)
  927. else:
  928. await action(self.main_intent)
  929. async def _update_avatar(self, info: ChatInfo, sender: Optional['p.Puppet'] = None) -> bool:
  930. path = None
  931. if isinstance(info, GroupV2):
  932. path = info.avatar
  933. elif isinstance(info, Group):
  934. path = f"group-{self.chat_id}"
  935. res = await p.Puppet.upload_avatar(self, path, self.main_intent)
  936. if res is False:
  937. return False
  938. self.avatar_hash, self.avatar_url = res
  939. if not self.mxid:
  940. return True
  941. try:
  942. await self._try_with_puppet(lambda i: i.set_room_avatar(self.mxid, self.avatar_url),
  943. puppet=sender)
  944. self.avatar_set = True
  945. except Exception:
  946. self.log.exception("Error setting avatar")
  947. self.avatar_set = False
  948. return True
  949. async def _update_participants(self, source: 'u.User', info: ChatInfo) -> None:
  950. if not self.mxid or not isinstance(info, (Group, GroupV2)):
  951. return
  952. pending_members = info.pending_members if isinstance(info, GroupV2) else []
  953. self._pending_members = {addr.uuid for addr in pending_members}
  954. for address in info.members:
  955. user = await u.User.get_by_address(address)
  956. if user:
  957. await self.main_intent.invite_user(self.mxid, user.mxid)
  958. puppet = await p.Puppet.get_by_address(address)
  959. await source.sync_contact(address)
  960. await puppet.intent_for(self).ensure_joined(self.mxid)
  961. for address in pending_members:
  962. user = await u.User.get_by_address(address)
  963. if user:
  964. await self.main_intent.invite_user(self.mxid, user.mxid)
  965. puppet = await p.Puppet.get_by_address(address)
  966. await source.sync_contact(address)
  967. await self.main_intent.invite_user(self.mxid, puppet.intent_for(self).mxid)
  968. async def _update_power_levels(self, info: ChatInfo) -> None:
  969. if not self.mxid:
  970. return
  971. power_levels = await self.main_intent.get_power_levels(self.mxid)
  972. power_levels = await self._get_power_levels(power_levels, info=info, is_initial=False)
  973. await self.main_intent.set_power_levels(self.mxid, power_levels)
  974. # endregion
  975. # region Bridge info state event
  976. @property
  977. def bridge_info_state_key(self) -> str:
  978. return f"net.maunium.signal://signal/{self.chat_id}"
  979. @property
  980. def bridge_info(self) -> Dict[str, Any]:
  981. return {
  982. "bridgebot": self.az.bot_mxid,
  983. "creator": self.main_intent.mxid,
  984. "protocol": {
  985. "id": "signal",
  986. "displayname": "Signal",
  987. "avatar_url": self.config["appservice.bot_avatar"],
  988. },
  989. "channel": {
  990. "id": str(self.chat_id),
  991. "displayname": self.name,
  992. "avatar_url": self.avatar_url,
  993. }
  994. }
  995. async def update_bridge_info(self) -> None:
  996. if not self.mxid:
  997. self.log.debug("Not updating bridge info: no Matrix room created")
  998. return
  999. try:
  1000. self.log.debug("Updating bridge info...")
  1001. await self.main_intent.send_state_event(self.mxid, StateBridge,
  1002. self.bridge_info, self.bridge_info_state_key)
  1003. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  1004. await self.main_intent.send_state_event(self.mxid, StateHalfShotBridge,
  1005. self.bridge_info, self.bridge_info_state_key)
  1006. except Exception:
  1007. self.log.warning("Failed to update bridge info", exc_info=True)
  1008. # endregion
  1009. # region Creating Matrix rooms
  1010. async def update_matrix_room(self, source: 'u.User', info: ChatInfo) -> None:
  1011. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  1012. raise ValueError(f"Unexpected type for updating group portal: {type(info)}")
  1013. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  1014. raise ValueError(f"Unexpected type for updating direct chat portal: {type(info)}")
  1015. try:
  1016. await self._update_matrix_room(source, info)
  1017. except Exception:
  1018. self.log.exception("Failed to update portal")
  1019. async def create_matrix_room(self, source: 'u.User', info: ChatInfo) -> Optional[RoomID]:
  1020. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  1021. raise ValueError(f"Unexpected type for creating group portal: {type(info)}")
  1022. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  1023. raise ValueError(f"Unexpected type for creating direct chat portal: {type(info)}")
  1024. if isinstance(info, Group) and not info.members:
  1025. groups = await self.signal.list_groups(source.username)
  1026. info = next((g for g in groups
  1027. if isinstance(g, Group) and g.group_id == info.group_id), info)
  1028. elif isinstance(info, GroupV2ID) and not isinstance(info, GroupV2):
  1029. self.log.debug(f"create_matrix_room() called with {info}, "
  1030. "fetching full info from signald")
  1031. info = await self.signal.get_group(source.username, info.id,
  1032. info.revision or -1)
  1033. if not info:
  1034. self.log.warning(f"Full info not found, canceling room creation")
  1035. return None
  1036. else:
  1037. self.log.trace("get_group() returned full info: %s", info)
  1038. if self.mxid:
  1039. await self.update_matrix_room(source, info)
  1040. return self.mxid
  1041. async with self._create_room_lock:
  1042. return await self._create_matrix_room(source, info)
  1043. def _get_invite_content(self, double_puppet: Optional['p.Puppet']) -> Dict[str, Any]:
  1044. invite_content = {}
  1045. if double_puppet:
  1046. invite_content["fi.mau.will_auto_accept"] = True
  1047. if self.is_direct:
  1048. invite_content["is_direct"] = True
  1049. return invite_content
  1050. async def _update_matrix_room(self, source: 'u.User', info: ChatInfo) -> None:
  1051. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  1052. await self.main_intent.invite_user(self.mxid, source.mxid, check_cache=True,
  1053. extra_content=self._get_invite_content(puppet))
  1054. if puppet:
  1055. did_join = await puppet.intent.ensure_joined(self.mxid)
  1056. if did_join and self.is_direct:
  1057. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  1058. await self.update_info(source, info)
  1059. async def _get_power_levels(self, levels: Optional[PowerLevelStateEventContent] = None,
  1060. info: Optional[ChatInfo] = None, is_initial: bool = False
  1061. ) -> PowerLevelStateEventContent:
  1062. levels = levels or PowerLevelStateEventContent()
  1063. if self.is_direct:
  1064. levels.ban = 99
  1065. levels.kick = 99
  1066. levels.invite = 99
  1067. levels.state_default = 0
  1068. meta_edit_level = 0
  1069. else:
  1070. if isinstance(info, GroupV2):
  1071. ac = info.access_control
  1072. for detail in info.member_detail + info.pending_member_detail:
  1073. puppet = await p.Puppet.get_by_address(Address(uuid=detail.uuid))
  1074. level = 50 if detail.role == GroupMemberRole.ADMINISTRATOR else 0
  1075. levels.users[puppet.intent_for(self).mxid] = level
  1076. else:
  1077. ac = GroupAccessControl()
  1078. levels.ban = 50
  1079. levels.kick = 50
  1080. levels.invite = 50 if ac.members == AccessControlMode.ADMINISTRATOR else 0
  1081. levels.state_default = 50
  1082. meta_edit_level = 50 if ac.attributes == AccessControlMode.ADMINISTRATOR else 0
  1083. levels.events[EventType.ROOM_NAME] = meta_edit_level
  1084. levels.events[EventType.ROOM_AVATAR] = meta_edit_level
  1085. levels.events[EventType.ROOM_TOPIC] = meta_edit_level
  1086. levels.events[EventType.ROOM_ENCRYPTION] = 50 if self.matrix.e2ee else 99
  1087. levels.events[EventType.ROOM_TOMBSTONE] = 99
  1088. levels.users_default = 0
  1089. levels.events_default = 0
  1090. # Remote delete is only for your own messages
  1091. levels.redact = 99
  1092. if self.main_intent.mxid not in levels.users:
  1093. levels.users[self.main_intent.mxid] = 9001 if is_initial else 100
  1094. return levels
  1095. async def _create_matrix_room(self, source: 'u.User', info: ChatInfo) -> Optional[RoomID]:
  1096. if self.mxid:
  1097. await self._update_matrix_room(source, info)
  1098. return self.mxid
  1099. await self.update_info(source, info)
  1100. self.log.debug("Creating Matrix room")
  1101. name: Optional[str] = None
  1102. power_levels = await self._get_power_levels(info=info, is_initial=True)
  1103. initial_state = [{
  1104. "type": str(StateBridge),
  1105. "state_key": self.bridge_info_state_key,
  1106. "content": self.bridge_info,
  1107. }, {
  1108. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  1109. "type": str(StateHalfShotBridge),
  1110. "state_key": self.bridge_info_state_key,
  1111. "content": self.bridge_info,
  1112. }, {
  1113. "type": str(EventType.ROOM_POWER_LEVELS),
  1114. "content": power_levels.serialize(),
  1115. }]
  1116. invites = []
  1117. if self.config["bridge.encryption.default"] and self.matrix.e2ee:
  1118. self.encrypted = True
  1119. initial_state.append({
  1120. "type": str(EventType.ROOM_ENCRYPTION),
  1121. "content": {"algorithm": "m.megolm.v1.aes-sha2"},
  1122. })
  1123. if self.is_direct:
  1124. invites.append(self.az.bot_mxid)
  1125. if self.is_direct and source.address == self.chat_id:
  1126. name = self.name = "Signal Note to Self"
  1127. elif self.encrypted or self.private_chat_portal_meta or not self.is_direct:
  1128. name = self.name
  1129. if self.avatar_url:
  1130. initial_state.append({
  1131. "type": str(EventType.ROOM_AVATAR),
  1132. "content": {"url": self.avatar_url},
  1133. })
  1134. if self.config["appservice.community_id"]:
  1135. initial_state.append({
  1136. "type": "m.room.related_groups",
  1137. "content": {"groups": [self.config["appservice.community_id"]]},
  1138. })
  1139. creation_content = {}
  1140. if not self.config["bridge.federate_rooms"]:
  1141. creation_content["m.federate"] = False
  1142. self.mxid = await self.main_intent.create_room(
  1143. name=name,
  1144. is_direct=self.is_direct,
  1145. initial_state=initial_state,
  1146. invitees=invites,
  1147. creation_content=creation_content,
  1148. )
  1149. if not self.mxid:
  1150. raise Exception("Failed to create room: no mxid returned")
  1151. self.name_set = bool(name)
  1152. self.avatar_set = bool(self.avatar_url)
  1153. if self.encrypted and self.matrix.e2ee and self.is_direct:
  1154. try:
  1155. await self.az.intent.ensure_joined(self.mxid)
  1156. except Exception:
  1157. self.log.warning("Failed to add bridge bot "
  1158. f"to new private chat {self.mxid}")
  1159. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  1160. await self.main_intent.invite_user(self.mxid, source.mxid,
  1161. extra_content=self._get_invite_content(puppet))
  1162. if puppet:
  1163. try:
  1164. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  1165. await puppet.intent.join_room_by_id(self.mxid)
  1166. except MatrixError:
  1167. self.log.debug("Failed to join custom puppet into newly created portal",
  1168. exc_info=True)
  1169. await self.update()
  1170. self.log.debug(f"Matrix room created: {self.mxid}")
  1171. self.by_mxid[self.mxid] = self
  1172. if not self.is_direct:
  1173. await self._update_participants(source, info)
  1174. # TODO
  1175. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  1176. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  1177. # in_community=in_community).upsert()
  1178. return self.mxid
  1179. # endregion
  1180. # region Database getters
  1181. async def _postinit(self) -> None:
  1182. self.by_chat_id[(self.chat_id_str, self.receiver)] = self
  1183. if self.mxid:
  1184. self.by_mxid[self.mxid] = self
  1185. if self.is_direct:
  1186. puppet = await p.Puppet.get_by_address(self.chat_id)
  1187. self._main_intent = puppet.default_mxid_intent
  1188. elif not self.is_direct:
  1189. self._main_intent = self.az.intent
  1190. async def delete(self) -> None:
  1191. await DBMessage.delete_all(self.mxid)
  1192. self.by_mxid.pop(self.mxid, None)
  1193. self.mxid = None
  1194. self.encrypted = False
  1195. await self.update()
  1196. async def save(self) -> None:
  1197. await self.update()
  1198. @classmethod
  1199. def all_with_room(cls) -> AsyncGenerator['Portal', None]:
  1200. return cls._db_to_portals(super().all_with_room())
  1201. @classmethod
  1202. def find_private_chats_with(cls, other_user: Address) -> AsyncGenerator['Portal', None]:
  1203. return cls._db_to_portals(super().find_private_chats_with(other_user))
  1204. @classmethod
  1205. async def _db_to_portals(cls, query: Awaitable[List['Portal']]
  1206. ) -> AsyncGenerator['Portal', None]:
  1207. portals = await query
  1208. for index, portal in enumerate(portals):
  1209. try:
  1210. yield cls.by_chat_id[(portal.chat_id_str, portal.receiver)]
  1211. except KeyError:
  1212. await portal._postinit()
  1213. yield portal
  1214. @classmethod
  1215. @async_getter_lock
  1216. async def get_by_mxid(cls, mxid: RoomID) -> Optional['Portal']:
  1217. try:
  1218. return cls.by_mxid[mxid]
  1219. except KeyError:
  1220. pass
  1221. portal = cast(cls, await super().get_by_mxid(mxid))
  1222. if portal is not None:
  1223. await portal._postinit()
  1224. return portal
  1225. return None
  1226. @classmethod
  1227. async def get_by_chat_id(cls, chat_id: Union[GroupID, Address], *, receiver: str = "",
  1228. create: bool = False) -> Optional['Portal']:
  1229. if isinstance(chat_id, str):
  1230. receiver = ""
  1231. elif not isinstance(chat_id, Address):
  1232. raise ValueError(f"Invalid chat ID type {type(chat_id)}")
  1233. elif not receiver:
  1234. raise ValueError("Direct chats must have a receiver")
  1235. best_id = id_to_str(chat_id)
  1236. portal = await cls._get_by_chat_id(best_id, receiver, create=create, chat_id=chat_id)
  1237. if portal:
  1238. portal.log.debug(f"get_by_chat_id({chat_id}, {receiver}) -> {hex(id(portal))}")
  1239. return portal
  1240. @classmethod
  1241. @async_getter_lock
  1242. async def _get_by_chat_id(cls, best_id: str, receiver: str, *, create: bool,
  1243. chat_id: Union[GroupID, Address]) -> Optional['Portal']:
  1244. try:
  1245. return cls.by_chat_id[(best_id, receiver)]
  1246. except KeyError:
  1247. pass
  1248. portal = cast(cls, await super().get_by_chat_id(chat_id, receiver))
  1249. if portal is not None:
  1250. await portal._postinit()
  1251. return portal
  1252. if create:
  1253. portal = cls(chat_id, receiver)
  1254. await portal.insert()
  1255. await portal._postinit()
  1256. return portal
  1257. return None
  1258. # endregion