puppet.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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, Tuple,
  17. TYPE_CHECKING, cast)
  18. from uuid import UUID
  19. import hashlib
  20. import asyncio
  21. import os.path
  22. from yarl import URL
  23. from mausignald.types import Address, Contact, Profile
  24. from mautrix.bridge import BasePuppet, async_getter_lock
  25. from mautrix.appservice import IntentAPI
  26. from mautrix.types import UserID, SyncToken, RoomID, ContentURI
  27. from mautrix.errors import MForbidden
  28. from mautrix.util.simple_template import SimpleTemplate
  29. from .db import Puppet as DBPuppet
  30. from .config import Config
  31. from . import portal as p, user as u
  32. if TYPE_CHECKING:
  33. from .__main__ import SignalBridge
  34. try:
  35. import phonenumbers
  36. except ImportError:
  37. phonenumbers = None
  38. class Puppet(DBPuppet, BasePuppet):
  39. by_uuid: Dict[UUID, 'Puppet'] = {}
  40. by_number: Dict[str, 'Puppet'] = {}
  41. by_custom_mxid: Dict[UserID, 'Puppet'] = {}
  42. hs_domain: str
  43. mxid_template: SimpleTemplate[str]
  44. config: Config
  45. default_mxid_intent: IntentAPI
  46. default_mxid: UserID
  47. _uuid_lock: asyncio.Lock
  48. _update_info_lock: asyncio.Lock
  49. def __init__(self, uuid: Optional[UUID], number: Optional[str], name: Optional[str] = None,
  50. avatar_url: Optional[ContentURI] = None, avatar_hash: Optional[str] = None,
  51. name_set: bool = False, avatar_set: bool = False, uuid_registered: bool = False,
  52. number_registered: bool = False, custom_mxid: Optional[UserID] = None,
  53. access_token: Optional[str] = None, next_batch: Optional[SyncToken] = None,
  54. base_url: Optional[URL] = None) -> None:
  55. super().__init__(uuid=uuid, number=number, name=name, avatar_url=avatar_url,
  56. avatar_hash=avatar_hash, name_set=name_set, avatar_set=avatar_set,
  57. uuid_registered=uuid_registered, number_registered=number_registered,
  58. custom_mxid=custom_mxid, access_token=access_token, next_batch=next_batch,
  59. base_url=base_url)
  60. self.log = self.log.getChild(str(uuid) if uuid else number)
  61. self.default_mxid = self.get_mxid_from_id(self.address)
  62. self.default_mxid_intent = self.az.intent.user(self.default_mxid)
  63. self.intent = self._fresh_intent()
  64. self._uuid_lock = asyncio.Lock()
  65. self._update_info_lock = asyncio.Lock()
  66. @classmethod
  67. def init_cls(cls, bridge: 'SignalBridge') -> AsyncIterable[Awaitable[None]]:
  68. cls.config = bridge.config
  69. cls.loop = bridge.loop
  70. cls.mx = bridge.matrix
  71. cls.az = bridge.az
  72. cls.hs_domain = cls.config["homeserver.domain"]
  73. cls.mxid_template = SimpleTemplate(cls.config["bridge.username_template"], "userid",
  74. prefix="@", suffix=f":{cls.hs_domain}", type=str)
  75. cls.sync_with_custom_puppets = cls.config["bridge.sync_with_custom_puppets"]
  76. cls.homeserver_url_map = {server: URL(url) for server, url
  77. in cls.config["bridge.double_puppet_server_map"].items()}
  78. cls.allow_discover_url = cls.config["bridge.double_puppet_allow_discovery"]
  79. cls.login_shared_secret_map = {server: secret.encode("utf-8") for server, secret
  80. in cls.config["bridge.login_shared_secret_map"].items()}
  81. cls.login_device_name = "Signal Bridge"
  82. return (puppet.try_start() async for puppet in cls.all_with_custom_mxid())
  83. def intent_for(self, portal: 'p.Portal') -> IntentAPI:
  84. if portal.chat_id == self.address:
  85. return self.default_mxid_intent
  86. return self.intent
  87. @property
  88. def is_registered(self) -> bool:
  89. return self.uuid_registered if self.uuid is not None else self.number_registered
  90. @is_registered.setter
  91. def is_registered(self, value: bool) -> None:
  92. if self.uuid is not None:
  93. self.uuid_registered = value
  94. else:
  95. self.number_registered = value
  96. @property
  97. def address(self) -> Address:
  98. return Address(uuid=self.uuid, number=self.number)
  99. async def handle_uuid_receive(self, uuid: UUID) -> None:
  100. async with self._uuid_lock:
  101. if self.uuid:
  102. # Received UUID was handled while this call was waiting
  103. return
  104. await self._handle_uuid_receive(uuid)
  105. async def handle_number_receive(self, number: str) -> None:
  106. async with self._uuid_lock:
  107. if self.number:
  108. return
  109. self.number = number
  110. self.by_number[self.number] = self
  111. await self._set_number(number)
  112. async def _handle_uuid_receive(self, uuid: UUID) -> None:
  113. self.log.debug(f"Found UUID for user: {uuid}")
  114. user = await u.User.get_by_username(self.number)
  115. if user and not user.uuid:
  116. user.uuid = self.uuid
  117. user.by_uuid[user.uuid] = user
  118. await user.update()
  119. self.uuid = uuid
  120. self.by_uuid[self.uuid] = self
  121. await self._set_uuid(uuid)
  122. async for portal in p.Portal.find_private_chats_with(Address(number=self.number)):
  123. self.log.trace(f"Updating chat_id of private chat portal {portal.receiver}")
  124. portal.handle_uuid_receive(self.uuid)
  125. prev_intent = self.default_mxid_intent
  126. self.default_mxid = self.get_mxid_from_id(self.address)
  127. self.default_mxid_intent = self.az.intent.user(self.default_mxid)
  128. self.intent = self._fresh_intent()
  129. await self.default_mxid_intent.ensure_registered()
  130. if self.name:
  131. await self.default_mxid_intent.set_displayname(self.name)
  132. self.log = Puppet.log.getChild(str(uuid))
  133. self.log.debug(f"Migrating memberships {prev_intent.mxid}"
  134. f" -> {self.default_mxid_intent.mxid}")
  135. try:
  136. joined_rooms = await prev_intent.get_joined_rooms()
  137. except MForbidden as e:
  138. self.log.debug(f"Got MForbidden ({e.message}) when getting joined rooms of old mxid, "
  139. "assuming there are no rooms to rejoin")
  140. return
  141. for room_id in joined_rooms:
  142. await prev_intent.invite_user(room_id, self.default_mxid)
  143. await prev_intent.leave_room(room_id)
  144. await self.default_mxid_intent.join_room_by_id(room_id)
  145. async def update_info(self, info: Union[Profile, Contact, Address]) -> None:
  146. address = info.address if isinstance(info, (Contact, Profile)) else info
  147. if address.uuid and not self.uuid:
  148. await self.handle_uuid_receive(address.uuid)
  149. if address.number and not self.number:
  150. await self.handle_number_receive(address.number)
  151. contact_names = self.config["bridge.contact_list_names"]
  152. if isinstance(info, Profile) and contact_names != "prefer" and info.profile_name:
  153. name = info.profile_name
  154. elif isinstance(info, (Contact, Profile)) and contact_names != "disallow":
  155. name = info.name
  156. if not name and isinstance(info, Profile) and info.profile_name:
  157. # Contact list name is preferred, but was not found, fall back to profile
  158. name = info.profile_name
  159. else:
  160. name = None
  161. async with self._update_info_lock:
  162. update = False
  163. if name is not None or self.name is None:
  164. update = await self._update_name(name) or update
  165. if isinstance(info, Profile):
  166. update = await self._update_avatar(info.avatar) or update
  167. elif contact_names != "disallow" and self.number:
  168. update = await self._update_avatar(f"contact-{self.number}") or update
  169. if update:
  170. await self.update()
  171. asyncio.create_task(self._update_portal_meta())
  172. @staticmethod
  173. def fmt_phone(number: str) -> str:
  174. if phonenumbers is None:
  175. return number
  176. parsed = phonenumbers.parse(number)
  177. fmt = phonenumbers.PhoneNumberFormat.INTERNATIONAL
  178. return phonenumbers.format_number(parsed, fmt)
  179. @classmethod
  180. def _get_displayname(cls, address: Address, name: Optional[str]) -> str:
  181. names = name.split("\x00") if name else []
  182. data = {
  183. "first_name": names[0] if len(names) > 0 else "",
  184. "last_name": names[-1] if len(names) > 1 else "",
  185. "full_name": " ".join(names),
  186. "phone": cls.fmt_phone(address.number) if address.number else None,
  187. "uuid": str(address.uuid) if address.uuid else None,
  188. "displayname": "Unknown user",
  189. }
  190. for pref in cls.config["bridge.displayname_preference"]:
  191. value = data.get(pref.replace(" ", "_"))
  192. if value:
  193. data["displayname"] = value
  194. break
  195. return cls.config["bridge.displayname_template"].format(**data)
  196. async def _update_name(self, name: Optional[str]) -> bool:
  197. name = self._get_displayname(self.address, name)
  198. if name != self.name or not self.name_set:
  199. self.name = name
  200. try:
  201. await self.default_mxid_intent.set_displayname(self.name)
  202. self.name_set = True
  203. except Exception:
  204. self.log.exception("Error setting displayname")
  205. self.name_set = False
  206. return True
  207. return False
  208. @staticmethod
  209. async def upload_avatar(self: Union['Puppet', 'p.Portal'], path: str, intent: IntentAPI,
  210. ) -> Union[bool, Tuple[str, ContentURI]]:
  211. if not path:
  212. return False
  213. if not path.startswith("/"):
  214. path = os.path.join(self.config["signal.avatar_dir"], path)
  215. try:
  216. with open(path, "rb") as file:
  217. data = file.read()
  218. except FileNotFoundError:
  219. return False
  220. if not data:
  221. return False
  222. new_hash = hashlib.sha256(data).hexdigest()
  223. if self.avatar_set and new_hash == self.avatar_hash:
  224. return False
  225. mxc = await intent.upload_media(data)
  226. return new_hash, mxc
  227. async def _update_avatar(self, path: str) -> bool:
  228. res = await Puppet.upload_avatar(self, path, self.default_mxid_intent)
  229. if res is False:
  230. return False
  231. self.avatar_hash, self.avatar_url = res
  232. try:
  233. await self.default_mxid_intent.set_avatar_url(self.avatar_url)
  234. self.avatar_set = True
  235. except Exception:
  236. self.log.exception("Error setting avatar")
  237. self.avatar_set = False
  238. return True
  239. async def _update_portal_meta(self) -> None:
  240. async for portal in p.Portal.find_private_chats_with(self.address):
  241. if portal.receiver == self.number:
  242. # This is a note to self chat, don't change the name
  243. continue
  244. try:
  245. await portal.update_puppet_name(self.name)
  246. await portal.update_puppet_avatar(self.avatar_hash, self.avatar_url)
  247. except Exception:
  248. self.log.exception(f"Error updating portal meta for {portal.receiver}")
  249. async def default_puppet_should_leave_room(self, room_id: RoomID) -> bool:
  250. portal = await p.Portal.get_by_mxid(room_id)
  251. return portal and portal.chat_id != self.uuid
  252. # region Database getters
  253. def _add_to_cache(self) -> None:
  254. if self.uuid:
  255. self.by_uuid[self.uuid] = self
  256. if self.number:
  257. self.by_number[self.number] = self
  258. if self.custom_mxid:
  259. self.by_custom_mxid[self.custom_mxid] = self
  260. async def save(self) -> None:
  261. await self.update()
  262. @classmethod
  263. async def get_by_mxid(cls, mxid: UserID, create: bool = True) -> Optional['Puppet']:
  264. address = cls.get_id_from_mxid(mxid)
  265. if not address:
  266. return None
  267. return await cls.get_by_address(address, create)
  268. @classmethod
  269. @async_getter_lock
  270. async def get_by_custom_mxid(cls, mxid: UserID) -> Optional['Puppet']:
  271. try:
  272. return cls.by_custom_mxid[mxid]
  273. except KeyError:
  274. pass
  275. puppet = cast(cls, await super().get_by_custom_mxid(mxid))
  276. if puppet:
  277. puppet._add_to_cache()
  278. return puppet
  279. return None
  280. @classmethod
  281. def get_id_from_mxid(cls, mxid: UserID) -> Optional[Address]:
  282. identifier = cls.mxid_template.parse(mxid)
  283. if not identifier:
  284. return None
  285. if identifier.startswith("phone_"):
  286. return Address(number="+" + identifier[len("phone_"):])
  287. else:
  288. try:
  289. return Address(uuid=UUID(identifier.upper()))
  290. except ValueError:
  291. return None
  292. @classmethod
  293. def get_mxid_from_id(cls, address: Address) -> UserID:
  294. if address.uuid:
  295. identifier = str(address.uuid).lower()
  296. elif address.number:
  297. identifier = f"phone_{address.number.lstrip('+')}"
  298. else:
  299. raise ValueError("Empty address")
  300. return UserID(cls.mxid_template.format_full(identifier))
  301. @classmethod
  302. @async_getter_lock
  303. async def get_by_address(cls, address: Address, create: bool = True) -> Optional['Puppet']:
  304. puppet = await cls._get_by_address(address, create)
  305. if puppet and address.uuid and not puppet.uuid:
  306. # We found a UUID for this user, store it ASAP
  307. await puppet.handle_uuid_receive(address.uuid)
  308. return puppet
  309. @classmethod
  310. async def _get_by_address(cls, address: Address, create: bool = True) -> Optional['Puppet']:
  311. if not address.is_valid:
  312. raise ValueError("Empty address")
  313. if address.uuid:
  314. try:
  315. return cls.by_uuid[address.uuid]
  316. except KeyError:
  317. pass
  318. if address.number:
  319. try:
  320. return cls.by_number[address.number]
  321. except KeyError:
  322. pass
  323. puppet = cast(cls, await super().get_by_address(address))
  324. if puppet is not None:
  325. puppet._add_to_cache()
  326. return puppet
  327. if create:
  328. puppet = cls(address.uuid, address.number)
  329. await puppet.insert()
  330. puppet._add_to_cache()
  331. return puppet
  332. return None
  333. @classmethod
  334. async def all_with_custom_mxid(cls) -> AsyncGenerator['Puppet', None]:
  335. puppets = await super().all_with_custom_mxid()
  336. puppet: cls
  337. for index, puppet in enumerate(puppets):
  338. try:
  339. yield cls.by_uuid[puppet.uuid]
  340. except KeyError:
  341. try:
  342. yield cls.by_number[puppet.number]
  343. except KeyError:
  344. puppet._add_to_cache()
  345. yield puppet
  346. # endregion