portal.py 48 KB

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