puppet.py 8.5 KB

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