user.py 11 KB

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