user.py 14 KB

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