user.py 14 KB

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