puppet.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 (Optional, Dict, AsyncIterable, Awaitable, AsyncGenerator, Union,
  17. TYPE_CHECKING, cast)
  18. from uuid import UUID
  19. import asyncio
  20. from yarl import URL
  21. from mausignald.types import Address, Contact, Profile
  22. from mautrix.bridge import BasePuppet
  23. from mautrix.appservice import IntentAPI
  24. from mautrix.types import UserID, SyncToken, RoomID
  25. from mautrix.util.simple_template import SimpleTemplate
  26. from .db import Puppet as DBPuppet
  27. from .config import Config
  28. from . import portal as p
  29. if TYPE_CHECKING:
  30. from .__main__ import SignalBridge
  31. try:
  32. import phonenumbers
  33. except ImportError:
  34. phonenumbers = None
  35. class Puppet(DBPuppet, BasePuppet):
  36. by_uuid: Dict[UUID, 'Puppet'] = {}
  37. by_number: Dict[str, 'Puppet'] = {}
  38. by_custom_mxid: Dict[UserID, 'Puppet'] = {}
  39. hs_domain: str
  40. mxid_template: SimpleTemplate[str]
  41. config: Config
  42. default_mxid_intent: IntentAPI
  43. default_mxid: UserID
  44. _uuid_lock: asyncio.Lock
  45. _update_info_lock: asyncio.Lock
  46. def __init__(self, uuid: Optional[UUID], number: Optional[str], name: Optional[str] = None,
  47. uuid_registered: bool = False, number_registered: bool = False,
  48. custom_mxid: Optional[UserID] = None, access_token: Optional[str] = None,
  49. next_batch: Optional[SyncToken] = None, base_url: Optional[URL] = None) -> None:
  50. super().__init__(uuid=uuid, number=number, name=name, uuid_registered=uuid_registered,
  51. number_registered=number_registered, custom_mxid=custom_mxid,
  52. access_token=access_token, next_batch=next_batch, base_url=base_url)
  53. self.log = self.log.getChild(str(uuid) or number)
  54. self.default_mxid = self.get_mxid_from_id(self.address)
  55. self.default_mxid_intent = self.az.intent.user(self.default_mxid)
  56. self.intent = self._fresh_intent()
  57. self._uuid_lock = asyncio.Lock()
  58. self._update_info_lock = asyncio.Lock()
  59. @classmethod
  60. def init_cls(cls, bridge: 'SignalBridge') -> AsyncIterable[Awaitable[None]]:
  61. cls.config = bridge.config
  62. cls.loop = bridge.loop
  63. cls.mx = bridge.matrix
  64. cls.az = bridge.az
  65. cls.hs_domain = cls.config["homeserver.domain"]
  66. cls.mxid_template = SimpleTemplate(cls.config["bridge.username_template"], "userid",
  67. prefix="@", suffix=f":{cls.hs_domain}", type=str)
  68. cls.sync_with_custom_puppets = cls.config["bridge.sync_with_custom_puppets"]
  69. cls.homeserver_url_map = {server: URL(url) for server, url
  70. in cls.config["bridge.double_puppet_server_map"].items()}
  71. cls.allow_discover_url = cls.config["bridge.double_puppet_allow_discovery"]
  72. cls.login_shared_secret_map = {server: secret.encode("utf-8") for server, secret
  73. in cls.config["bridge.login_shared_secret_map"].items()}
  74. cls.login_device_name = "Signal Bridge"
  75. return (puppet.try_start() async for puppet in cls.all_with_custom_mxid())
  76. def intent_for(self, portal: 'p.Portal') -> IntentAPI:
  77. if portal.chat_id == self.uuid:
  78. return self.default_mxid_intent
  79. return self.intent
  80. @property
  81. def is_registered(self) -> bool:
  82. return self.uuid_registered if self.uuid is not None else self.number_registered
  83. @is_registered.setter
  84. def is_registered(self, value: bool) -> None:
  85. if self.uuid is not None:
  86. self.uuid_registered = value
  87. else:
  88. self.number_registered = value
  89. @property
  90. def address(self) -> Address:
  91. return Address(uuid=self.uuid, number=self.number)
  92. async def handle_uuid_receive(self, uuid: UUID) -> None:
  93. async with self._uuid_lock:
  94. if self.uuid:
  95. # Received UUID was handled while this call was waiting
  96. return
  97. await self._handle_uuid_receive(uuid)
  98. async def _handle_uuid_receive(self, uuid: UUID) -> None:
  99. self.log.debug(f"Found UUID for user: {uuid}")
  100. await self._set_uuid(uuid)
  101. self.by_uuid[self.uuid] = self
  102. prev_intent = self.default_mxid_intent
  103. self.default_mxid = self.get_mxid_from_id(self.address)
  104. self.default_mxid_intent = self.az.intent.user(self.default_mxid)
  105. self.intent = self._fresh_intent()
  106. await self.intent.ensure_registered()
  107. await self.intent.set_displayname(self.name)
  108. self.log = self.log.getChild(str(uuid))
  109. self.log.debug(f"Migrating memberships {prev_intent.mxid} -> {self.default_mxid_intent}")
  110. for room_id in await prev_intent.get_joined_rooms():
  111. await prev_intent.invite_user(room_id, self.default_mxid)
  112. await self.default_mxid_intent.join_room_by_id(room_id)
  113. await prev_intent.leave_room(room_id)
  114. async def update_info(self, info: Union[Profile, Contact]) -> None:
  115. if isinstance(info, (Contact, Address)):
  116. address = info.address if isinstance(info, Contact) else info
  117. if address.uuid and not self.uuid:
  118. await self.handle_uuid_receive(address.uuid)
  119. if not self.config["bridge.allow_contact_list_name_updates"] and self.name is not None:
  120. return
  121. name = info.name if isinstance(info, (Contact, Profile)) else None
  122. async with self._update_info_lock:
  123. update = False
  124. update = await self._update_name(name) or update
  125. if update:
  126. await self.update()
  127. @staticmethod
  128. def fmt_phone(number: str) -> str:
  129. if phonenumbers is None:
  130. return number
  131. parsed = phonenumbers.parse(number)
  132. fmt = phonenumbers.PhoneNumberFormat.INTERNATIONAL
  133. return phonenumbers.format_number(parsed, fmt)
  134. @classmethod
  135. def _get_displayname(cls, address: Address, name: Optional[str]) -> str:
  136. names = name.split("\x00") if name else []
  137. data = {
  138. "first_name": names[0] if len(names) > 0 else "",
  139. "last_name": names[-1] if len(names) > 1 else "",
  140. "full_name": " ".join(names),
  141. "phone": cls.fmt_phone(address.number) if address.number else None,
  142. "uuid": str(address.uuid) if address.uuid else None,
  143. }
  144. for pref in cls.config["bridge.displayname_preference"]:
  145. value = data.get(pref.replace(" ", "_"))
  146. if value:
  147. data["displayname"] = value
  148. break
  149. return cls.config["bridge.displayname_template"].format(**data)
  150. async def _update_name(self, name: Optional[str]) -> bool:
  151. name = self._get_displayname(self.address, name)
  152. if name != self.name:
  153. self.name = name
  154. await self.default_mxid_intent.set_displayname(self.name)
  155. self.loop.create_task(self._update_portal_names())
  156. return True
  157. return False
  158. async def _update_portal_names(self) -> None:
  159. async for portal in p.Portal.find_private_chats_with(self.uuid):
  160. if portal.receiver == self.number:
  161. # This is a note to self chat, don't change the name
  162. continue
  163. await portal.update_puppet_name(self.name)
  164. async def default_puppet_should_leave_room(self, room_id: RoomID) -> bool:
  165. portal = await p.Portal.get_by_mxid(room_id)
  166. return portal and portal.chat_id != self.uuid
  167. # region Database getters
  168. def _add_to_cache(self) -> None:
  169. if self.uuid:
  170. self.by_uuid[self.uuid] = self
  171. if self.number:
  172. self.by_number[self.number] = self
  173. if self.custom_mxid:
  174. self.by_custom_mxid[self.custom_mxid] = self
  175. async def save(self) -> None:
  176. await self.update()
  177. @classmethod
  178. async def get_by_mxid(cls, mxid: UserID, create: bool = True) -> Optional['Puppet']:
  179. address = cls.get_id_from_mxid(mxid)
  180. if not address:
  181. return None
  182. return await cls.get_by_address(address, create)
  183. @classmethod
  184. async def get_by_custom_mxid(cls, mxid: UserID) -> Optional['Puppet']:
  185. try:
  186. return cls.by_custom_mxid[mxid]
  187. except KeyError:
  188. pass
  189. puppet = cast(cls, await super().get_by_custom_mxid(mxid))
  190. if puppet:
  191. puppet._add_to_cache()
  192. return puppet
  193. return None
  194. @classmethod
  195. def get_id_from_mxid(cls, mxid: UserID) -> Optional[Address]:
  196. identifier = cls.mxid_template.parse(mxid)
  197. if not identifier:
  198. return None
  199. if identifier.startswith("phone_"):
  200. return Address(number="+" + identifier[len("phone_"):])
  201. else:
  202. try:
  203. return Address(uuid=UUID(identifier.upper()))
  204. except ValueError:
  205. return None
  206. @classmethod
  207. def get_mxid_from_id(cls, address: Address) -> UserID:
  208. if address.uuid:
  209. identifier = str(address.uuid).lower()
  210. elif address.number:
  211. identifier = f"phone_{address.number.lstrip('+')}"
  212. else:
  213. raise ValueError("Empty address")
  214. return UserID(cls.mxid_template.format_full(identifier))
  215. @classmethod
  216. async def get_by_address(cls, address: Address, create: bool = True) -> Optional['Puppet']:
  217. puppet = await cls._get_by_address(address, create)
  218. if puppet and address.uuid and not puppet.uuid:
  219. # We found a UUID for this user, store it ASAP
  220. await puppet.handle_uuid_receive(address.uuid)
  221. return puppet
  222. @classmethod
  223. async def _get_by_address(cls, address: Address, create: bool = True) -> Optional['Puppet']:
  224. if not address.is_valid:
  225. raise ValueError("Empty address")
  226. if address.uuid:
  227. try:
  228. return cls.by_uuid[address.uuid]
  229. except KeyError:
  230. pass
  231. if address.number:
  232. try:
  233. return cls.by_number[address.number]
  234. except KeyError:
  235. pass
  236. puppet = cast(cls, await super().get_by_address(address))
  237. if puppet is not None:
  238. puppet._add_to_cache()
  239. return puppet
  240. if create:
  241. puppet = cls(address.uuid, address.number)
  242. await puppet.insert()
  243. puppet._add_to_cache()
  244. return puppet
  245. return None
  246. @classmethod
  247. async def all_with_custom_mxid(cls) -> AsyncGenerator['Puppet', None]:
  248. puppets = await super().all_with_custom_mxid()
  249. puppet: cls
  250. for index, puppet in enumerate(puppets):
  251. try:
  252. yield cls.by_uuid[puppet.uuid]
  253. except KeyError:
  254. try:
  255. yield cls.by_number[puppet.number]
  256. except KeyError:
  257. puppet._add_to_cache()
  258. yield puppet
  259. # endregion