user.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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, 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_contacts()
  115. except Exception:
  116. self.log.exception("Error while syncing contacts")
  117. try:
  118. await self._sync_groups()
  119. except Exception:
  120. self.log.exception("Error while syncing groups")
  121. async def sync_contact(self, contact: Union[Contact, Address], create_portals: bool = False
  122. ) -> None:
  123. self.log.trace("Syncing contact %s", contact)
  124. address = contact.address if isinstance(contact, Contact) else contact
  125. puppet = await pu.Puppet.get_by_address(address)
  126. profile = await self.bridge.signal.get_profile(self.username, address)
  127. if profile and profile.name:
  128. self.log.trace("Got profile for %s: %s", address, profile)
  129. else:
  130. profile = None
  131. await puppet.update_info(profile or contact)
  132. if create_portals:
  133. portal = await po.Portal.get_by_chat_id(puppet.address, self.username, create=True)
  134. await portal.create_matrix_room(self, profile or contact)
  135. async def _sync_group(self, group: Group, create_portals: bool) -> None:
  136. self.log.trace("Syncing group %s", group)
  137. portal = await po.Portal.get_by_chat_id(group.group_id, create=True)
  138. if create_portals:
  139. await portal.create_matrix_room(self, group)
  140. elif portal.mxid:
  141. await portal.update_matrix_room(self, group)
  142. async def _sync_group_v2(self, group: GroupV2, create_portals: bool) -> None:
  143. self.log.trace("Syncing group %s", group.id)
  144. portal = await po.Portal.get_by_chat_id(group.id, create=True)
  145. if create_portals:
  146. await portal.create_matrix_room(self, group)
  147. elif portal.mxid:
  148. await portal.update_matrix_room(self, group)
  149. async def _sync_contacts(self) -> None:
  150. create_contact_portal = self.config["bridge.autocreate_contact_portal"]
  151. for contact in await self.bridge.signal.list_contacts(self.username):
  152. try:
  153. await self.sync_contact(contact, create_contact_portal)
  154. except Exception:
  155. self.log.exception(f"Failed to sync contact {contact.address}")
  156. async def _sync_groups(self) -> None:
  157. create_group_portal = self.config["bridge.autocreate_group_portal"]
  158. for group in await self.bridge.signal.list_groups(self.username):
  159. group_id = group.group_id if isinstance(group, Group) else group.id
  160. try:
  161. if isinstance(group, Group):
  162. await self._sync_group(group, create_group_portal)
  163. elif isinstance(group, GroupV2):
  164. await self._sync_group_v2(group, create_group_portal)
  165. else:
  166. self.log.warning("Unknown return type in list_groups: %s", type(group))
  167. except Exception:
  168. self.log.exception(f"Failed to sync group {group_id}")
  169. # region Database getters
  170. def _add_to_cache(self) -> None:
  171. self.by_mxid[self.mxid] = self
  172. if self.username:
  173. self.by_username[self.username] = self
  174. @classmethod
  175. async def get_by_mxid(cls, mxid: UserID, create: bool = True) -> Optional['User']:
  176. # Never allow ghosts to be users
  177. if pu.Puppet.get_id_from_mxid(mxid):
  178. return None
  179. try:
  180. return cls.by_mxid[mxid]
  181. except KeyError:
  182. pass
  183. user = cast(cls, await super().get_by_mxid(mxid))
  184. if user is not None:
  185. user._add_to_cache()
  186. return user
  187. if create:
  188. user = cls(mxid)
  189. await user.insert()
  190. user._add_to_cache()
  191. return user
  192. return None
  193. @classmethod
  194. async def get_by_username(cls, username: str) -> Optional['User']:
  195. try:
  196. return cls.by_username[username]
  197. except KeyError:
  198. pass
  199. user = cast(cls, await super().get_by_username(username))
  200. if user is not None:
  201. user._add_to_cache()
  202. return user
  203. return None
  204. @classmethod
  205. async def all_logged_in(cls) -> AsyncGenerator['User', None]:
  206. users = await super().all_logged_in()
  207. user: cls
  208. for user in users:
  209. try:
  210. yield cls.by_mxid[user.mxid]
  211. except KeyError:
  212. user._add_to_cache()
  213. yield user
  214. # endregion