user.py 11 KB

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