user.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. # mautrix-signal - A Matrix-Signal puppeting bridge
  2. # Copyright (C) 2021 Tulir Asokan
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from __future__ import annotations
  17. from typing import TYPE_CHECKING, AsyncGenerator, cast
  18. from asyncio.tasks import sleep
  19. from datetime import datetime
  20. from uuid import UUID
  21. import asyncio
  22. from mausignald.errors import AuthorizationFailedError, ProfileUnavailableError
  23. from mausignald.types import (
  24. Account,
  25. Address,
  26. GroupV2,
  27. MessageResendSuccessEvent,
  28. Profile,
  29. WebsocketConnectionState,
  30. WebsocketConnectionStateChangeEvent,
  31. )
  32. from mautrix.appservice import AppService
  33. from mautrix.bridge import AutologinError, BaseUser, async_getter_lock
  34. from mautrix.types import EventType, RoomID, UserID
  35. from mautrix.util.bridge_state import BridgeState, BridgeStateEvent
  36. from mautrix.util.message_send_checkpoint import MessageSendCheckpointStatus
  37. from mautrix.util.opt_prometheus import Gauge
  38. from . import portal as po, puppet as pu
  39. from .config import Config
  40. from .db import Message as DBMessage, User as DBUser
  41. if TYPE_CHECKING:
  42. from .__main__ import SignalBridge
  43. METRIC_CONNECTED = Gauge("bridge_connected", "Bridge users connected to Signal")
  44. METRIC_LOGGED_IN = Gauge("bridge_logged_in", "Bridge users logged into Signal")
  45. BridgeState.human_readable_errors.update(
  46. {
  47. "logged-out": "You're not logged into Signal",
  48. "signal-not-connected": None,
  49. }
  50. )
  51. class User(DBUser, BaseUser):
  52. by_mxid: dict[UserID, User] = {}
  53. by_username: dict[str, User] = {}
  54. by_uuid: dict[UUID, User] = {}
  55. config: Config
  56. az: AppService
  57. loop: asyncio.AbstractEventLoop
  58. bridge: "SignalBridge"
  59. relay_whitelisted: bool
  60. is_admin: bool
  61. permission_level: str
  62. _sync_lock: asyncio.Lock
  63. _notice_room_lock: asyncio.Lock
  64. _connected: bool
  65. _websocket_connection_state: BridgeStateEvent | None
  66. _latest_non_transient_bridge_state: datetime | None
  67. def __init__(
  68. self,
  69. mxid: UserID,
  70. username: str | None = None,
  71. uuid: UUID | None = None,
  72. notice_room: RoomID | None = None,
  73. ) -> None:
  74. super().__init__(mxid=mxid, username=username, uuid=uuid, notice_room=notice_room)
  75. BaseUser.__init__(self)
  76. self._notice_room_lock = asyncio.Lock()
  77. self._sync_lock = asyncio.Lock()
  78. self._connected = False
  79. self._websocket_connection_state = None
  80. perms = self.config.get_permissions(mxid)
  81. self.relay_whitelisted, self.is_whitelisted, self.is_admin, self.permission_level = perms
  82. @classmethod
  83. def init_cls(cls, bridge: "SignalBridge") -> None:
  84. cls.bridge = bridge
  85. cls.config = bridge.config
  86. cls.az = bridge.az
  87. cls.loop = bridge.loop
  88. @property
  89. def address(self) -> Address | None:
  90. if not self.username:
  91. return None
  92. return Address(uuid=self.uuid, number=self.username)
  93. async def is_logged_in(self) -> bool:
  94. return bool(self.username)
  95. async def needs_relay(self, portal: po.Portal) -> bool:
  96. return not await self.is_logged_in() or (
  97. portal.is_direct and portal.receiver != self.username
  98. )
  99. async def logout(self) -> None:
  100. if not self.username:
  101. return
  102. username = self.username
  103. if self.uuid and self.by_uuid.get(self.uuid) == self:
  104. del self.by_uuid[self.uuid]
  105. if self.username and self.by_username.get(self.username) == self:
  106. del self.by_username[self.username]
  107. self.username = None
  108. self.uuid = None
  109. await self.update()
  110. await self.bridge.signal.unsubscribe(username)
  111. # Wait a while for signald to finish disconnecting
  112. await asyncio.sleep(1)
  113. await self.bridge.signal.delete_account(username)
  114. self._track_metric(METRIC_LOGGED_IN, False)
  115. await self.push_bridge_state(BridgeStateEvent.LOGGED_OUT, remote_id=username)
  116. async def fill_bridge_state(self, state: BridgeState) -> None:
  117. await super().fill_bridge_state(state)
  118. if not state.remote_id:
  119. state.remote_id = self.username
  120. if self.address:
  121. puppet = await self.get_puppet()
  122. state.remote_name = puppet.name or self.username
  123. async def get_bridge_states(self) -> list[BridgeState]:
  124. if not self.username:
  125. return []
  126. state = BridgeState(state_event=BridgeStateEvent.UNKNOWN_ERROR)
  127. if self.bridge.signal.is_connected and self._connected:
  128. state.state_event = BridgeStateEvent.CONNECTED
  129. else:
  130. state.state_event = BridgeStateEvent.TRANSIENT_DISCONNECT
  131. return [state]
  132. async def handle_auth_failure(self, e: Exception) -> None:
  133. if isinstance(e, AuthorizationFailedError):
  134. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=str(e))
  135. async def get_puppet(self) -> pu.Puppet | None:
  136. if not self.address:
  137. return None
  138. return await pu.Puppet.get_by_address(self.address)
  139. async def get_portal_with(self, puppet: pu.Puppet, create: bool = True) -> po.Portal | None:
  140. if not self.username:
  141. return None
  142. return await po.Portal.get_by_chat_id(puppet.uuid, receiver=self.username, create=create)
  143. async def on_signin(self, account: Account) -> None:
  144. self.username = account.account_id
  145. self.uuid = account.address.uuid
  146. self._add_to_cache()
  147. await self.update()
  148. await self.bridge.signal.subscribe(self.username)
  149. asyncio.create_task(self.sync())
  150. self._track_metric(METRIC_LOGGED_IN, True)
  151. def on_websocket_connection_state_change(
  152. self, evt: WebsocketConnectionStateChangeEvent
  153. ) -> None:
  154. if evt.state == WebsocketConnectionState.CONNECTED:
  155. self.log.info(f"Connected to Signal (ws: {evt.socket})")
  156. self._track_metric(METRIC_CONNECTED, True)
  157. self._track_metric(METRIC_LOGGED_IN, True)
  158. self._connected = True
  159. else:
  160. if evt.exception:
  161. self.log.error(
  162. f"New {evt.socket} websocket state from signald {evt.state} "
  163. f"with error {evt.exception}"
  164. )
  165. else:
  166. self.log.warning(f"New {evt.socket} websocket state from signald {evt.state}")
  167. self._track_metric(METRIC_CONNECTED, False)
  168. self._connected = False
  169. bridge_state = {
  170. # Signald disconnected
  171. WebsocketConnectionState.SOCKET_DISCONNECTED: BridgeStateEvent.TRANSIENT_DISCONNECT,
  172. # Websocket state reported by signald
  173. WebsocketConnectionState.DISCONNECTED: (
  174. None
  175. if self._websocket_connection_state == BridgeStateEvent.BAD_CREDENTIALS
  176. else BridgeStateEvent.TRANSIENT_DISCONNECT
  177. ),
  178. WebsocketConnectionState.CONNECTING: BridgeStateEvent.CONNECTING,
  179. WebsocketConnectionState.CONNECTED: BridgeStateEvent.CONNECTED,
  180. WebsocketConnectionState.RECONNECTING: BridgeStateEvent.TRANSIENT_DISCONNECT,
  181. WebsocketConnectionState.DISCONNECTING: BridgeStateEvent.TRANSIENT_DISCONNECT,
  182. WebsocketConnectionState.AUTHENTICATION_FAILED: BridgeStateEvent.BAD_CREDENTIALS,
  183. WebsocketConnectionState.FAILED: BridgeStateEvent.TRANSIENT_DISCONNECT,
  184. }.get(evt.state)
  185. if bridge_state is None:
  186. self.log.info(f"Websocket state {evt.state} seen, not reporting new bridge state")
  187. return
  188. now = datetime.now()
  189. if bridge_state in (BridgeStateEvent.TRANSIENT_DISCONNECT, BridgeStateEvent.CONNECTING):
  190. self.log.debug(
  191. f"New bridge state {bridge_state} is likely transient. Waiting 15 seconds to send."
  192. )
  193. async def wait_report_bridge_state():
  194. # Wait for 15 seconds (that should be enough for the bridge to get connected)
  195. # before sending a TRANSIENT_DISCONNECT/CONNECTING.
  196. await sleep(15)
  197. if (
  198. self._latest_non_transient_bridge_state
  199. and now > self._latest_non_transient_bridge_state
  200. ):
  201. asyncio.create_task(self.push_bridge_state(bridge_state))
  202. self._websocket_connection_state = bridge_state
  203. # Wait for another minute. If the bridge stays in TRANSIENT_DISCONNECT/CONNECTING
  204. # for that long, something terrible has happened (signald failed to restart, the
  205. # internet broke, etc.)
  206. await sleep(60)
  207. if (
  208. self._latest_non_transient_bridge_state
  209. and now > self._latest_non_transient_bridge_state
  210. ):
  211. asyncio.create_task(
  212. self.push_bridge_state(
  213. BridgeStateEvent.UNKNOWN_ERROR,
  214. message="Failed to restore connection to Signal",
  215. )
  216. )
  217. self._websocket_connection_state = BridgeStateEvent.UNKNOWN_ERROR
  218. else:
  219. self.log.info(
  220. f"New state since last {bridge_state} push, "
  221. "not transitioning to UNKNOWN_ERROR."
  222. )
  223. asyncio.create_task(wait_report_bridge_state())
  224. elif self._websocket_connection_state == bridge_state:
  225. self.log.info("Websocket state unchanged, not reporting new bridge state")
  226. self._latest_non_transient_bridge_state = now
  227. else:
  228. asyncio.create_task(self.push_bridge_state(bridge_state))
  229. self._latest_non_transient_bridge_state = now
  230. self._websocket_connection_state = bridge_state
  231. async def on_message_resend_success(self, evt: MessageResendSuccessEvent):
  232. # These messages mean we need to resend the message to that user.
  233. my_uuid = self.address.uuid
  234. self.log.debug(f"Successfully resent message {my_uuid}/{evt.timestamp}")
  235. message = await DBMessage.find_by_sender_timestamp(my_uuid, evt.timestamp)
  236. if not message:
  237. self.log.warning("Couldn't find message that was resent")
  238. return
  239. self.log.debug(f"Successfully resent {message.mxid} in {message.mx_room}")
  240. self.send_remote_checkpoint(
  241. status=MessageSendCheckpointStatus.SUCCESS,
  242. event_id=message.mxid,
  243. room_id=message.mx_room,
  244. event_type=EventType.ROOM_MESSAGE,
  245. )
  246. async def _sync_puppet(self) -> None:
  247. puppet = await self.get_puppet()
  248. if not puppet:
  249. self.log.warning(f"Didn't find puppet for own address {self.address}")
  250. return
  251. if puppet.uuid and not self.uuid:
  252. self.uuid = puppet.uuid
  253. self.by_uuid[self.uuid] = self
  254. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  255. self.log.info("Automatically enabling custom puppet")
  256. try:
  257. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  258. except AutologinError as e:
  259. self.log.warning(f"Failed to enable custom puppet: {e}")
  260. async def sync(self) -> None:
  261. await self.sync_puppet()
  262. await self.sync_contacts()
  263. await self.sync_groups()
  264. self.log.debug("Sync complete")
  265. async def sync_puppet(self) -> None:
  266. try:
  267. async with self._sync_lock:
  268. await self._sync_puppet()
  269. except Exception:
  270. self.log.exception("Error while syncing own puppet")
  271. async def sync_contacts(self) -> None:
  272. try:
  273. async with self._sync_lock:
  274. await self._sync_contacts()
  275. except Exception as e:
  276. self.log.exception("Error while syncing contacts")
  277. await self.handle_auth_failure(e)
  278. async def sync_groups(self) -> None:
  279. try:
  280. async with self._sync_lock:
  281. await self._sync_groups()
  282. except Exception as e:
  283. self.log.exception("Error while syncing groups")
  284. await self.handle_auth_failure(e)
  285. async def sync_contact(
  286. self, contact: Profile | Address, create_portals: bool = False, use_cache: bool = True
  287. ) -> None:
  288. self.log.trace("Syncing contact %s", contact)
  289. try:
  290. if isinstance(contact, Address):
  291. address = contact
  292. try:
  293. profile = await self.bridge.signal.get_profile(
  294. self.username, address, use_cache=use_cache
  295. )
  296. except ProfileUnavailableError:
  297. self.log.debug(f"Profile of {address} was not available when syncing")
  298. profile = None
  299. if profile and profile.name:
  300. self.log.trace("Got profile for %s: %s", address, profile)
  301. else:
  302. address = contact.address
  303. profile = contact
  304. puppet = await pu.Puppet.get_by_address(address, resolve_via=self.username)
  305. if not puppet:
  306. self.log.debug(f"Didn't find puppet for {address} while syncing contact")
  307. return
  308. await puppet.update_info(profile or address, self)
  309. if create_portals:
  310. portal = await po.Portal.get_by_chat_id(
  311. puppet.uuid, receiver=self.username, create=True
  312. )
  313. await portal.create_matrix_room(self, profile or address)
  314. except Exception as e:
  315. await self.handle_auth_failure(e)
  316. raise
  317. async def _sync_group_v2(self, group: GroupV2, create_portals: bool) -> None:
  318. self.log.trace("Syncing group %s", group.id)
  319. portal = await po.Portal.get_by_chat_id(group.id, create=True)
  320. if create_portals:
  321. await portal.create_matrix_room(self, group)
  322. elif portal.mxid:
  323. await portal.update_matrix_room(self, group)
  324. async def _sync_contacts(self) -> None:
  325. create_contact_portal = self.config["bridge.autocreate_contact_portal"]
  326. for contact in await self.bridge.signal.list_contacts(self.username):
  327. try:
  328. await self.sync_contact(contact, create_contact_portal)
  329. except Exception:
  330. self.log.exception(f"Failed to sync contact {contact.address}")
  331. async def _sync_groups(self) -> None:
  332. create_group_portal = self.config["bridge.autocreate_group_portal"]
  333. for group in await self.bridge.signal.list_groups(self.username):
  334. try:
  335. await self._sync_group_v2(group, create_group_portal)
  336. except Exception:
  337. self.log.exception(f"Failed to sync group {group.id}")
  338. # region Database getters
  339. def _add_to_cache(self) -> None:
  340. self.by_mxid[self.mxid] = self
  341. if self.username:
  342. self.by_username[self.username] = self
  343. if self.uuid:
  344. self.by_uuid[self.uuid] = self
  345. @classmethod
  346. @async_getter_lock
  347. async def get_by_mxid(cls, mxid: UserID, /, *, create: bool = True) -> User | None:
  348. # Never allow ghosts to be users
  349. if pu.Puppet.get_id_from_mxid(mxid):
  350. return None
  351. try:
  352. return cls.by_mxid[mxid]
  353. except KeyError:
  354. pass
  355. user = cast(cls, await super().get_by_mxid(mxid))
  356. if user is not None:
  357. user._add_to_cache()
  358. return user
  359. if create:
  360. user = cls(mxid)
  361. await user.insert()
  362. user._add_to_cache()
  363. return user
  364. return None
  365. @classmethod
  366. @async_getter_lock
  367. async def get_by_username(cls, username: str, /) -> User | None:
  368. try:
  369. return cls.by_username[username]
  370. except KeyError:
  371. pass
  372. user = cast(cls, await super().get_by_username(username))
  373. if user is not None:
  374. user._add_to_cache()
  375. return user
  376. return None
  377. @classmethod
  378. @async_getter_lock
  379. async def get_by_uuid(cls, uuid: UUID, /) -> User | None:
  380. try:
  381. return cls.by_uuid[uuid]
  382. except KeyError:
  383. pass
  384. user = cast(cls, await super().get_by_uuid(uuid))
  385. if user is not None:
  386. user._add_to_cache()
  387. return user
  388. return None
  389. @classmethod
  390. async def get_by_address(cls, address: Address) -> User | None:
  391. if address.uuid:
  392. return await cls.get_by_uuid(address.uuid)
  393. elif address.number:
  394. return await cls.get_by_username(address.number)
  395. else:
  396. raise ValueError("Given address is blank")
  397. @classmethod
  398. async def all_logged_in(cls) -> AsyncGenerator[User, None]:
  399. users = await super().all_logged_in()
  400. user: cls
  401. for user in users:
  402. try:
  403. yield cls.by_mxid[user.mxid]
  404. except KeyError:
  405. user._add_to_cache()
  406. yield user
  407. # endregion