puppet.py 10 KB

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