user.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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.types import (
  23. Account,
  24. Address,
  25. Group,
  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 get_puppet(self) -> pu.Puppet | None:
  131. if not self.address:
  132. return None
  133. return await pu.Puppet.get_by_address(self.address)
  134. async def on_signin(self, account: Account) -> None:
  135. self.username = account.account_id
  136. self.uuid = account.address.uuid
  137. self._add_to_cache()
  138. # Push a remote state immediately so that the client knows that it's doing something.
  139. asyncio.create_task(self.push_bridge_state(BridgeStateEvent.CONNECTING))
  140. await self.update()
  141. await self.bridge.signal.subscribe(self.username)
  142. asyncio.create_task(self.sync())
  143. self._track_metric(METRIC_LOGGED_IN, True)
  144. def on_websocket_connection_state_change(
  145. self, evt: WebsocketConnectionStateChangeEvent
  146. ) -> None:
  147. if evt.state == WebsocketConnectionState.CONNECTED:
  148. self.log.info("Connected to Signal")
  149. self._track_metric(METRIC_CONNECTED, True)
  150. self._track_metric(METRIC_LOGGED_IN, True)
  151. self._connected = True
  152. else:
  153. self.log.warning(
  154. f"New websocket state from signald: {evt.state}. Error: {evt.exception}"
  155. )
  156. self._track_metric(METRIC_CONNECTED, False)
  157. self._connected = False
  158. bridge_state = {
  159. # Signald disconnected
  160. WebsocketConnectionState.SOCKET_DISCONNECTED: BridgeStateEvent.TRANSIENT_DISCONNECT,
  161. # Websocket state reported by signald
  162. WebsocketConnectionState.DISCONNECTED: (
  163. None
  164. if self._websocket_connection_state == BridgeStateEvent.BAD_CREDENTIALS
  165. else BridgeStateEvent.TRANSIENT_DISCONNECT
  166. ),
  167. WebsocketConnectionState.CONNECTING: BridgeStateEvent.CONNECTING,
  168. WebsocketConnectionState.CONNECTED: BridgeStateEvent.CONNECTED,
  169. WebsocketConnectionState.RECONNECTING: BridgeStateEvent.TRANSIENT_DISCONNECT,
  170. WebsocketConnectionState.DISCONNECTING: BridgeStateEvent.TRANSIENT_DISCONNECT,
  171. WebsocketConnectionState.AUTHENTICATION_FAILED: BridgeStateEvent.BAD_CREDENTIALS,
  172. WebsocketConnectionState.FAILED: BridgeStateEvent.TRANSIENT_DISCONNECT,
  173. }.get(evt.state)
  174. if bridge_state is None:
  175. self.log.info(f"Websocket state {evt.state} seen. Will not report new Bridge State")
  176. return
  177. now = datetime.now()
  178. if bridge_state == BridgeStateEvent.TRANSIENT_DISCONNECT:
  179. async def wait_report_transient_disconnect():
  180. # Wait for 10 seconds (that should be enough for the bridge to get connected)
  181. # before sending a TRANSIENT_DISCONNECT.
  182. # self._latest_non_transient_disconnect_state will only be None if the bridge is
  183. # still starting.
  184. if self._latest_non_transient_disconnect_state is None:
  185. await sleep(15)
  186. if self._latest_non_transient_disconnect_state is None:
  187. asyncio.create_task(self.push_bridge_state(bridge_state))
  188. # Wait for another minute. If the bridge stays in TRANSIENT_DISCONNECT for that
  189. # long, something terrible has happened (signald failed to restart, the internet
  190. # broke, etc.)
  191. await sleep(60)
  192. if (
  193. self._latest_non_transient_disconnect_state
  194. and now > self._latest_non_transient_disconnect_state
  195. ):
  196. asyncio.create_task(
  197. self.push_bridge_state(
  198. BridgeStateEvent.UNKNOWN_ERROR,
  199. message="Failed restore connection to Signal",
  200. )
  201. )
  202. else:
  203. self.log.info(
  204. "New state since last TRANSIENT_DISCONNECT push. "
  205. "Not transitioning to UNKNOWN_ERROR."
  206. )
  207. asyncio.create_task(wait_report_transient_disconnect())
  208. else:
  209. asyncio.create_task(self.push_bridge_state(bridge_state))
  210. self._latest_non_transient_disconnect_state = now
  211. self._websocket_connection_state = bridge_state
  212. async def _sync_puppet(self) -> None:
  213. puppet = await pu.Puppet.get_by_address(self.address)
  214. if puppet.uuid and not self.uuid:
  215. self.uuid = puppet.uuid
  216. self.by_uuid[self.uuid] = self
  217. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  218. self.log.info("Automatically enabling custom puppet")
  219. try:
  220. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  221. except AutologinError as e:
  222. self.log.warning(f"Failed to enable custom puppet: {e}")
  223. async def sync(self) -> None:
  224. await self.sync_puppet()
  225. await self.sync_contacts()
  226. await self.sync_groups()
  227. async def sync_puppet(self) -> None:
  228. try:
  229. async with self._sync_lock:
  230. await self._sync_puppet()
  231. except Exception:
  232. self.log.exception("Error while syncing own puppet")
  233. async def sync_contacts(self) -> None:
  234. try:
  235. async with self._sync_lock:
  236. await self._sync_contacts()
  237. except Exception:
  238. self.log.exception("Error while syncing contacts")
  239. async def sync_groups(self) -> None:
  240. try:
  241. async with self._sync_lock:
  242. await self._sync_groups()
  243. except Exception:
  244. self.log.exception("Error while syncing groups")
  245. async def sync_contact(self, contact: Profile | Address, create_portals: bool = False) -> None:
  246. self.log.trace("Syncing contact %s", contact)
  247. if isinstance(contact, Address):
  248. address = contact
  249. profile = await self.bridge.signal.get_profile(self.username, address, use_cache=True)
  250. if profile and profile.name:
  251. self.log.trace("Got profile for %s: %s", address, profile)
  252. else:
  253. address = contact.address
  254. profile = contact
  255. puppet = await pu.Puppet.get_by_address(address)
  256. await puppet.update_info(profile)
  257. if create_portals:
  258. portal = await po.Portal.get_by_chat_id(
  259. puppet.address, receiver=self.username, create=True
  260. )
  261. await portal.create_matrix_room(self, profile)
  262. async def _sync_group(self, group: Group, create_portals: bool) -> None:
  263. self.log.trace("Syncing group %s", group)
  264. portal = await po.Portal.get_by_chat_id(group.group_id, create=True)
  265. if create_portals:
  266. await portal.create_matrix_room(self, group)
  267. elif portal.mxid:
  268. await portal.update_matrix_room(self, group)
  269. async def _sync_group_v2(self, group: GroupV2, create_portals: bool) -> None:
  270. self.log.trace("Syncing group %s", group.id)
  271. portal = await po.Portal.get_by_chat_id(group.id, create=True)
  272. if create_portals:
  273. await portal.create_matrix_room(self, group)
  274. elif portal.mxid:
  275. await portal.update_matrix_room(self, group)
  276. async def _sync_contacts(self) -> None:
  277. create_contact_portal = self.config["bridge.autocreate_contact_portal"]
  278. for contact in await self.bridge.signal.list_contacts(self.username):
  279. try:
  280. await self.sync_contact(contact, create_contact_portal)
  281. except Exception:
  282. self.log.exception(f"Failed to sync contact {contact.address}")
  283. async def _sync_groups(self) -> None:
  284. create_group_portal = self.config["bridge.autocreate_group_portal"]
  285. for group in await self.bridge.signal.list_groups(self.username):
  286. group_id = group.group_id if isinstance(group, Group) else group.id
  287. try:
  288. if isinstance(group, Group):
  289. await self._sync_group(group, create_group_portal)
  290. elif isinstance(group, GroupV2):
  291. await self._sync_group_v2(group, create_group_portal)
  292. else:
  293. self.log.warning("Unknown return type in list_groups: %s", type(group))
  294. except Exception:
  295. self.log.exception(f"Failed to sync group {group_id}")
  296. # region Database getters
  297. def _add_to_cache(self) -> None:
  298. self.by_mxid[self.mxid] = self
  299. if self.username:
  300. self.by_username[self.username] = self
  301. if self.uuid:
  302. self.by_uuid[self.uuid] = self
  303. @classmethod
  304. @async_getter_lock
  305. async def get_by_mxid(cls, mxid: UserID, create: bool = True) -> User | None:
  306. # Never allow ghosts to be users
  307. if pu.Puppet.get_id_from_mxid(mxid):
  308. return None
  309. try:
  310. return cls.by_mxid[mxid]
  311. except KeyError:
  312. pass
  313. user = cast(cls, await super().get_by_mxid(mxid))
  314. if user is not None:
  315. user._add_to_cache()
  316. return user
  317. if create:
  318. user = cls(mxid)
  319. await user.insert()
  320. user._add_to_cache()
  321. return user
  322. return None
  323. @classmethod
  324. @async_getter_lock
  325. async def get_by_username(cls, username: str) -> User | None:
  326. try:
  327. return cls.by_username[username]
  328. except KeyError:
  329. pass
  330. user = cast(cls, await super().get_by_username(username))
  331. if user is not None:
  332. user._add_to_cache()
  333. return user
  334. return None
  335. @classmethod
  336. @async_getter_lock
  337. async def get_by_uuid(cls, uuid: UUID) -> User | None:
  338. try:
  339. return cls.by_uuid[uuid]
  340. except KeyError:
  341. pass
  342. user = cast(cls, await super().get_by_uuid(uuid))
  343. if user is not None:
  344. user._add_to_cache()
  345. return user
  346. return None
  347. @classmethod
  348. async def get_by_address(cls, address: Address) -> User | None:
  349. if address.uuid:
  350. return await cls.get_by_uuid(address.uuid)
  351. elif address.number:
  352. return await cls.get_by_username(address.number)
  353. else:
  354. raise ValueError("Given address is blank")
  355. @classmethod
  356. async def all_logged_in(cls) -> AsyncGenerator[User, None]:
  357. users = await super().all_logged_in()
  358. user: cls
  359. for user in users:
  360. try:
  361. yield cls.by_mxid[user.mxid]
  362. except KeyError:
  363. user._add_to_cache()
  364. yield user
  365. # endregion