puppet.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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, 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 = await self._update_contact_info(info)
  116. update = await self._update_name(info) or update
  117. update = await self._update_avatar(info, source) or update
  118. if update:
  119. await self.update()
  120. async def _update_contact_info(self, info: BaseResponseUser | None = None) -> bool:
  121. if not self.bridge.homeserver_software.is_hungry:
  122. return False
  123. if self.contact_info_set:
  124. return False
  125. try:
  126. identifiers = []
  127. if info and info.username:
  128. identifiers.append(f"instagram:{info.username}")
  129. await self.default_mxid_intent.beeper_update_profile(
  130. {
  131. "com.beeper.bridge.identifiers": identifiers,
  132. "com.beeper.bridge.remote_id": str(self.fbid),
  133. "com.beeper.bridge.service": self.bridge.beeper_service_name,
  134. "com.beeper.bridge.network": self.bridge.beeper_network_name,
  135. }
  136. )
  137. self.contact_info_set = True
  138. except Exception:
  139. self.log.exception("Error updating contact info")
  140. self.contact_info_set = False
  141. return True
  142. @classmethod
  143. def _get_displayname(cls, info: BaseResponseUser) -> str:
  144. return cls.config["bridge.displayname_template"].format(
  145. displayname=info.full_name or info.username, id=info.pk, username=info.username
  146. )
  147. async def _update_name(self, info: BaseResponseUser) -> bool:
  148. name = self._get_displayname(info)
  149. if name != self.name:
  150. self.name = name
  151. try:
  152. await self.default_mxid_intent.set_displayname(self.name)
  153. self.name_set = True
  154. except Exception:
  155. self.log.exception("Failed to update displayname")
  156. self.name_set = False
  157. return True
  158. return False
  159. async def _update_avatar(self, info: BaseResponseUser, source: u.User) -> bool:
  160. pic_id = (
  161. f"id_{info.profile_pic_id}.jpg"
  162. if info.profile_pic_id
  163. else os.path.basename(URL(info.profile_pic_url).path)
  164. )
  165. if pic_id != self.photo_id or not self.avatar_set:
  166. self.photo_id = pic_id
  167. if info.has_anonymous_profile_picture:
  168. mxc = ""
  169. else:
  170. resp = await source.client.proxy_with_retry(
  171. "Puppet._update_avatar",
  172. lambda: source.client.raw_http_get(info.profile_pic_url),
  173. )
  174. content_type = resp.headers["Content-Type"]
  175. resp_data = await resp.read()
  176. mxc = await self.default_mxid_intent.upload_media(
  177. data=resp_data,
  178. mime_type=content_type,
  179. filename=pic_id,
  180. async_upload=self.config["homeserver.async_media"],
  181. )
  182. try:
  183. await self.default_mxid_intent.set_avatar_url(mxc)
  184. self.avatar_set = True
  185. self.photo_mxc = mxc
  186. except Exception:
  187. self.log.exception("Failed to update avatar")
  188. self.avatar_set = False
  189. return True
  190. return False
  191. async def default_puppet_should_leave_room(self, room_id: RoomID) -> bool:
  192. portal = await p.Portal.get_by_mxid(room_id)
  193. return portal and portal.other_user_pk != self.pk
  194. # region Database getters
  195. def _add_to_cache(self) -> None:
  196. self.by_pk[self.pk] = self
  197. if self.custom_mxid:
  198. self.by_custom_mxid[self.custom_mxid] = self
  199. async def save(self) -> None:
  200. await self.update()
  201. @classmethod
  202. async def get_by_mxid(cls, mxid: UserID, create: bool = True) -> Puppet | None:
  203. pk = cls.get_id_from_mxid(mxid)
  204. if pk:
  205. return await cls.get_by_pk(pk, create=create)
  206. return None
  207. @classmethod
  208. @async_getter_lock
  209. async def get_by_custom_mxid(cls, mxid: UserID) -> Puppet | None:
  210. try:
  211. return cls.by_custom_mxid[mxid]
  212. except KeyError:
  213. pass
  214. puppet = cast(cls, await super().get_by_custom_mxid(mxid))
  215. if puppet:
  216. puppet._add_to_cache()
  217. return puppet
  218. return None
  219. @classmethod
  220. def get_id_from_mxid(cls, mxid: UserID) -> int | None:
  221. return cls.mxid_template.parse(mxid)
  222. @classmethod
  223. def get_mxid_from_id(cls, pk: int) -> UserID:
  224. return UserID(cls.mxid_template.format_full(pk))
  225. @classmethod
  226. @async_getter_lock
  227. async def get_by_pk(cls, pk: int, *, create: bool = True) -> Puppet | None:
  228. try:
  229. return cls.by_pk[pk]
  230. except KeyError:
  231. pass
  232. puppet = cast(cls, await super().get_by_pk(pk))
  233. if puppet is not None:
  234. puppet._add_to_cache()
  235. return puppet
  236. if create:
  237. puppet = cls(pk)
  238. await puppet.insert()
  239. puppet._add_to_cache()
  240. return puppet
  241. return None
  242. @classmethod
  243. async def all_with_custom_mxid(cls) -> AsyncGenerator[Puppet, None]:
  244. puppets = await super().all_with_custom_mxid()
  245. puppet: cls
  246. for index, puppet in enumerate(puppets):
  247. try:
  248. yield cls.by_pk[puppet.pk]
  249. except KeyError:
  250. puppet._add_to_cache()
  251. yield puppet
  252. # endregion