user.py 15 KB

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