user.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2020 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 typing import (Dict, Optional, AsyncIterable, Awaitable, AsyncGenerator, List, TYPE_CHECKING,
  17. cast)
  18. from collections import defaultdict
  19. import asyncio
  20. import logging
  21. import time
  22. from mauigpapi import AndroidAPI, AndroidState, AndroidMQTT
  23. from mauigpapi.mqtt import Connect, Disconnect, GraphQLSubscription, SkywalkerSubscription
  24. from mauigpapi.types import (CurrentUser, MessageSyncEvent, Operation, RealtimeDirectEvent,
  25. ActivityIndicatorData, TypingStatus)
  26. from mauigpapi.errors import IGNotLoggedInError
  27. from mautrix.bridge import BaseUser
  28. from mautrix.types import UserID, RoomID, EventID, TextMessageEventContent, MessageType
  29. from mautrix.appservice import AppService
  30. from mautrix.util.opt_prometheus import Summary, Gauge, async_time
  31. from mautrix.util.logging import TraceLogger
  32. from .db import User as DBUser, Portal as DBPortal
  33. from .config import Config
  34. from . import puppet as pu, portal as po
  35. if TYPE_CHECKING:
  36. from .__main__ import InstagramBridge
  37. METRIC_MESSAGE = Summary("bridge_on_message", "calls to handle_message")
  38. METRIC_RTD = Summary("bridge_on_rtd", "calls to handle_rtd")
  39. METRIC_LOGGED_IN = Gauge("bridge_logged_in", "Users logged into the bridge")
  40. METRIC_CONNECTED = Gauge("bridge_connected", "Bridged users connected to Instagram")
  41. class User(DBUser, BaseUser):
  42. ig_base_log: TraceLogger = logging.getLogger("mau.instagram")
  43. _activity_indicator_ids: Dict[str, int] = {}
  44. by_mxid: Dict[UserID, 'User'] = {}
  45. by_igpk: Dict[int, 'User'] = {}
  46. config: Config
  47. az: AppService
  48. loop: asyncio.AbstractEventLoop
  49. client: Optional[AndroidAPI]
  50. mqtt: Optional[AndroidMQTT]
  51. _listen_task: Optional[asyncio.Task] = None
  52. permission_level: str
  53. username: Optional[str]
  54. _notice_room_lock: asyncio.Lock
  55. _notice_send_lock: asyncio.Lock
  56. _is_logged_in: bool
  57. def __init__(self, mxid: UserID, igpk: Optional[int] = None,
  58. state: Optional[AndroidState] = None, notice_room: Optional[RoomID] = None
  59. ) -> None:
  60. super().__init__(mxid=mxid, igpk=igpk, state=state, notice_room=notice_room)
  61. self._notice_room_lock = asyncio.Lock()
  62. self._notice_send_lock = asyncio.Lock()
  63. perms = self.config.get_permissions(mxid)
  64. self.is_whitelisted, self.is_admin, self.permission_level = perms
  65. self.log = self.log.getChild(self.mxid)
  66. self.client = None
  67. self.username = None
  68. self.dm_update_lock = asyncio.Lock()
  69. self._metric_value = defaultdict(lambda: False)
  70. self._is_logged_in = False
  71. self._listen_task = None
  72. self.command_status = None
  73. @classmethod
  74. def init_cls(cls, bridge: 'InstagramBridge') -> AsyncIterable[Awaitable[None]]:
  75. cls.bridge = bridge
  76. cls.config = bridge.config
  77. cls.az = bridge.az
  78. cls.loop = bridge.loop
  79. return (user.try_connect() async for user in cls.all_logged_in())
  80. # region Connection management
  81. async def is_logged_in(self) -> bool:
  82. return bool(self.client) and self._is_logged_in
  83. async def try_connect(self) -> None:
  84. try:
  85. await self.connect()
  86. except Exception:
  87. self.log.exception("Error while connecting to Instagram")
  88. async def connect(self) -> None:
  89. client = AndroidAPI(self.state, log=self.ig_base_log.getChild("http").getChild(self.mxid))
  90. try:
  91. resp = await client.current_user()
  92. except IGNotLoggedInError as e:
  93. self.log.warning(f"Failed to connect to Instagram: {e}")
  94. # TODO show reason?
  95. await self.send_bridge_notice("You have been logged out of Instagram")
  96. return
  97. self.client = client
  98. self._is_logged_in = True
  99. self.igpk = resp.user.pk
  100. self.username = resp.user.username
  101. self._track_metric(METRIC_LOGGED_IN, True)
  102. self.by_igpk[self.igpk] = self
  103. self.mqtt = AndroidMQTT(self.state, loop=self.loop,
  104. log=self.ig_base_log.getChild("mqtt").getChild(self.mxid))
  105. self.mqtt.add_event_handler(Connect, self.on_connect)
  106. self.mqtt.add_event_handler(Disconnect, self.on_disconnect)
  107. self.mqtt.add_event_handler(MessageSyncEvent, self.handle_message)
  108. self.mqtt.add_event_handler(RealtimeDirectEvent, self.handle_rtd)
  109. await self.update()
  110. self.loop.create_task(self._try_sync_puppet(resp.user))
  111. self.loop.create_task(self._try_sync())
  112. async def on_connect(self, evt: Connect) -> None:
  113. self.log.debug("Connected to Instagram")
  114. self._track_metric(METRIC_CONNECTED, True)
  115. async def on_disconnect(self, evt: Disconnect) -> None:
  116. self.log.debug("Disconnected from Instagram")
  117. self._track_metric(METRIC_CONNECTED, False)
  118. # TODO this stuff could probably be moved to mautrix-python
  119. async def get_notice_room(self) -> RoomID:
  120. if not self.notice_room:
  121. async with self._notice_room_lock:
  122. # If someone already created the room while this call was waiting,
  123. # don't make a new room
  124. if self.notice_room:
  125. return self.notice_room
  126. self.notice_room = await self.az.intent.create_room(
  127. is_direct=True, invitees=[self.mxid],
  128. topic="Instagram bridge notices")
  129. await self.update()
  130. return self.notice_room
  131. async def send_bridge_notice(self, text: str, edit: Optional[EventID] = None,
  132. important: bool = False) -> Optional[EventID]:
  133. event_id = None
  134. try:
  135. self.log.debug("Sending bridge notice: %s", text)
  136. content = TextMessageEventContent(body=text, msgtype=(MessageType.TEXT if important
  137. else MessageType.NOTICE))
  138. if edit:
  139. content.set_edit(edit)
  140. # This is locked to prevent notices going out in the wrong order
  141. async with self._notice_send_lock:
  142. event_id = await self.az.intent.send_message(await self.get_notice_room(), content)
  143. except Exception:
  144. self.log.warning("Failed to send bridge notice", exc_info=True)
  145. return edit or event_id
  146. async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
  147. puppet = await pu.Puppet.get_by_pk(self.igpk)
  148. try:
  149. await puppet.update_info(user_info, self)
  150. except Exception:
  151. self.log.exception("Failed to update own puppet info")
  152. try:
  153. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  154. self.log.info(f"Automatically enabling custom puppet")
  155. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  156. except Exception:
  157. self.log.exception("Failed to automatically enable custom puppet")
  158. async def _try_sync(self) -> None:
  159. try:
  160. await self.sync()
  161. except Exception:
  162. self.log.exception("Exception while syncing")
  163. async def get_direct_chats(self) -> Dict[UserID, List[RoomID]]:
  164. return {
  165. pu.Puppet.get_mxid_from_id(portal.other_user_pk): [portal.mxid]
  166. for portal in await DBPortal.find_private_chats_of(self.igpk)
  167. if portal.mxid
  168. }
  169. async def sync(self) -> None:
  170. resp = await self.client.get_inbox()
  171. limit = self.config["bridge.initial_conversation_sync"]
  172. threads = sorted(resp.inbox.threads, key=lambda thread: thread.last_activity_at)
  173. if limit < 0:
  174. limit = len(threads)
  175. for i, thread in enumerate(threads):
  176. portal = await po.Portal.get_by_thread(thread, self.igpk)
  177. if portal.mxid:
  178. await portal.update_matrix_room(self, thread, backfill=True)
  179. elif i < limit:
  180. await portal.create_matrix_room(self, thread)
  181. await self.update_direct_chats()
  182. self._listen_task = self.loop.create_task(self.mqtt.listen(
  183. graphql_subs={GraphQLSubscription.app_presence(),
  184. GraphQLSubscription.direct_typing(self.state.user_id),
  185. GraphQLSubscription.direct_status()},
  186. skywalker_subs={SkywalkerSubscription.direct_sub(self.state.user_id),
  187. SkywalkerSubscription.live_sub(self.state.user_id)},
  188. seq_id=resp.seq_id, snapshot_at_ms=resp.snapshot_at_ms))
  189. async def stop(self) -> None:
  190. if self.mqtt:
  191. self.mqtt.disconnect()
  192. self._track_metric(METRIC_CONNECTED, False)
  193. await self.update()
  194. async def logout(self) -> None:
  195. if self.mqtt:
  196. self.mqtt.disconnect()
  197. self._track_metric(METRIC_CONNECTED, False)
  198. self._track_metric(METRIC_LOGGED_IN, False)
  199. puppet = await pu.Puppet.get_by_pk(self.igpk, create=False)
  200. if puppet and puppet.is_real_user:
  201. await puppet.switch_mxid(None, None)
  202. try:
  203. del self.by_igpk[self.igpk]
  204. except KeyError:
  205. pass
  206. self.client = None
  207. self.mqtt = None
  208. self.state = None
  209. self._is_logged_in = False
  210. await self.update()
  211. # endregion
  212. # region Event handlers
  213. @async_time(METRIC_MESSAGE)
  214. async def handle_message(self, evt: MessageSyncEvent) -> None:
  215. portal = await po.Portal.get_by_thread_id(evt.message.thread_id, receiver=self.igpk)
  216. if not portal:
  217. # TODO try to find the thread?
  218. self.log.warning(f"Ignoring message to unknown thread {evt.message.thread_id}")
  219. return
  220. elif not portal.mxid:
  221. # TODO create portal room?
  222. self.log.warning(f"Ignoring message to thread with no room {evt.message.thread_id}")
  223. return
  224. self.log.trace(f"Received message sync event {evt.message}")
  225. sender = await pu.Puppet.get_by_pk(evt.message.user_id) if evt.message.user_id else None
  226. if evt.message.op == Operation.ADD:
  227. if not sender:
  228. # I don't think we care about adds with no sender
  229. return
  230. await portal.handle_instagram_item(self, sender, evt.message)
  231. elif evt.message.op == Operation.REMOVE:
  232. # Removes don't have a sender, only the message sender can unsend messages anyway
  233. await portal.handle_instagram_remove(evt.message.item_id)
  234. elif evt.message.op == Operation.REPLACE:
  235. await portal.handle_instagram_update(evt.message)
  236. @async_time(METRIC_RTD)
  237. async def handle_rtd(self, evt: RealtimeDirectEvent) -> None:
  238. if not isinstance(evt.value, ActivityIndicatorData):
  239. return
  240. now = int(time.time() * 1000)
  241. date = int(evt.value.timestamp) // 1000
  242. expiry = date + evt.value.ttl
  243. if expiry < now:
  244. return
  245. if evt.activity_indicator_id in self._activity_indicator_ids:
  246. return
  247. # TODO clear expired items from this dict
  248. self._activity_indicator_ids[evt.activity_indicator_id] = expiry
  249. puppet = await pu.Puppet.get_by_pk(int(evt.value.sender_id))
  250. portal = await po.Portal.get_by_thread_id(evt.thread_id, receiver=self.igpk)
  251. if not puppet or not portal:
  252. return
  253. is_typing = evt.value.activity_status != TypingStatus.OFF
  254. await puppet.intent_for(portal).set_typing(portal.mxid, is_typing=is_typing,
  255. timeout=evt.value.ttl)
  256. # endregion
  257. # region Database getters
  258. def _add_to_cache(self) -> None:
  259. self.by_mxid[self.mxid] = self
  260. if self.igpk:
  261. self.by_igpk[self.igpk] = self
  262. @classmethod
  263. async def get_by_mxid(cls, mxid: UserID, create: bool = True) -> Optional['User']:
  264. # Never allow ghosts to be users
  265. if pu.Puppet.get_id_from_mxid(mxid):
  266. return None
  267. try:
  268. return cls.by_mxid[mxid]
  269. except KeyError:
  270. pass
  271. user = cast(cls, await super().get_by_mxid(mxid))
  272. if user is not None:
  273. user._add_to_cache()
  274. return user
  275. if create:
  276. user = cls(mxid)
  277. await user.insert()
  278. user._add_to_cache()
  279. return user
  280. return None
  281. @classmethod
  282. async def get_by_igpk(cls, igpk: int) -> Optional['User']:
  283. try:
  284. return cls.by_igpk[igpk]
  285. except KeyError:
  286. pass
  287. user = cast(cls, await super().get_by_igpk(igpk))
  288. if user is not None:
  289. user._add_to_cache()
  290. return user
  291. return None
  292. @classmethod
  293. async def all_logged_in(cls) -> AsyncGenerator['User', None]:
  294. users = await super().all_logged_in()
  295. user: cls
  296. for index, user in enumerate(users):
  297. try:
  298. yield cls.by_mxid[user.mxid]
  299. except KeyError:
  300. user._add_to_cache()
  301. yield user
  302. # endregion