user.py 16 KB

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