user.py 16 KB

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