puppet.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2022 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 __future__ import annotations
  17. from typing import TYPE_CHECKING, Any, AsyncGenerator, AsyncIterable, Awaitable, cast
  18. import os.path
  19. from yarl import URL
  20. from mauigpapi.types import BaseResponseUser
  21. from mautrix.appservice import IntentAPI
  22. from mautrix.bridge import BasePuppet, async_getter_lock
  23. from mautrix.types import ContentURI, RoomID, SyncToken, UserID
  24. from mautrix.util.simple_template import SimpleTemplate
  25. from . import portal as p, user as u
  26. from .config import Config
  27. from .db import Puppet as DBPuppet
  28. if TYPE_CHECKING:
  29. from .__main__ import InstagramBridge
  30. class Puppet(DBPuppet, BasePuppet):
  31. by_pk: dict[int, Puppet] = {}
  32. by_custom_mxid: dict[UserID, Puppet] = {}
  33. hs_domain: str
  34. mxid_template: SimpleTemplate[int]
  35. bridge: InstagramBridge
  36. config: Config
  37. default_mxid_intent: IntentAPI
  38. default_mxid: UserID
  39. def __init__(
  40. self,
  41. pk: int,
  42. name: str | None = None,
  43. username: str | None = None,
  44. photo_id: str | None = None,
  45. photo_mxc: ContentURI | None = None,
  46. name_set: bool = False,
  47. avatar_set: bool = False,
  48. contact_info_set: bool = False,
  49. is_registered: bool = False,
  50. custom_mxid: UserID | None = None,
  51. access_token: str | None = None,
  52. next_batch: SyncToken | None = None,
  53. base_url: URL | None = None,
  54. ) -> None:
  55. super().__init__(
  56. pk=pk,
  57. name=name,
  58. username=username,
  59. photo_id=photo_id,
  60. name_set=name_set,
  61. photo_mxc=photo_mxc,
  62. avatar_set=avatar_set,
  63. contact_info_set=contact_info_set,
  64. is_registered=is_registered,
  65. custom_mxid=custom_mxid,
  66. access_token=access_token,
  67. next_batch=next_batch,
  68. base_url=base_url,
  69. )
  70. self.log = self.log.getChild(str(pk))
  71. self.default_mxid = self.get_mxid_from_id(pk)
  72. self.default_mxid_intent = self.az.intent.user(self.default_mxid)
  73. self.intent = self._fresh_intent()
  74. @classmethod
  75. def init_cls(cls, bridge: "InstagramBridge") -> AsyncIterable[Awaitable[None]]:
  76. cls.bridge = bridge
  77. cls.config = bridge.config
  78. cls.loop = bridge.loop
  79. cls.mx = bridge.matrix
  80. cls.az = bridge.az
  81. cls.hs_domain = cls.config["homeserver.domain"]
  82. cls.mxid_template = SimpleTemplate(
  83. cls.config["bridge.username_template"],
  84. "userid",
  85. prefix="@",
  86. suffix=f":{cls.hs_domain}",
  87. type=int,
  88. )
  89. cls.sync_with_custom_puppets = cls.config["bridge.sync_with_custom_puppets"]
  90. cls.homeserver_url_map = {
  91. server: URL(url)
  92. for server, url in cls.config["bridge.double_puppet_server_map"].items()
  93. }
  94. cls.allow_discover_url = cls.config["bridge.double_puppet_allow_discovery"]
  95. cls.login_shared_secret_map = {
  96. server: secret.encode("utf-8")
  97. for server, secret in cls.config["bridge.login_shared_secret_map"].items()
  98. }
  99. cls.login_device_name = "Instagram Bridge"
  100. return (puppet.try_start() async for puppet in cls.all_with_custom_mxid())
  101. @property
  102. def igpk(self) -> int:
  103. return self.pk
  104. def intent_for(self, portal: p.Portal) -> IntentAPI:
  105. if portal.other_user_pk == self.pk:
  106. return self.default_mxid_intent
  107. return self.intent
  108. def need_backfill_invite(self, portal: p.Portal) -> bool:
  109. return (
  110. portal.other_user_pk != self.pk
  111. and (self.is_real_user or portal.is_direct)
  112. and self.config["bridge.backfill.invite_own_puppet"]
  113. )
  114. async def update_info(self, info: BaseResponseUser, source: u.User) -> None:
  115. update = False
  116. if info.username and self.username != info.username:
  117. self.username = info.username
  118. update = True
  119. update = await self.update_contact_info() or update
  120. update = await self._update_name(info) or update
  121. update = await self._update_avatar(info, source) or update
  122. if update:
  123. await self.update()
  124. async def update_contact_info(self) -> bool:
  125. if not self.bridge.homeserver_software.is_hungry:
  126. return False
  127. if self.contact_info_set:
  128. return False
  129. try:
  130. contact_info: dict[str, Any] = {
  131. "com.beeper.bridge.remote_id": str(self.igpk),
  132. "com.beeper.bridge.service": self.bridge.beeper_service_name,
  133. "com.beeper.bridge.network": self.bridge.beeper_network_name,
  134. }
  135. if self.username:
  136. contact_info["com.beeper.bridge.identifiers"] = [f"instagram:{self.username}"]
  137. await self.default_mxid_intent.beeper_update_profile(contact_info)
  138. self.contact_info_set = True
  139. except Exception:
  140. self.log.exception("Error updating contact info")
  141. self.contact_info_set = False
  142. return True
  143. @classmethod
  144. def _get_displayname(cls, info: BaseResponseUser) -> str:
  145. return cls.config["bridge.displayname_template"].format(
  146. displayname=info.full_name or info.username, id=info.pk, username=info.username
  147. )
  148. async def _update_name(self, info: BaseResponseUser) -> bool:
  149. name = self._get_displayname(info)
  150. if name != self.name:
  151. self.name = name
  152. try:
  153. await self.default_mxid_intent.set_displayname(self.name)
  154. self.name_set = True
  155. except Exception:
  156. self.log.exception("Failed to update displayname")
  157. self.name_set = False
  158. return True
  159. return False
  160. async def _update_avatar(self, info: BaseResponseUser, source: u.User) -> bool:
  161. pic_id = (
  162. f"id_{info.profile_pic_id}.jpg"
  163. if info.profile_pic_id
  164. else os.path.basename(URL(info.profile_pic_url).path)
  165. )
  166. if pic_id != self.photo_id or not self.avatar_set:
  167. self.photo_id = pic_id
  168. if info.has_anonymous_profile_picture:
  169. mxc = ""
  170. else:
  171. resp = await source.client.proxy_with_retry(
  172. "Puppet._update_avatar",
  173. lambda: source.client.raw_http_get(info.profile_pic_url),
  174. )
  175. content_type = resp.headers["Content-Type"]
  176. resp_data = await resp.read()
  177. mxc = await self.default_mxid_intent.upload_media(
  178. data=resp_data,
  179. mime_type=content_type,
  180. filename=pic_id,
  181. async_upload=self.config["homeserver.async_media"],
  182. )
  183. try:
  184. await self.default_mxid_intent.set_avatar_url(mxc)
  185. self.avatar_set = True
  186. self.photo_mxc = mxc
  187. except Exception:
  188. self.log.exception("Failed to update avatar")
  189. self.avatar_set = False
  190. return True
  191. return False
  192. async def default_puppet_should_leave_room(self, room_id: RoomID) -> bool:
  193. portal = await p.Portal.get_by_mxid(room_id)
  194. return portal and portal.other_user_pk != self.pk
  195. # region Database getters
  196. def _add_to_cache(self) -> None:
  197. self.by_pk[self.pk] = self
  198. if self.custom_mxid:
  199. self.by_custom_mxid[self.custom_mxid] = self
  200. async def save(self) -> None:
  201. await self.update()
  202. @classmethod
  203. async def get_by_mxid(cls, mxid: UserID, create: bool = True) -> Puppet | None:
  204. pk = cls.get_id_from_mxid(mxid)
  205. if pk:
  206. return await cls.get_by_pk(pk, create=create)
  207. return None
  208. @classmethod
  209. @async_getter_lock
  210. async def get_by_custom_mxid(cls, mxid: UserID) -> Puppet | None:
  211. try:
  212. return cls.by_custom_mxid[mxid]
  213. except KeyError:
  214. pass
  215. puppet = cast(cls, await super().get_by_custom_mxid(mxid))
  216. if puppet:
  217. puppet._add_to_cache()
  218. return puppet
  219. return None
  220. @classmethod
  221. def get_id_from_mxid(cls, mxid: UserID) -> int | None:
  222. return cls.mxid_template.parse(mxid)
  223. @classmethod
  224. def get_mxid_from_id(cls, pk: int) -> UserID:
  225. return UserID(cls.mxid_template.format_full(pk))
  226. @classmethod
  227. @async_getter_lock
  228. async def get_by_pk(cls, pk: int, *, create: bool = True) -> Puppet | None:
  229. try:
  230. return cls.by_pk[pk]
  231. except KeyError:
  232. pass
  233. puppet = cast(cls, await super().get_by_pk(pk))
  234. if puppet is not None:
  235. puppet._add_to_cache()
  236. return puppet
  237. if create:
  238. puppet = cls(pk)
  239. await puppet.insert()
  240. puppet._add_to_cache()
  241. return puppet
  242. return None
  243. @classmethod
  244. async def all_with_custom_mxid(cls) -> AsyncGenerator[Puppet, None]:
  245. puppets = await super().all_with_custom_mxid()
  246. puppet: cls
  247. for puppet in puppets:
  248. try:
  249. yield cls.by_pk[puppet.pk]
  250. except KeyError:
  251. puppet._add_to_cache()
  252. yield puppet
  253. @classmethod
  254. async def get_all(cls) -> AsyncGenerator[Puppet, None]:
  255. puppets = await super().get_all()
  256. puppet: cls
  257. for puppet in puppets:
  258. try:
  259. yield cls.by_pk[puppet.pk]
  260. except KeyError:
  261. puppet._add_to_cache()
  262. yield puppet
  263. # endregion