portal.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. # mautrix-signal - A Matrix-Signal puppeting bridge
  2. # Copyright (C) 2020 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 collections import deque
  19. from uuid import UUID, uuid4
  20. import mimetypes
  21. import hashlib
  22. import asyncio
  23. import os.path
  24. import time
  25. import os
  26. from mausignald.types import (Address, MessageData, Reaction, Quote, Group, Contact, Profile,
  27. Attachment, GroupID, GroupV2ID, GroupV2, Mention, Sticker,
  28. GroupAccessControl, AccessControlMode, GroupMemberRole)
  29. from mausignald.errors import RPCError
  30. from mautrix.appservice import AppService, IntentAPI
  31. from mautrix.bridge import BasePortal, async_getter_lock
  32. from mautrix.types import (EventID, MessageEventContent, RoomID, EventType, MessageType,
  33. MessageEvent, EncryptedEvent, ContentURI, MediaMessageEventContent,
  34. ImageInfo, VideoInfo, FileInfo, AudioInfo, PowerLevelStateEventContent)
  35. from mautrix.errors import MatrixError, MForbidden, IntentError
  36. from .db import Portal as DBPortal, Message as DBMessage, Reaction as DBReaction
  37. from .config import Config
  38. from .formatter import matrix_to_signal, signal_to_matrix
  39. from . import user as u, puppet as p, matrix as m, signal as s
  40. if TYPE_CHECKING:
  41. from .__main__ import SignalBridge
  42. try:
  43. from mautrix.crypto.attachments import encrypt_attachment, decrypt_attachment
  44. except ImportError:
  45. encrypt_attachment = decrypt_attachment = None
  46. try:
  47. from signalstickers_client import StickersClient
  48. from signalstickers_client.models import StickerPack
  49. except ImportError:
  50. StickersClient = StickerPack = None
  51. try:
  52. import magic
  53. except ImportError:
  54. magic = None
  55. StateBridge = EventType.find("m.bridge", EventType.Class.STATE)
  56. StateHalfShotBridge = EventType.find("uk.half-shot.bridge", EventType.Class.STATE)
  57. ChatInfo = Union[Group, GroupV2, GroupV2ID, Contact, Profile, Address]
  58. class Portal(DBPortal, BasePortal):
  59. by_mxid: Dict[RoomID, 'Portal'] = {}
  60. by_chat_id: Dict[Tuple[str, str], 'Portal'] = {}
  61. _sticker_meta_cache: Dict[str, StickerPack] = {}
  62. config: Config
  63. matrix: 'm.MatrixHandler'
  64. signal: 's.SignalHandler'
  65. az: AppService
  66. private_chat_portal_meta: bool
  67. _main_intent: Optional[IntentAPI]
  68. _create_room_lock: asyncio.Lock
  69. _msgts_dedup: Deque[Tuple[Address, int]]
  70. _reaction_dedup: Deque[Tuple[Address, int, str]]
  71. _reaction_lock: asyncio.Lock
  72. _pending_members: Optional[Set[UUID]]
  73. def __init__(self, chat_id: Union[GroupID, Address], receiver: str,
  74. mxid: Optional[RoomID] = None, name: Optional[str] = None,
  75. avatar_hash: Optional[str] = None, avatar_url: Optional[ContentURI] = None,
  76. name_set: bool = False, avatar_set: bool = False, revision: int = 0,
  77. encrypted: bool = False) -> None:
  78. super().__init__(chat_id, receiver, mxid, name, avatar_hash, avatar_url,
  79. name_set, avatar_set, revision, encrypted)
  80. self._create_room_lock = asyncio.Lock()
  81. self.log = self.log.getChild(self.chat_id_str)
  82. self._main_intent = None
  83. self._msgts_dedup = deque(maxlen=100)
  84. self._reaction_dedup = deque(maxlen=100)
  85. self._last_participant_update = set()
  86. self._reaction_lock = asyncio.Lock()
  87. self._pending_members = None
  88. @property
  89. def main_intent(self) -> IntentAPI:
  90. if not self._main_intent:
  91. raise ValueError("Portal must be postinit()ed before main_intent can be used")
  92. return self._main_intent
  93. @property
  94. def is_direct(self) -> bool:
  95. return isinstance(self.chat_id, Address)
  96. def handle_uuid_receive(self, uuid: UUID) -> None:
  97. if not self.is_direct or self.chat_id.uuid:
  98. raise ValueError("handle_uuid_receive can only be used for private chat portals with "
  99. "a phone number chat_id")
  100. del self.by_chat_id[(self.chat_id_str, self.receiver)]
  101. self.chat_id = Address(uuid=uuid)
  102. self.by_chat_id[(self.chat_id_str, self.receiver)] = self
  103. @classmethod
  104. def init_cls(cls, bridge: 'SignalBridge') -> None:
  105. cls.config = bridge.config
  106. cls.matrix = bridge.matrix
  107. cls.signal = bridge.signal
  108. cls.az = bridge.az
  109. cls.loop = bridge.loop
  110. BasePortal.bridge = bridge
  111. cls.private_chat_portal_meta = cls.config["bridge.private_chat_portal_meta"]
  112. # region Misc
  113. async def _send_delivery_receipt(self, event_id: EventID) -> None:
  114. if event_id and self.config["bridge.delivery_receipts"]:
  115. try:
  116. await self.az.intent.mark_read(self.mxid, event_id)
  117. except Exception:
  118. self.log.exception("Failed to send delivery receipt for %s", event_id)
  119. async def _upsert_reaction(self, existing: DBReaction, intent: IntentAPI, mxid: EventID,
  120. sender: Union['p.Puppet', 'u.User'], message: DBMessage, emoji: str
  121. ) -> None:
  122. if existing:
  123. self.log.debug(f"_upsert_reaction redacting {existing.mxid} and inserting {mxid}"
  124. f" (message: {message.mxid})")
  125. try:
  126. await intent.redact(existing.mx_room, existing.mxid)
  127. except MForbidden:
  128. self.log.debug("Unexpected MForbidden redacting reaction", exc_info=True)
  129. await existing.edit(emoji=emoji, mxid=mxid, mx_room=message.mx_room)
  130. else:
  131. self.log.debug(f"_upsert_reaction inserting {mxid} (message: {message.mxid})")
  132. await DBReaction(mxid=mxid, mx_room=message.mx_room, emoji=emoji,
  133. signal_chat_id=self.chat_id, signal_receiver=self.receiver,
  134. msg_author=message.sender, msg_timestamp=message.timestamp,
  135. author=sender.address).insert()
  136. # endregion
  137. # region Matrix event handling
  138. @staticmethod
  139. def _make_attachment(message: MediaMessageEventContent, path: str) -> Attachment:
  140. attachment = Attachment(custom_filename=message.body, content_type=message.info.mimetype,
  141. outgoing_filename=path)
  142. info = message.info
  143. attachment.width = info.get("w", info.get("width", 0))
  144. attachment.height = info.get("h", info.get("height", 0))
  145. attachment.voice_note = message.msgtype == MessageType.AUDIO
  146. return attachment
  147. async def _download_matrix_media(self, message: MediaMessageEventContent) -> str:
  148. if message.file:
  149. data = await self.main_intent.download_media(message.file.url)
  150. data = decrypt_attachment(data, message.file.key.key,
  151. message.file.hashes.get("sha256"), message.file.iv)
  152. else:
  153. data = await self.main_intent.download_media(message.url)
  154. path = os.path.join(self.config["signal.outgoing_attachment_dir"],
  155. f"mautrix-signal-{str(uuid4())}")
  156. with open(path, "wb") as file:
  157. file.write(data)
  158. return path
  159. async def handle_matrix_message(self, sender: 'u.User', message: MessageEventContent,
  160. event_id: EventID) -> None:
  161. if ((message.get(self.bridge.real_user_content_key, False)
  162. and await p.Puppet.get_by_custom_mxid(sender.mxid))):
  163. self.log.debug(f"Ignoring puppet-sent message by confirmed puppet user {sender.mxid}")
  164. return
  165. request_id = int(time.time() * 1000)
  166. self._msgts_dedup.appendleft((sender.address, request_id))
  167. quote = None
  168. if message.get_reply_to():
  169. reply = await DBMessage.get_by_mxid(message.get_reply_to(), self.mxid)
  170. # TODO include actual text? either store in db or fetch event from homeserver
  171. if reply is not None:
  172. quote = Quote(id=reply.timestamp, author=reply.sender, text="")
  173. attachments: Optional[List[Attachment]] = None
  174. attachment_path: Optional[str] = None
  175. mentions: Optional[List[Mention]] = None
  176. if message.msgtype.is_text:
  177. text, mentions = await matrix_to_signal(message)
  178. elif message.msgtype.is_media:
  179. attachment_path = await self._download_matrix_media(message)
  180. attachment = self._make_attachment(message, attachment_path)
  181. attachments = [attachment]
  182. text = None
  183. self.log.trace("Formed outgoing attachment %s", attachment)
  184. else:
  185. self.log.debug(f"Unknown msgtype {message.msgtype} in Matrix message {event_id}")
  186. return
  187. await self.signal.send(username=sender.username, recipient=self.chat_id, body=text,
  188. mentions=mentions, quote=quote, attachments=attachments,
  189. timestamp=request_id)
  190. msg = DBMessage(mxid=event_id, mx_room=self.mxid, sender=sender.address,
  191. timestamp=request_id,
  192. signal_chat_id=self.chat_id, signal_receiver=self.receiver)
  193. await msg.insert()
  194. await self._send_delivery_receipt(event_id)
  195. self.log.debug(f"Handled Matrix message {event_id} -> {request_id}")
  196. if attachment_path and self.config["signal.remove_file_after_handling"]:
  197. try:
  198. os.remove(attachment_path)
  199. except FileNotFoundError:
  200. pass
  201. async def handle_matrix_reaction(self, sender: 'u.User', event_id: EventID,
  202. reacting_to: EventID, emoji: str) -> None:
  203. # Signal doesn't seem to use variation selectors at all
  204. emoji = emoji.rstrip("\ufe0f")
  205. message = await DBMessage.get_by_mxid(reacting_to, self.mxid)
  206. if not message:
  207. self.log.debug(f"Ignoring reaction to unknown event {reacting_to}")
  208. return
  209. existing = await DBReaction.get_by_signal_id(self.chat_id, self.receiver, message.sender,
  210. message.timestamp, sender.address)
  211. if existing and existing.emoji == emoji:
  212. return
  213. dedup_id = (message.sender, message.timestamp, emoji)
  214. self._reaction_dedup.appendleft(dedup_id)
  215. async with self._reaction_lock:
  216. reaction = Reaction(emoji=emoji, remove=False,
  217. target_author=message.sender,
  218. target_sent_timestamp=message.timestamp)
  219. await self.signal.react(username=sender.username, recipient=self.chat_id,
  220. reaction=reaction)
  221. await self._upsert_reaction(existing, self.main_intent, event_id, sender, message,
  222. emoji)
  223. self.log.trace(f"{sender.mxid} reacted to {message.timestamp} with {emoji}")
  224. await self._send_delivery_receipt(event_id)
  225. async def handle_matrix_redaction(self, sender: 'u.User', event_id: EventID,
  226. redaction_event_id: EventID) -> None:
  227. if not self.mxid:
  228. return
  229. # TODO message redactions after https://gitlab.com/signald/signald/-/issues/37
  230. reaction = await DBReaction.get_by_mxid(event_id, self.mxid)
  231. if reaction:
  232. try:
  233. await reaction.delete()
  234. remove_reaction = Reaction(emoji=reaction.emoji, remove=True,
  235. target_author=reaction.msg_author,
  236. target_sent_timestamp=reaction.msg_timestamp)
  237. await self.signal.react(username=sender.username, recipient=self.chat_id,
  238. reaction=remove_reaction)
  239. await self._send_delivery_receipt(redaction_event_id)
  240. self.log.trace(f"Removed {reaction} after Matrix redaction")
  241. except Exception:
  242. self.log.exception("Removing reaction failed")
  243. async def handle_matrix_join(self, user: 'u.User') -> None:
  244. if self.is_direct:
  245. return
  246. if self._pending_members is None:
  247. self.log.debug(f"{user.mxid} ({user.uuid}) joined room, but pending_members is None,"
  248. " updating chat info")
  249. await self.update_info(user, GroupV2ID(id=self.chat_id))
  250. if self._pending_members is None:
  251. self.log.warning(f"Didn't get pending member list after info update, "
  252. f"{user.mxid} ({user.uuid}) may not be in the group on Signal.")
  253. elif user.uuid in self._pending_members:
  254. self.log.debug(f"{user.mxid} ({user.uuid}) joined room, accepting invite on Signal")
  255. try:
  256. resp = await self.signal.accept_invitation(user.username, self.chat_id)
  257. self._pending_members.remove(user.uuid)
  258. except RPCError as e:
  259. await self.main_intent.send_notice(self.mxid, "\u26a0 Failed to accept invite "
  260. f"on Signal: {e}")
  261. else:
  262. await self.update_info(user, resp)
  263. async def handle_matrix_leave(self, user: 'u.User') -> None:
  264. if self.is_direct:
  265. self.log.info(f"{user.mxid} left private chat portal with {self.chat_id}")
  266. if user.username == self.receiver:
  267. self.log.info(f"{user.mxid} was the recipient of this portal. "
  268. "Cleaning up and deleting...")
  269. await self.cleanup_and_delete()
  270. else:
  271. self.log.debug(f"{user.mxid} left portal to {self.chat_id}")
  272. # TODO cleanup if empty
  273. async def handle_matrix_name(self, user: 'u.User', name: str) -> None:
  274. if self.name == name or self.is_direct or not name:
  275. return
  276. self.name = name
  277. self.log.debug(f"{user.mxid} changed the group name, sending to Signal")
  278. try:
  279. await self.signal.update_group(user.username, self.chat_id, title=name)
  280. except Exception:
  281. self.log.exception("Failed to update Signal group name")
  282. self.name = None
  283. async def handle_matrix_avatar(self, user: 'u.User', url: ContentURI) -> None:
  284. if self.is_direct or not url:
  285. return
  286. data = await self.main_intent.download_media(url)
  287. new_hash = hashlib.sha256(data).hexdigest()
  288. if new_hash == self.avatar_hash and self.avatar_set:
  289. self.log.debug(f"New avatar from Matrix set by {user.mxid} is same as current one")
  290. return
  291. self.avatar_url = url
  292. self.avatar_hash = new_hash
  293. path = os.path.join(self.config["signal.outgoing_attachment_dir"],
  294. f"mautrix-signal-avatar-{str(uuid4())}")
  295. self.log.debug(f"{user.mxid} changed the group avatar, sending to Signal")
  296. try:
  297. with open(path, "wb") as file:
  298. file.write(data)
  299. await self.signal.update_group(user.username, self.chat_id, avatar_path=path)
  300. self.avatar_set = True
  301. except Exception:
  302. self.log.exception("Failed to update Signal group avatar")
  303. self.avatar_set = False
  304. if self.config["signal.remove_file_after_handling"]:
  305. try:
  306. os.remove(path)
  307. except FileNotFoundError:
  308. pass
  309. # endregion
  310. # region Signal event handling
  311. @staticmethod
  312. async def _resolve_address(address: Address) -> Address:
  313. puppet = await p.Puppet.get_by_address(address, create=False)
  314. return puppet.address
  315. async def _find_quote_event_id(self, quote: Optional[Quote]
  316. ) -> Optional[Union[MessageEvent, EventID]]:
  317. if not quote:
  318. return None
  319. author_address = await self._resolve_address(quote.author)
  320. reply_msg = await DBMessage.get_by_signal_id(author_address, quote.id,
  321. self.chat_id, self.receiver)
  322. if not reply_msg:
  323. return None
  324. try:
  325. evt = await self.main_intent.get_event(self.mxid, reply_msg.mxid)
  326. if isinstance(evt, EncryptedEvent):
  327. return await self.matrix.e2ee.decrypt(evt, wait_session_timeout=0)
  328. return evt
  329. except MatrixError:
  330. return reply_msg.mxid
  331. async def handle_signal_message(self, source: 'u.User', sender: 'p.Puppet',
  332. message: MessageData) -> None:
  333. if (sender.address, message.timestamp) in self._msgts_dedup:
  334. self.log.debug(f"Ignoring message {message.timestamp} by {sender.uuid}"
  335. " as it was already handled (message.timestamp in dedup queue)")
  336. await self.signal.send_receipt(source.username, sender.address,
  337. timestamps=[message.timestamp])
  338. return
  339. old_message = await DBMessage.get_by_signal_id(sender.address, message.timestamp,
  340. self.chat_id, self.receiver)
  341. if old_message is not None:
  342. self.log.debug(f"Ignoring message {message.timestamp} by {sender.uuid}"
  343. " as it was already handled (message.id found in database)")
  344. await self.signal.send_receipt(source.username, sender.address,
  345. timestamps=[message.timestamp])
  346. return
  347. self.log.debug(f"Started handling message {message.timestamp} by {sender.uuid}")
  348. self.log.trace(f"Message content: {message}")
  349. self._msgts_dedup.appendleft((sender.address, message.timestamp))
  350. intent = sender.intent_for(self)
  351. await intent.set_typing(self.mxid, False)
  352. event_id = None
  353. reply_to = await self._find_quote_event_id(message.quote)
  354. if message.sticker:
  355. if message.sticker.attachment.incoming_filename:
  356. content = await self._handle_signal_attachment(intent, message.sticker.attachment)
  357. elif StickersClient:
  358. content = await self._handle_signal_sticker(intent, message.sticker)
  359. else:
  360. self.log.debug(f"Not handling sticker in {message.timestamp}: no incoming_filename"
  361. " and signalstickers-client not installed.")
  362. return
  363. if content:
  364. if message.sticker.attachment.blurhash:
  365. content.info["blurhash"] = message.sticker.attachment.blurhash
  366. content.info["xyz.amorgan.blurhash"] = message.sticker.attachment.blurhash
  367. await self._add_sticker_meta(message.sticker, content)
  368. if reply_to and not message.body:
  369. content.set_reply(reply_to)
  370. reply_to = None
  371. event_id = await self._send_message(intent, content, timestamp=message.timestamp,
  372. event_type=EventType.STICKER)
  373. for attachment in message.attachments:
  374. if not attachment.incoming_filename:
  375. self.log.warning("Failed to bridge attachment, no incoming filename: %s",
  376. attachment)
  377. continue
  378. content = await self._handle_signal_attachment(intent, attachment)
  379. if reply_to and not message.body:
  380. # If there's no text, set the first image as the reply
  381. content.set_reply(reply_to)
  382. reply_to = None
  383. event_id = await self._send_message(intent, content, timestamp=message.timestamp)
  384. if message.body:
  385. content = await signal_to_matrix(message)
  386. if reply_to:
  387. content.set_reply(reply_to)
  388. event_id = await self._send_message(intent, content, timestamp=message.timestamp)
  389. if event_id:
  390. msg = DBMessage(mxid=event_id, mx_room=self.mxid,
  391. sender=sender.address, timestamp=message.timestamp,
  392. signal_chat_id=self.chat_id, signal_receiver=self.receiver)
  393. await msg.insert()
  394. await self.signal.send_receipt(source.username, sender.address,
  395. timestamps=[message.timestamp])
  396. await self._send_delivery_receipt(event_id)
  397. self.log.debug(f"Handled Signal message {message.timestamp} -> {event_id}")
  398. else:
  399. self.log.debug(f"Didn't get event ID for {message.timestamp}")
  400. @staticmethod
  401. def _make_media_content(attachment: Attachment) -> MediaMessageEventContent:
  402. if attachment.content_type.startswith("image/"):
  403. msgtype = MessageType.IMAGE
  404. info = ImageInfo(mimetype=attachment.content_type,
  405. width=attachment.width, height=attachment.height)
  406. elif attachment.content_type.startswith("video/"):
  407. msgtype = MessageType.VIDEO
  408. info = VideoInfo(mimetype=attachment.content_type,
  409. width=attachment.width, height=attachment.height)
  410. elif attachment.voice_note or attachment.content_type.startswith("audio/"):
  411. msgtype = MessageType.AUDIO
  412. info = AudioInfo(mimetype=attachment.content_type)
  413. else:
  414. msgtype = MessageType.FILE
  415. info = FileInfo(mimetype=attachment.content_type)
  416. if not attachment.custom_filename:
  417. ext = mimetypes.guess_extension(attachment.content_type) or ""
  418. attachment.custom_filename = attachment.id + ext
  419. if attachment.blurhash:
  420. info["blurhash"] = attachment.blurhash
  421. info["xyz.amorgan.blurhash"] = attachment.blurhash
  422. return MediaMessageEventContent(msgtype=msgtype, info=info,
  423. body=attachment.custom_filename)
  424. async def _handle_signal_attachment(self, intent: IntentAPI, attachment: Attachment
  425. ) -> MediaMessageEventContent:
  426. self.log.trace(f"Reuploading attachment {attachment}")
  427. if not attachment.content_type:
  428. attachment.content_type = (magic.from_file(attachment.incoming_filename, mime=True)
  429. if magic is not None else "application/octet-stream")
  430. content = self._make_media_content(attachment)
  431. with open(attachment.incoming_filename, "rb") as file:
  432. data = file.read()
  433. if self.config["signal.remove_file_after_handling"]:
  434. os.remove(attachment.incoming_filename)
  435. await self._upload_attachment(intent, content, data, attachment.id)
  436. return content
  437. async def _add_sticker_meta(self, sticker: Sticker, content: MediaMessageEventContent) -> None:
  438. try:
  439. pack = self._sticker_meta_cache[sticker.pack_id]
  440. except KeyError:
  441. self.log.debug(f"Fetching sticker pack metadata for {sticker.pack_id}")
  442. try:
  443. async with StickersClient() as client:
  444. pack = await client.get_pack_metadata(sticker.pack_id, sticker.pack_key)
  445. self._sticker_meta_cache[sticker.pack_id] = pack
  446. except Exception:
  447. self.log.warning(f"Failed to fetch pack metadata for {sticker.pack_id}",
  448. exc_info=True)
  449. pack = None
  450. if not pack:
  451. content.info["fi.mau.signal.sticker"] = {
  452. "id": sticker.sticker_id,
  453. "pack": {
  454. "id": sticker.pack_id,
  455. "key": sticker.pack_key,
  456. },
  457. }
  458. return
  459. sticker_meta = pack.stickers[sticker.sticker_id]
  460. content.body = sticker_meta.emoji
  461. content.info["fi.mau.signal.sticker"] = {
  462. "id": sticker.sticker_id,
  463. "emoji": sticker_meta.emoji,
  464. "pack": {
  465. "id": pack.id,
  466. "key": pack.key,
  467. "title": pack.title,
  468. "author": pack.author,
  469. },
  470. }
  471. async def _handle_signal_sticker(self, intent: IntentAPI, sticker: Sticker
  472. ) -> Optional[MediaMessageEventContent]:
  473. try:
  474. self.log.debug(f"Fetching sticker {sticker.pack_id}#{sticker.sticker_id}")
  475. async with StickersClient() as client:
  476. data = await client.download_sticker(sticker.sticker_id,
  477. sticker.pack_id, sticker.pack_key)
  478. except Exception:
  479. self.log.warning(f"Failed to download sticker {sticker.sticker_id}", exc_info=True)
  480. return None
  481. info = ImageInfo(mimetype=sticker.attachment.content_type, size=len(data),
  482. width=sticker.attachment.width, height=sticker.attachment.height)
  483. if info.width > 256 or info.height > 256:
  484. if info.width == info.height:
  485. info.width = info.height = 256
  486. elif info.width > info.height:
  487. info.height = int(info.height / (info.width / 256))
  488. info.width = 256
  489. else:
  490. info.width = int(info.width / (info.height / 256))
  491. info.height = 256
  492. if magic:
  493. info.mimetype = magic.from_buffer(data, mime=True)
  494. ext = mimetypes.guess_extension(info.mimetype)
  495. if not ext and info.mimetype == "image/webp":
  496. ext = ".webp"
  497. content = MediaMessageEventContent(msgtype=MessageType.IMAGE, info=info,
  498. body=f"sticker{ext}")
  499. await self._upload_attachment(intent, content, data, sticker.attachment.id)
  500. return content
  501. async def _upload_attachment(self, intent: IntentAPI, content: MediaMessageEventContent,
  502. data: bytes, id: str) -> None:
  503. upload_mime_type = content.info.mimetype
  504. if self.encrypted and encrypt_attachment:
  505. data, content.file = encrypt_attachment(data)
  506. upload_mime_type = "application/octet-stream"
  507. content.url = await intent.upload_media(data, mime_type=upload_mime_type, filename=id)
  508. if content.file:
  509. content.file.url = content.url
  510. content.url = None
  511. # This is a hack for bad clients like Element iOS that require a thumbnail
  512. if content.info.mimetype.startswith("image/"):
  513. if content.file:
  514. content.info.thumbnail_file = content.file
  515. elif content.url:
  516. content.info.thumbnail_url = content.url
  517. async def handle_signal_reaction(self, sender: 'p.Puppet', reaction: Reaction) -> None:
  518. author_address = await self._resolve_address(reaction.target_author)
  519. target_id = reaction.target_sent_timestamp
  520. async with self._reaction_lock:
  521. dedup_id = (author_address, target_id, reaction.emoji)
  522. if dedup_id in self._reaction_dedup:
  523. return
  524. self._reaction_dedup.appendleft(dedup_id)
  525. existing = await DBReaction.get_by_signal_id(self.chat_id, self.receiver,
  526. author_address, target_id, sender.address)
  527. if reaction.remove:
  528. if existing:
  529. try:
  530. await sender.intent_for(self).redact(existing.mx_room, existing.mxid)
  531. except IntentError:
  532. await self.main_intent.redact(existing.mx_room, existing.mxid)
  533. await existing.delete()
  534. self.log.trace(f"Removed {existing} after Signal removal")
  535. return
  536. elif existing and existing.emoji == reaction.emoji:
  537. return
  538. message = await DBMessage.get_by_signal_id(author_address, target_id,
  539. self.chat_id, self.receiver)
  540. if not message:
  541. self.log.debug(f"Ignoring reaction to unknown message {target_id}")
  542. return
  543. intent = sender.intent_for(self)
  544. # TODO add variation selectors to emoji before sending to Matrix
  545. mxid = await intent.react(message.mx_room, message.mxid, reaction.emoji)
  546. self.log.debug(f"{sender.address} reacted to {message.mxid} -> {mxid}")
  547. await self._upsert_reaction(existing, intent, mxid, sender, message, reaction.emoji)
  548. async def handle_signal_delete(self, sender: 'p.Puppet', message_ts: int) -> None:
  549. message = await DBMessage.get_by_signal_id(sender.address, message_ts,
  550. self.chat_id, self.receiver)
  551. if not message:
  552. return
  553. await message.delete()
  554. try:
  555. await sender.intent_for(self).redact(message.mx_room, message.mxid)
  556. except MForbidden:
  557. await self.main_intent.redact(message.mx_room, message.mxid)
  558. # endregion
  559. # region Updating portal info
  560. async def update_info(self, source: 'u.User', info: ChatInfo,
  561. sender: Optional['p.Puppet'] = None) -> None:
  562. if self.is_direct:
  563. if not isinstance(info, (Contact, Profile, Address)):
  564. raise ValueError(f"Unexpected type for direct chat update_info: {type(info)}")
  565. if not self.name:
  566. puppet = await p.Puppet.get_by_address(self.chat_id)
  567. if not puppet.name:
  568. await puppet.update_info(info)
  569. self.name = puppet.name
  570. return
  571. if isinstance(info, GroupV2ID):
  572. info = await self.signal.get_group(source.username, info.id, info.revision or -1)
  573. if not info:
  574. self.log.debug(f"Failed to get full group v2 info through {source.username}, "
  575. "cancelling update")
  576. return
  577. changed = False
  578. if isinstance(info, Group):
  579. changed = await self._update_name(info.name, sender) or changed
  580. elif isinstance(info, GroupV2):
  581. if self.revision < info.revision:
  582. self.revision = info.revision
  583. changed = True
  584. elif self.revision > info.revision:
  585. self.log.warning(f"Got outdated info when syncing through {source.username} "
  586. f"({info.revision} < {self.revision}), ignoring...")
  587. return
  588. changed = await self._update_name(info.title, sender) or changed
  589. elif isinstance(info, GroupV2ID):
  590. return
  591. else:
  592. raise ValueError(f"Unexpected type for group update_info: {type(info)}")
  593. changed = await self._update_avatar(info, sender) or changed
  594. await self._update_participants(source, info)
  595. try:
  596. await self._update_power_levels(info)
  597. except Exception:
  598. self.log.warning("Error updating power levels", exc_info=True)
  599. if changed:
  600. await self.update_bridge_info()
  601. await self.update()
  602. async def update_puppet_avatar(self, new_hash: str, avatar_url: ContentURI) -> None:
  603. if not self.encrypted and not self.private_chat_portal_meta:
  604. return
  605. if self.avatar_hash != new_hash or not self.avatar_set:
  606. self.avatar_hash = new_hash
  607. self.avatar_url = avatar_url
  608. if self.mxid:
  609. try:
  610. await self.main_intent.set_room_avatar(self.mxid, avatar_url)
  611. self.avatar_set = True
  612. except Exception:
  613. self.log.exception("Error setting avatar")
  614. self.avatar_set = False
  615. await self.update_bridge_info()
  616. await self.update()
  617. async def update_puppet_name(self, name: str) -> None:
  618. if not self.encrypted and not self.private_chat_portal_meta:
  619. return
  620. changed = await self._update_name(name)
  621. if changed:
  622. await self.update_bridge_info()
  623. await self.update()
  624. async def _update_name(self, name: str, sender: Optional['p.Puppet'] = None) -> bool:
  625. if self.name != name or not self.name_set:
  626. self.name = name
  627. if self.mxid:
  628. try:
  629. await self._try_with_puppet(lambda i: i.set_room_name(self.mxid, self.name),
  630. puppet=sender)
  631. self.name_set = True
  632. except Exception:
  633. self.log.exception("Error setting name")
  634. self.name_set = False
  635. return True
  636. return False
  637. async def _try_with_puppet(self, action: Callable[[IntentAPI], Awaitable[Any]],
  638. puppet: Optional['p.Puppet'] = None) -> None:
  639. if puppet:
  640. try:
  641. await action(puppet.intent_for(self))
  642. except (MForbidden, IntentError):
  643. await action(self.main_intent)
  644. else:
  645. await action(self.main_intent)
  646. async def _update_avatar(self, info: ChatInfo, sender: Optional['p.Puppet'] = None) -> bool:
  647. path = None
  648. if isinstance(info, GroupV2):
  649. path = info.avatar
  650. elif isinstance(info, Group):
  651. path = f"group-{self.chat_id}"
  652. res = await p.Puppet.upload_avatar(self, path, self.main_intent)
  653. if res is False:
  654. return False
  655. self.avatar_hash, self.avatar_url = res
  656. if not self.mxid:
  657. return True
  658. try:
  659. await self._try_with_puppet(lambda i: i.set_room_avatar(self.mxid, self.avatar_url),
  660. puppet=sender)
  661. self.avatar_set = True
  662. except Exception:
  663. self.log.exception("Error setting avatar")
  664. self.avatar_set = False
  665. return True
  666. async def _update_participants(self, source: 'u.User', info: ChatInfo) -> None:
  667. if not self.mxid or not isinstance(info, (Group, GroupV2)):
  668. return
  669. pending_members = info.pending_members if isinstance(info, GroupV2) else []
  670. self._pending_members = {addr.uuid for addr in pending_members}
  671. for address in info.members:
  672. user = await u.User.get_by_address(address)
  673. if user:
  674. await self.main_intent.invite_user(self.mxid, user.mxid)
  675. puppet = await p.Puppet.get_by_address(address)
  676. if not puppet.name:
  677. await source.sync_contact(address)
  678. await puppet.intent_for(self).ensure_joined(self.mxid)
  679. for address in pending_members:
  680. user = await u.User.get_by_address(address)
  681. if user:
  682. await self.main_intent.invite_user(self.mxid, user.mxid)
  683. puppet = await p.Puppet.get_by_address(address)
  684. if not puppet.name:
  685. await source.sync_contact(address)
  686. await self.main_intent.invite_user(self.mxid, puppet.intent_for(self).mxid)
  687. async def _update_power_levels(self, info: ChatInfo) -> None:
  688. if not self.mxid:
  689. return
  690. power_levels = await self.main_intent.get_power_levels(self.mxid)
  691. power_levels = await self._get_power_levels(power_levels, info=info, is_initial=False)
  692. await self.main_intent.set_power_levels(self.mxid, power_levels)
  693. # endregion
  694. # region Bridge info state event
  695. @property
  696. def bridge_info_state_key(self) -> str:
  697. return f"net.maunium.signal://signal/{self.chat_id}"
  698. @property
  699. def bridge_info(self) -> Dict[str, Any]:
  700. return {
  701. "bridgebot": self.az.bot_mxid,
  702. "creator": self.main_intent.mxid,
  703. "protocol": {
  704. "id": "signal",
  705. "displayname": "Signal",
  706. "avatar_url": self.config["appservice.bot_avatar"],
  707. },
  708. "channel": {
  709. "id": str(self.chat_id),
  710. "displayname": self.name,
  711. "avatar_url": self.avatar_url,
  712. }
  713. }
  714. async def update_bridge_info(self) -> None:
  715. if not self.mxid:
  716. self.log.debug("Not updating bridge info: no Matrix room created")
  717. return
  718. try:
  719. self.log.debug("Updating bridge info...")
  720. await self.main_intent.send_state_event(self.mxid, StateBridge,
  721. self.bridge_info, self.bridge_info_state_key)
  722. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  723. await self.main_intent.send_state_event(self.mxid, StateHalfShotBridge,
  724. self.bridge_info, self.bridge_info_state_key)
  725. except Exception:
  726. self.log.warning("Failed to update bridge info", exc_info=True)
  727. # endregion
  728. # region Creating Matrix rooms
  729. async def update_matrix_room(self, source: 'u.User', info: ChatInfo) -> None:
  730. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  731. raise ValueError(f"Unexpected type for updating group portal: {type(info)}")
  732. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  733. raise ValueError(f"Unexpected type for updating direct chat portal: {type(info)}")
  734. try:
  735. await self._update_matrix_room(source, info)
  736. except Exception:
  737. self.log.exception("Failed to update portal")
  738. async def create_matrix_room(self, source: 'u.User', info: ChatInfo) -> Optional[RoomID]:
  739. if not self.is_direct and not isinstance(info, (Group, GroupV2, GroupV2ID)):
  740. raise ValueError(f"Unexpected type for creating group portal: {type(info)}")
  741. elif self.is_direct and not isinstance(info, (Contact, Profile, Address)):
  742. raise ValueError(f"Unexpected type for creating direct chat portal: {type(info)}")
  743. if isinstance(info, Group) and not info.members:
  744. groups = await self.signal.list_groups(source.username)
  745. info = next((g for g in groups
  746. if isinstance(g, Group) and g.group_id == info.group_id), info)
  747. elif isinstance(info, GroupV2ID) and not isinstance(info, GroupV2):
  748. self.log.debug(f"create_matrix_room() called with {info}, "
  749. "fetching full info from signald")
  750. info = await self.signal.get_group(source.username, info.id,
  751. info.revision or -1)
  752. if not info:
  753. self.log.warning(f"Full info not found, canceling room creation")
  754. return None
  755. else:
  756. self.log.trace("get_group() returned full info: %s", info)
  757. if self.mxid:
  758. await self.update_matrix_room(source, info)
  759. return self.mxid
  760. async with self._create_room_lock:
  761. return await self._create_matrix_room(source, info)
  762. async def _update_matrix_room(self, source: 'u.User', info: ChatInfo) -> None:
  763. if self.is_direct:
  764. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  765. if puppet:
  766. await self.main_intent.invite_user(self.mxid, source.mxid, check_cache=True)
  767. await puppet.intent.ensure_joined(self.mxid)
  768. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  769. await self.update_info(source, info)
  770. async def _get_power_levels(self, levels: Optional[PowerLevelStateEventContent] = None,
  771. info: Optional[ChatInfo] = None, is_initial: bool = False
  772. ) -> PowerLevelStateEventContent:
  773. levels = levels or PowerLevelStateEventContent()
  774. if self.is_direct:
  775. levels.ban = 99
  776. levels.kick = 99
  777. levels.invite = 99
  778. levels.state_default = 0
  779. meta_edit_level = 0
  780. else:
  781. if isinstance(info, GroupV2):
  782. ac = info.access_control
  783. for detail in info.member_detail + info.pending_member_detail:
  784. puppet = await p.Puppet.get_by_address(Address(uuid=detail.uuid))
  785. level = 50 if detail.role == GroupMemberRole.ADMINISTRATOR else 0
  786. levels.users[puppet.intent_for(self).mxid] = level
  787. else:
  788. ac = GroupAccessControl()
  789. levels.ban = 50
  790. levels.kick = 50
  791. levels.invite = 50 if ac.members == AccessControlMode.ADMINISTRATOR else 0
  792. levels.state_default = 50
  793. meta_edit_level = 50 if ac.attributes == AccessControlMode.ADMINISTRATOR else 0
  794. levels.events[EventType.ROOM_NAME] = meta_edit_level
  795. levels.events[EventType.ROOM_AVATAR] = meta_edit_level
  796. levels.events[EventType.ROOM_TOPIC] = meta_edit_level
  797. levels.events[EventType.ROOM_ENCRYPTION] = 50 if self.matrix.e2ee else 99
  798. levels.events[EventType.ROOM_TOMBSTONE] = 99
  799. levels.users_default = 0
  800. levels.events_default = 0
  801. # Remote delete is only for your own messages
  802. levels.redact = 99
  803. if self.main_intent.mxid not in levels.users:
  804. levels.users[self.main_intent.mxid] = 9001 if is_initial else 100
  805. return levels
  806. async def _create_matrix_room(self, source: 'u.User', info: ChatInfo) -> Optional[RoomID]:
  807. if self.mxid:
  808. await self._update_matrix_room(source, info)
  809. return self.mxid
  810. await self.update_info(source, info)
  811. self.log.debug("Creating Matrix room")
  812. name: Optional[str] = None
  813. power_levels = await self._get_power_levels(info=info, is_initial=True)
  814. initial_state = [{
  815. "type": str(StateBridge),
  816. "state_key": self.bridge_info_state_key,
  817. "content": self.bridge_info,
  818. }, {
  819. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  820. "type": str(StateHalfShotBridge),
  821. "state_key": self.bridge_info_state_key,
  822. "content": self.bridge_info,
  823. }, {
  824. "type": str(EventType.ROOM_POWER_LEVELS),
  825. "content": power_levels.serialize(),
  826. }]
  827. invites = [source.mxid]
  828. if self.config["bridge.encryption.default"] and self.matrix.e2ee:
  829. self.encrypted = True
  830. initial_state.append({
  831. "type": str(EventType.ROOM_ENCRYPTION),
  832. "content": {"algorithm": "m.megolm.v1.aes-sha2"},
  833. })
  834. if self.is_direct:
  835. invites.append(self.az.bot_mxid)
  836. if self.is_direct and source.address == self.chat_id:
  837. name = self.name = "Signal Note to Self"
  838. elif self.encrypted or self.private_chat_portal_meta or not self.is_direct:
  839. name = self.name
  840. if self.avatar_url:
  841. initial_state.append({
  842. "type": str(EventType.ROOM_AVATAR),
  843. "content": {"url": self.avatar_url},
  844. })
  845. if self.config["appservice.community_id"]:
  846. initial_state.append({
  847. "type": "m.room.related_groups",
  848. "content": {"groups": [self.config["appservice.community_id"]]},
  849. })
  850. self.mxid = await self.main_intent.create_room(name=name, is_direct=self.is_direct,
  851. initial_state=initial_state,
  852. invitees=invites)
  853. if not self.mxid:
  854. raise Exception("Failed to create room: no mxid returned")
  855. self.name_set = bool(name)
  856. self.avatar_set = bool(self.avatar_url)
  857. if self.encrypted and self.matrix.e2ee and self.is_direct:
  858. try:
  859. await self.az.intent.ensure_joined(self.mxid)
  860. except Exception:
  861. self.log.warning("Failed to add bridge bot "
  862. f"to new private chat {self.mxid}")
  863. await self.update()
  864. self.log.debug(f"Matrix room created: {self.mxid}")
  865. self.by_mxid[self.mxid] = self
  866. if not self.is_direct:
  867. await self._update_participants(source, info)
  868. else:
  869. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  870. if puppet:
  871. try:
  872. await puppet.intent.join_room_by_id(self.mxid)
  873. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  874. except MatrixError:
  875. self.log.debug("Failed to join custom puppet into newly created portal",
  876. exc_info=True)
  877. # TODO
  878. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  879. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  880. # in_community=in_community).upsert()
  881. return self.mxid
  882. # endregion
  883. # region Database getters
  884. async def _postinit(self) -> None:
  885. self.by_chat_id[(self.chat_id, self.receiver)] = self
  886. if self.mxid:
  887. self.by_mxid[self.mxid] = self
  888. if self.is_direct:
  889. puppet = await p.Puppet.get_by_address(self.chat_id)
  890. self._main_intent = puppet.default_mxid_intent
  891. elif not self.is_direct:
  892. self._main_intent = self.az.intent
  893. async def delete(self) -> None:
  894. await DBMessage.delete_all(self.mxid)
  895. self.by_mxid.pop(self.mxid, None)
  896. self.mxid = None
  897. self.encrypted = False
  898. await self.update()
  899. async def save(self) -> None:
  900. await self.update()
  901. @classmethod
  902. def all_with_room(cls) -> AsyncGenerator['Portal', None]:
  903. return cls._db_to_portals(super().all_with_room())
  904. @classmethod
  905. def find_private_chats_with(cls, other_user: Address) -> AsyncGenerator['Portal', None]:
  906. return cls._db_to_portals(super().find_private_chats_with(other_user))
  907. @classmethod
  908. async def _db_to_portals(cls, query: Awaitable[List['Portal']]
  909. ) -> AsyncGenerator['Portal', None]:
  910. portals = await query
  911. for index, portal in enumerate(portals):
  912. try:
  913. yield cls.by_chat_id[(portal.chat_id_str, portal.receiver)]
  914. except KeyError:
  915. await portal._postinit()
  916. yield portal
  917. @classmethod
  918. @async_getter_lock
  919. async def get_by_mxid(cls, mxid: RoomID) -> Optional['Portal']:
  920. try:
  921. return cls.by_mxid[mxid]
  922. except KeyError:
  923. pass
  924. portal = cast(cls, await super().get_by_mxid(mxid))
  925. if portal is not None:
  926. await portal._postinit()
  927. return portal
  928. return None
  929. @classmethod
  930. @async_getter_lock
  931. async def get_by_chat_id(cls, chat_id: Union[GroupID, Address], *, receiver: str = "",
  932. create: bool = False) -> Optional['Portal']:
  933. if isinstance(chat_id, str):
  934. receiver = ""
  935. elif not isinstance(chat_id, Address):
  936. raise ValueError(f"Invalid chat ID type {type(chat_id)}")
  937. elif not receiver:
  938. raise ValueError("Direct chats must have a receiver")
  939. try:
  940. best_id = chat_id.best_identifier if isinstance(chat_id, Address) else chat_id
  941. return cls.by_chat_id[(best_id, receiver)]
  942. except KeyError:
  943. pass
  944. portal = cast(cls, await super().get_by_chat_id(chat_id, receiver))
  945. if portal is not None:
  946. await portal._postinit()
  947. return portal
  948. if create:
  949. portal = cls(chat_id, receiver)
  950. await portal.insert()
  951. await portal._postinit()
  952. return portal
  953. return None
  954. # endregion