puppet.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. config: Config
  36. default_mxid_intent: IntentAPI
  37. default_mxid: UserID
  38. def __init__(
  39. self,
  40. pk: int,
  41. name: str | None = None,
  42. username: str | None = None,
  43. photo_id: str | None = None,
  44. photo_mxc: ContentURI | None = None,
  45. name_set: bool = False,
  46. avatar_set: bool = False,
  47. contact_info_set: bool = False,
  48. is_registered: bool = False,
  49. custom_mxid: UserID | None = None,
  50. access_token: str | None = None,
  51. next_batch: SyncToken | None = None,
  52. base_url: URL | None = None,
  53. ) -> None:
  54. super().__init__(
  55. pk=pk,
  56. name=name,
  57. username=username,
  58. photo_id=photo_id,
  59. name_set=name_set,
  60. photo_mxc=photo_mxc,
  61. avatar_set=avatar_set,
  62. contact_info_set=contact_info_set,
  63. is_registered=is_registered,
  64. custom_mxid=custom_mxid,
  65. access_token=access_token,
  66. next_batch=next_batch,
  67. base_url=base_url,
  68. )
  69. self.log = self.log.getChild(str(pk))
  70. self.default_mxid = self.get_mxid_from_id(pk)
  71. self.default_mxid_intent = self.az.intent.user(self.default_mxid)
  72. self.intent = self._fresh_intent()
  73. @classmethod
  74. def init_cls(cls, bridge: "InstagramBridge") -> AsyncIterable[Awaitable[None]]:
  75. cls.config = bridge.config
  76. cls.loop = bridge.loop
  77. cls.mx = bridge.matrix
  78. cls.az = bridge.az
  79. cls.hs_domain = cls.config["homeserver.domain"]
  80. cls.mxid_template = SimpleTemplate(
  81. cls.config["bridge.username_template"],
  82. "userid",
  83. prefix="@",
  84. suffix=f":{cls.hs_domain}",
  85. type=int,
  86. )
  87. cls.sync_with_custom_puppets = cls.config["bridge.sync_with_custom_puppets"]
  88. cls.homeserver_url_map = {
  89. server: URL(url)
  90. for server, url in cls.config["bridge.double_puppet_server_map"].items()
  91. }
  92. cls.allow_discover_url = cls.config["bridge.double_puppet_allow_discovery"]
  93. cls.login_shared_secret_map = {
  94. server: secret.encode("utf-8")
  95. for server, secret in cls.config["bridge.login_shared_secret_map"].items()
  96. }
  97. cls.login_device_name = "Instagram Bridge"
  98. return (puppet.try_start() async for puppet in cls.all_with_custom_mxid())
  99. @property
  100. def igpk(self) -> int:
  101. return self.pk
  102. def intent_for(self, portal: p.Portal) -> IntentAPI:
  103. if portal.other_user_pk == self.pk:
  104. return self.default_mxid_intent
  105. return self.intent
  106. def need_backfill_invite(self, portal: p.Portal) -> bool:
  107. return (
  108. portal.other_user_pk != self.pk
  109. and (self.is_real_user or portal.is_direct)
  110. and self.config["bridge.backfill.invite_own_puppet"]
  111. )
  112. async def update_info(self, info: BaseResponseUser, source: u.User) -> None:
  113. update = False
  114. update = await self._update_name(info) or update
  115. update = await self._update_avatar(info, source) or update
  116. if update:
  117. await self.update()
  118. @classmethod
  119. def _get_displayname(cls, info: BaseResponseUser) -> str:
  120. return cls.config["bridge.displayname_template"].format(
  121. displayname=info.full_name or info.username, id=info.pk, username=info.username
  122. )
  123. async def _update_name(self, info: BaseResponseUser) -> bool:
  124. name = self._get_displayname(info)
  125. if name != self.name:
  126. self.name = name
  127. try:
  128. await self.default_mxid_intent.set_displayname(self.name)
  129. self.name_set = True
  130. except Exception:
  131. self.log.exception("Failed to update displayname")
  132. self.name_set = False
  133. return True
  134. return False
  135. async def _update_avatar(self, info: BaseResponseUser, source: u.User) -> bool:
  136. pic_id = (
  137. f"id_{info.profile_pic_id}.jpg"
  138. if info.profile_pic_id
  139. else os.path.basename(URL(info.profile_pic_url).path)
  140. )
  141. if pic_id != self.photo_id or not self.avatar_set:
  142. self.photo_id = pic_id
  143. if info.has_anonymous_profile_picture:
  144. mxc = ""
  145. else:
  146. resp = await source.client.proxy_with_retry(
  147. "Puppet._update_avatar",
  148. lambda: source.client.raw_http_get(info.profile_pic_url),
  149. )
  150. content_type = resp.headers["Content-Type"]
  151. resp_data = await resp.read()
  152. mxc = await self.default_mxid_intent.upload_media(
  153. data=resp_data,
  154. mime_type=content_type,
  155. filename=pic_id,
  156. async_upload=self.config["homeserver.async_media"],
  157. )
  158. try:
  159. await self.default_mxid_intent.set_avatar_url(mxc)
  160. self.avatar_set = True
  161. self.photo_mxc = mxc
  162. except Exception:
  163. self.log.exception("Failed to update avatar")
  164. self.avatar_set = False
  165. return True
  166. return False
  167. async def default_puppet_should_leave_room(self, room_id: RoomID) -> bool:
  168. portal = await p.Portal.get_by_mxid(room_id)
  169. return portal and portal.other_user_pk != self.pk
  170. # region Database getters
  171. def _add_to_cache(self) -> None:
  172. self.by_pk[self.pk] = 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) -> Puppet | None:
  179. pk = cls.get_id_from_mxid(mxid)
  180. if pk:
  181. return await cls.get_by_pk(pk, create=create)
  182. return None
  183. @classmethod
  184. @async_getter_lock
  185. async def get_by_custom_mxid(cls, mxid: UserID) -> Puppet | None:
  186. try:
  187. return cls.by_custom_mxid[mxid]
  188. except KeyError:
  189. pass
  190. puppet = cast(cls, await super().get_by_custom_mxid(mxid))
  191. if puppet:
  192. puppet._add_to_cache()
  193. return puppet
  194. return None
  195. @classmethod
  196. def get_id_from_mxid(cls, mxid: UserID) -> int | None:
  197. return cls.mxid_template.parse(mxid)
  198. @classmethod
  199. def get_mxid_from_id(cls, pk: int) -> UserID:
  200. return UserID(cls.mxid_template.format_full(pk))
  201. @classmethod
  202. @async_getter_lock
  203. async def get_by_pk(cls, pk: int, *, create: bool = True) -> Puppet | None:
  204. try:
  205. return cls.by_pk[pk]
  206. except KeyError:
  207. pass
  208. puppet = cast(cls, await super().get_by_pk(pk))
  209. if puppet is not None:
  210. puppet._add_to_cache()
  211. return puppet
  212. if create:
  213. puppet = cls(pk)
  214. await puppet.insert()
  215. puppet._add_to_cache()
  216. return puppet
  217. return None
  218. @classmethod
  219. async def all_with_custom_mxid(cls) -> AsyncGenerator[Puppet, None]:
  220. puppets = await super().all_with_custom_mxid()
  221. puppet: cls
  222. for index, puppet in enumerate(puppets):
  223. try:
  224. yield cls.by_pk[puppet.pk]
  225. except KeyError:
  226. puppet._add_to_cache()
  227. yield puppet
  228. # endregion