user.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 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, Contact, Group, GroupV2, ListenEvent, ListenAction
  23. from mautrix.bridge import BaseUser
  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. class User(DBUser, BaseUser):
  34. by_mxid: Dict[UserID, 'User'] = {}
  35. by_username: Dict[str, 'User'] = {}
  36. config: Config
  37. az: AppService
  38. loop: asyncio.AbstractEventLoop
  39. bridge: 'SignalBridge'
  40. is_admin: bool
  41. permission_level: str
  42. _notice_room_lock: asyncio.Lock
  43. def __init__(self, mxid: UserID, username: Optional[str] = None, uuid: Optional[UUID] = None,
  44. notice_room: Optional[RoomID] = None) -> None:
  45. super().__init__(mxid=mxid, username=username, uuid=uuid, notice_room=notice_room)
  46. self._notice_room_lock = asyncio.Lock()
  47. perms = self.config.get_permissions(mxid)
  48. self.is_whitelisted, self.is_admin, self.permission_level = perms
  49. self.log = self.log.getChild(self.mxid)
  50. self.dm_update_lock = asyncio.Lock()
  51. self.command_status = None
  52. self._metric_value = defaultdict(lambda: False)
  53. @classmethod
  54. def init_cls(cls, bridge: 'SignalBridge') -> None:
  55. cls.bridge = bridge
  56. cls.config = bridge.config
  57. cls.az = bridge.az
  58. cls.loop = bridge.loop
  59. @property
  60. def address(self) -> Optional[Address]:
  61. if not self.username:
  62. return None
  63. return Address(uuid=self.uuid, number=self.username)
  64. async def is_logged_in(self) -> bool:
  65. return bool(self.username)
  66. async def logout(self) -> None:
  67. if not self.username:
  68. return
  69. username = self.username
  70. self.username = None
  71. self.uuid = None
  72. await self.update()
  73. await self.bridge.signal.unsubscribe(username)
  74. # Wait a while for signald to finish disconnecting
  75. await asyncio.sleep(1)
  76. path = os.path.join(self.config["signal.data_dir"], username)
  77. extra_dir = f"{path}.d/"
  78. try:
  79. self.log.debug("Removing %s", path)
  80. os.remove(path)
  81. except FileNotFoundError as e:
  82. self.log.warning(f"Failed to remove signald data file: {e}")
  83. self.log.debug("Removing %s", extra_dir)
  84. shutil.rmtree(extra_dir, ignore_errors=True)
  85. async def on_signin(self, account: Account) -> None:
  86. self.username = account.username
  87. self.uuid = account.uuid
  88. await self.update()
  89. await self.bridge.signal.subscribe(self.username)
  90. self.loop.create_task(self.sync())
  91. def on_listen(self, evt: ListenEvent) -> None:
  92. if evt.action == ListenAction.STARTED:
  93. self.log.info("Connected to Signal")
  94. self._track_metric(METRIC_CONNECTED, True)
  95. elif evt.action == ListenAction.STOPPED:
  96. if evt.exception:
  97. self.log.warning(f"Disconnected from Signal: {evt.exception}")
  98. else:
  99. self.log.info("Disconnected from Signal")
  100. self._track_metric(METRIC_CONNECTED, False)
  101. else:
  102. self.log.warning(f"Unrecognized listen action {evt.action}")
  103. async def _sync_puppet(self) -> None:
  104. puppet = await pu.Puppet.get_by_address(self.address)
  105. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  106. self.log.info(f"Automatically enabling custom puppet")
  107. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  108. async def sync(self) -> None:
  109. try:
  110. await self._sync_puppet()
  111. except Exception:
  112. self.log.exception("Error while syncing own puppet")
  113. try:
  114. await self._sync()
  115. except Exception:
  116. self.log.exception("Error while syncing")
  117. async def _sync_contact(self, contact: Contact, create_portals: bool) -> None:
  118. self.log.trace("Syncing contact %s", contact)
  119. puppet = await pu.Puppet.get_by_address(contact.address)
  120. if not puppet.name:
  121. profile = await self.bridge.signal.get_profile(self.username, contact.address)
  122. if profile and profile.name:
  123. self.log.trace("Got profile for %s: %s", contact.address, profile)
  124. else:
  125. profile = None
  126. else:
  127. # get_profile probably does a request to the servers, so let's not do that unless
  128. # necessary, but maybe we could listen for updates?
  129. profile = None
  130. await puppet.update_info(profile or contact)
  131. if create_portals:
  132. portal = await po.Portal.get_by_chat_id(puppet.address, self.username, create=True)
  133. await portal.create_matrix_room(self, profile or contact)
  134. async def _sync_group(self, group: Group, create_portals: bool) -> None:
  135. self.log.trace("Syncing group %s", group)
  136. portal = await po.Portal.get_by_chat_id(group.group_id, create=True)
  137. if create_portals:
  138. await portal.create_matrix_room(self, group)
  139. elif portal.mxid:
  140. await portal.update_matrix_room(self, group)
  141. async def _sync_group_v2(self, group: GroupV2, create_portals: bool) -> None:
  142. self.log.trace("Syncing group %s", group.id)
  143. portal = await po.Portal.get_by_chat_id(group.id, create=True)
  144. if create_portals:
  145. await portal.create_matrix_room(self, group)
  146. elif portal.mxid:
  147. await portal.update_matrix_room(self, group)
  148. async def _sync(self) -> None:
  149. create_contact_portal = self.config["bridge.autocreate_contact_portal"]
  150. for contact in await self.bridge.signal.list_contacts(self.username):
  151. try:
  152. await self._sync_contact(contact, create_contact_portal)
  153. except Exception:
  154. self.log.exception(f"Failed to sync contact {contact.address}")
  155. create_group_portal = self.config["bridge.autocreate_group_portal"]
  156. for group in await self.bridge.signal.list_groups(self.username):
  157. try:
  158. if isinstance(group, Group):
  159. await self._sync_group(group, create_group_portal)
  160. elif isinstance(group, GroupV2):
  161. await self._sync_group_v2(group, create_group_portal)
  162. else:
  163. self.log.warning("Unknown return type in list_groups: %s", type(group))
  164. except Exception:
  165. self.log.exception(f"Failed to sync group {group.group_id}")
  166. # region Database getters
  167. def _add_to_cache(self) -> None:
  168. self.by_mxid[self.mxid] = self
  169. if self.username:
  170. self.by_username[self.username] = self
  171. @classmethod
  172. async def get_by_mxid(cls, mxid: UserID, create: bool = True) -> Optional['User']:
  173. # Never allow ghosts to be users
  174. if pu.Puppet.get_id_from_mxid(mxid):
  175. return None
  176. try:
  177. return cls.by_mxid[mxid]
  178. except KeyError:
  179. pass
  180. user = cast(cls, await super().get_by_mxid(mxid))
  181. if user is not None:
  182. user._add_to_cache()
  183. return user
  184. if create:
  185. user = cls(mxid)
  186. await user.insert()
  187. user._add_to_cache()
  188. return user
  189. return None
  190. @classmethod
  191. async def get_by_username(cls, username: str) -> Optional['User']:
  192. try:
  193. return cls.by_username[username]
  194. except KeyError:
  195. pass
  196. user = cast(cls, await super().get_by_username(username))
  197. if user is not None:
  198. user._add_to_cache()
  199. return user
  200. return None
  201. @classmethod
  202. async def all_logged_in(cls) -> AsyncGenerator['User', None]:
  203. users = await super().all_logged_in()
  204. user: cls
  205. for user in users:
  206. try:
  207. yield cls.by_mxid[user.mxid]
  208. except KeyError:
  209. user._add_to_cache()
  210. yield user
  211. # endregion