user.py 13 KB

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