user.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. import asyncio
  19. import logging
  20. import time
  21. from mauigpapi import AndroidAPI, AndroidState, AndroidMQTT
  22. from mauigpapi.mqtt import Connect, Disconnect, GraphQLSubscription, SkywalkerSubscription
  23. from mauigpapi.types import (CurrentUser, MessageSyncEvent, Operation, RealtimeDirectEvent,
  24. ActivityIndicatorData, TypingStatus, ThreadSyncEvent, Thread)
  25. from mauigpapi.errors import (IGNotLoggedInError, MQTTNotLoggedIn, MQTTNotConnected,
  26. IrisSubscribeError)
  27. from mautrix.bridge import BaseUser, BridgeState, async_getter_lock
  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_THREAD_SYNC = Summary("bridge_on_thread_sync", "calls to handle_thread_sync")
  39. METRIC_RTD = Summary("bridge_on_rtd", "calls to handle_rtd")
  40. METRIC_LOGGED_IN = Gauge("bridge_logged_in", "Users logged into the bridge")
  41. METRIC_CONNECTED = Gauge("bridge_connected", "Bridged users connected to Instagram")
  42. BridgeState.human_readable_errors.update({
  43. "ig-connection-error": "Instagram disconnected unexpectedly",
  44. "ig-auth-error": "Authentication error from Instagram: {message}",
  45. "ig-disconnected": None,
  46. "ig-no-mqtt": "You're not connected to Instagram",
  47. "logged-out": "You're not logged into Instagram",
  48. })
  49. class User(DBUser, BaseUser):
  50. ig_base_log: TraceLogger = logging.getLogger("mau.instagram")
  51. _activity_indicator_ids: Dict[str, int] = {}
  52. by_mxid: Dict[UserID, 'User'] = {}
  53. by_igpk: Dict[int, 'User'] = {}
  54. config: Config
  55. az: AppService
  56. loop: asyncio.AbstractEventLoop
  57. client: Optional[AndroidAPI]
  58. mqtt: Optional[AndroidMQTT]
  59. _listen_task: Optional[asyncio.Task] = None
  60. permission_level: str
  61. username: Optional[str]
  62. _notice_room_lock: asyncio.Lock
  63. _notice_send_lock: asyncio.Lock
  64. _is_logged_in: bool
  65. _is_connected: bool
  66. shutdown: bool
  67. remote_typing_status: Optional[TypingStatus]
  68. def __init__(self, mxid: UserID, igpk: Optional[int] = None,
  69. state: Optional[AndroidState] = None, notice_room: Optional[RoomID] = None
  70. ) -> None:
  71. super().__init__(mxid=mxid, igpk=igpk, state=state, notice_room=notice_room)
  72. BaseUser.__init__(self)
  73. self._notice_room_lock = asyncio.Lock()
  74. self._notice_send_lock = asyncio.Lock()
  75. perms = self.config.get_permissions(mxid)
  76. self.is_whitelisted, self.is_admin, self.permission_level = perms
  77. self.client = None
  78. self.mqtt = None
  79. self.username = None
  80. self._is_logged_in = False
  81. self._is_connected = False
  82. self.shutdown = False
  83. self._listen_task = None
  84. self.remote_typing_status = None
  85. @classmethod
  86. def init_cls(cls, bridge: 'InstagramBridge') -> AsyncIterable[Awaitable[None]]:
  87. cls.bridge = bridge
  88. cls.config = bridge.config
  89. cls.az = bridge.az
  90. cls.loop = bridge.loop
  91. return (user.try_connect() async for user in cls.all_logged_in())
  92. # region Connection management
  93. async def is_logged_in(self) -> bool:
  94. return bool(self.client) and self._is_logged_in
  95. async def try_connect(self) -> None:
  96. try:
  97. await self.connect()
  98. except Exception:
  99. self.log.exception("Error while connecting to Instagram")
  100. @property
  101. def api_log(self) -> TraceLogger:
  102. return self.ig_base_log.getChild("http").getChild(self.mxid)
  103. @property
  104. def is_connected(self) -> bool:
  105. return bool(self.client) and bool(self.mqtt) and self._is_connected
  106. async def connect(self) -> None:
  107. client = AndroidAPI(self.state, log=self.api_log)
  108. try:
  109. resp = await client.current_user()
  110. except IGNotLoggedInError as e:
  111. self.log.warning(f"Failed to connect to Instagram: {e}, logging out")
  112. await self.send_bridge_notice(f"You have been logged out of Instagram: {e!s}",
  113. important=True, error_code="ig-auth-error",
  114. error_message=str(e))
  115. await self.logout(from_error=True)
  116. return
  117. self.client = client
  118. self._is_logged_in = True
  119. self.igpk = resp.user.pk
  120. self.username = resp.user.username
  121. self._track_metric(METRIC_LOGGED_IN, True)
  122. self.by_igpk[self.igpk] = self
  123. self.mqtt = AndroidMQTT(self.state, loop=self.loop,
  124. log=self.ig_base_log.getChild("mqtt").getChild(self.mxid))
  125. self.mqtt.add_event_handler(Connect, self.on_connect)
  126. self.mqtt.add_event_handler(Disconnect, self.on_disconnect)
  127. self.mqtt.add_event_handler(MessageSyncEvent, self.handle_message)
  128. self.mqtt.add_event_handler(ThreadSyncEvent, self.handle_thread_sync)
  129. self.mqtt.add_event_handler(RealtimeDirectEvent, self.handle_rtd)
  130. await self.update()
  131. self.loop.create_task(self._try_sync_puppet(resp.user))
  132. self.loop.create_task(self._try_sync())
  133. async def on_connect(self, evt: Connect) -> None:
  134. self.log.debug("Connected to Instagram")
  135. self._track_metric(METRIC_CONNECTED, True)
  136. self._is_connected = True
  137. await self.send_bridge_notice("Connected to Instagram")
  138. await self.push_bridge_state(ok=True)
  139. async def on_disconnect(self, evt: Disconnect) -> None:
  140. self.log.debug("Disconnected from Instagram")
  141. self._track_metric(METRIC_CONNECTED, False)
  142. self._is_connected = False
  143. # TODO this stuff could probably be moved to mautrix-python
  144. async def get_notice_room(self) -> RoomID:
  145. if not self.notice_room:
  146. async with self._notice_room_lock:
  147. # If someone already created the room while this call was waiting,
  148. # don't make a new room
  149. if self.notice_room:
  150. return self.notice_room
  151. self.notice_room = await self.az.intent.create_room(
  152. is_direct=True, invitees=[self.mxid],
  153. topic="Instagram bridge notices")
  154. await self.update()
  155. return self.notice_room
  156. async def fill_bridge_state(self, state: BridgeState) -> None:
  157. await super().fill_bridge_state(state)
  158. state.remote_id = str(self.igpk)
  159. state.remote_name = f"@{self.username}"
  160. async def get_bridge_state(self) -> BridgeState:
  161. if not self.client:
  162. return BridgeState(ok=False, error="logged-out")
  163. elif not self._listen_task or self._listen_task.done() or not self.is_connected:
  164. return BridgeState(ok=False, error="ig-no-mqtt")
  165. return BridgeState(ok=True)
  166. async def send_bridge_notice(self, text: str, edit: Optional[EventID] = None,
  167. important: bool = False, error_code: Optional[str] = None,
  168. error_message: Optional[str] = None) -> Optional[EventID]:
  169. if error_code:
  170. await self.push_bridge_state(ok=False, error=error_code, message=error_message)
  171. if self.config["bridge.disable_bridge_notices"]:
  172. return None
  173. if not important and not self.config["bridge.unimportant_bridge_notices"]:
  174. self.log.debug("Not sending unimportant bridge notice: %s", text)
  175. return None
  176. event_id = None
  177. try:
  178. self.log.debug("Sending bridge notice: %s", text)
  179. content = TextMessageEventContent(body=text, msgtype=(MessageType.TEXT if important
  180. else MessageType.NOTICE))
  181. if edit:
  182. content.set_edit(edit)
  183. # This is locked to prevent notices going out in the wrong order
  184. async with self._notice_send_lock:
  185. event_id = await self.az.intent.send_message(await self.get_notice_room(), content)
  186. except Exception:
  187. self.log.warning("Failed to send bridge notice", exc_info=True)
  188. return edit or event_id
  189. async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
  190. puppet = await pu.Puppet.get_by_pk(self.igpk)
  191. try:
  192. await puppet.update_info(user_info, self)
  193. except Exception:
  194. self.log.exception("Failed to update own puppet info")
  195. try:
  196. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  197. self.log.info(f"Automatically enabling custom puppet")
  198. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  199. except Exception:
  200. self.log.exception("Failed to automatically enable custom puppet")
  201. async def _try_sync(self) -> None:
  202. try:
  203. await self.sync()
  204. except Exception:
  205. self.log.exception("Exception while syncing")
  206. async def get_direct_chats(self) -> Dict[UserID, List[RoomID]]:
  207. return {
  208. pu.Puppet.get_mxid_from_id(portal.other_user_pk): [portal.mxid]
  209. for portal in await DBPortal.find_private_chats_of(self.igpk)
  210. if portal.mxid
  211. }
  212. async def refresh(self, resync: bool = True) -> None:
  213. await self.stop_listen()
  214. if resync:
  215. retry_count = 0
  216. while True:
  217. try:
  218. await self.sync()
  219. return
  220. except Exception:
  221. if retry_count >= 4:
  222. raise
  223. retry_count += 1
  224. self.log.exception("Error while syncing for refresh, retrying in 1 minute")
  225. await asyncio.sleep(60)
  226. else:
  227. await self.start_listen()
  228. async def _sync_thread(self, thread: Thread, min_active_at: int) -> None:
  229. portal = await po.Portal.get_by_thread(thread, self.igpk)
  230. if portal.mxid:
  231. self.log.debug(f"{thread.thread_id} has a portal, syncing and backfilling...")
  232. await portal.update_matrix_room(self, thread, backfill=True)
  233. elif thread.last_activity_at > min_active_at:
  234. self.log.debug(f"{thread.thread_id} has been active recently, creating portal...")
  235. await portal.create_matrix_room(self, thread)
  236. else:
  237. self.log.debug(f"{thread.thread_id} is not active and doesn't have a portal")
  238. async def sync(self) -> None:
  239. resp = await self.client.get_inbox()
  240. max_age = self.config["bridge.portal_create_max_age"] * 1_000_000
  241. limit = self.config["bridge.chat_sync_limit"]
  242. min_active_at = (time.time() * 1_000_000) - max_age
  243. i = 0
  244. async for thread in self.client.iter_inbox(start_at=resp):
  245. try:
  246. await self._sync_thread(thread, min_active_at)
  247. except Exception:
  248. self.log.exception(f"Error syncing thread {thread.thread_id}")
  249. i += 1
  250. if i >= limit:
  251. break
  252. try:
  253. await self.update_direct_chats()
  254. except Exception:
  255. self.log.exception("Error updating direct chat list")
  256. if not self._listen_task:
  257. await self.start_listen(resp.seq_id, resp.snapshot_at_ms)
  258. async def start_listen(self, seq_id: Optional[int] = None, snapshot_at_ms: Optional[int] = None
  259. ) -> None:
  260. self.shutdown = False
  261. if not seq_id:
  262. resp = await self.client.get_inbox(limit=1)
  263. seq_id, snapshot_at_ms = resp.seq_id, resp.snapshot_at_ms
  264. task = self.listen(seq_id=seq_id, snapshot_at_ms=snapshot_at_ms)
  265. self._listen_task = self.loop.create_task(task)
  266. async def listen(self, seq_id: int, snapshot_at_ms: int) -> None:
  267. try:
  268. await self.mqtt.listen(
  269. graphql_subs={GraphQLSubscription.app_presence(),
  270. GraphQLSubscription.direct_typing(self.state.user_id),
  271. GraphQLSubscription.direct_status()},
  272. skywalker_subs={SkywalkerSubscription.direct_sub(self.state.user_id),
  273. SkywalkerSubscription.live_sub(self.state.user_id)},
  274. seq_id=seq_id, snapshot_at_ms=snapshot_at_ms)
  275. except IrisSubscribeError as e:
  276. self.log.warning(f"Got IrisSubscribeError {e}, refreshing...")
  277. await self.refresh()
  278. except (MQTTNotConnected, MQTTNotLoggedIn) as e:
  279. await self.send_bridge_notice(f"Error in listener: {e}", important=True,
  280. error_code="ig-connection-error")
  281. self.mqtt.disconnect()
  282. except Exception:
  283. self.log.exception("Fatal error in listener")
  284. await self.send_bridge_notice("Fatal error in listener (see logs for more info)",
  285. important=True, error_code="ig-connection-error")
  286. self.mqtt.disconnect()
  287. else:
  288. if not self.shutdown:
  289. await self.send_bridge_notice("Instagram connection closed without error",
  290. error_code="ig-disconnected")
  291. finally:
  292. self._listen_task = None
  293. self._is_connected = False
  294. self._track_metric(METRIC_CONNECTED, False)
  295. async def stop_listen(self) -> None:
  296. if self.mqtt:
  297. self.shutdown = True
  298. self.mqtt.disconnect()
  299. if self._listen_task:
  300. await self._listen_task
  301. self.shutdown = False
  302. self._track_metric(METRIC_CONNECTED, False)
  303. self._is_connected = False
  304. await self.update()
  305. async def logout(self, from_error: bool = False) -> None:
  306. if self.client:
  307. try:
  308. await self.client.logout(one_tap_app_login=False)
  309. except Exception:
  310. self.log.debug("Exception logging out", exc_info=True)
  311. if self.mqtt:
  312. self.mqtt.disconnect()
  313. self._track_metric(METRIC_CONNECTED, False)
  314. self._track_metric(METRIC_LOGGED_IN, False)
  315. if not from_error:
  316. puppet = await pu.Puppet.get_by_pk(self.igpk, create=False)
  317. if puppet and puppet.is_real_user:
  318. await puppet.switch_mxid(None, None)
  319. try:
  320. del self.by_igpk[self.igpk]
  321. except KeyError:
  322. pass
  323. self.igpk = None
  324. else:
  325. await self.push_bridge_state(ok=False, error="logged-out")
  326. self.client = None
  327. self.mqtt = None
  328. self.state = None
  329. self._is_logged_in = False
  330. await self.update()
  331. # endregion
  332. # region Event handlers
  333. @async_time(METRIC_MESSAGE)
  334. async def handle_message(self, evt: MessageSyncEvent) -> None:
  335. portal = await po.Portal.get_by_thread_id(evt.message.thread_id, receiver=self.igpk)
  336. if not portal or not portal.mxid:
  337. self.log.debug("Got message in thread with no portal, getting info...")
  338. resp = await self.client.get_thread(evt.message.thread_id)
  339. portal = await po.Portal.get_by_thread(resp.thread, self.igpk)
  340. self.log.debug("Got info for unknown portal, creating room")
  341. await portal.create_matrix_room(self, resp.thread)
  342. if not portal.mxid:
  343. self.log.warning("Room creation appears to have failed, "
  344. f"dropping message in {evt.message.thread_id}")
  345. return
  346. self.log.trace(f"Received message sync event {evt.message}")
  347. sender = await pu.Puppet.get_by_pk(evt.message.user_id) if evt.message.user_id else None
  348. if evt.message.op == Operation.ADD:
  349. if not sender:
  350. # I don't think we care about adds with no sender
  351. return
  352. await portal.handle_instagram_item(self, sender, evt.message)
  353. elif evt.message.op == Operation.REMOVE:
  354. # Removes don't have a sender, only the message sender can unsend messages anyway
  355. await portal.handle_instagram_remove(evt.message.item_id)
  356. elif evt.message.op == Operation.REPLACE:
  357. await portal.handle_instagram_update(evt.message)
  358. @async_time(METRIC_THREAD_SYNC)
  359. async def handle_thread_sync(self, evt: ThreadSyncEvent) -> None:
  360. self.log.trace("Received thread sync event %s", evt)
  361. portal = await po.Portal.get_by_thread(evt, receiver=self.igpk)
  362. await portal.create_matrix_room(self, evt)
  363. @async_time(METRIC_RTD)
  364. async def handle_rtd(self, evt: RealtimeDirectEvent) -> None:
  365. if not isinstance(evt.value, ActivityIndicatorData):
  366. return
  367. now = int(time.time() * 1000)
  368. date = int(evt.value.timestamp) // 1000
  369. expiry = date + evt.value.ttl
  370. if expiry < now:
  371. return
  372. if evt.activity_indicator_id in self._activity_indicator_ids:
  373. return
  374. # TODO clear expired items from this dict
  375. self._activity_indicator_ids[evt.activity_indicator_id] = expiry
  376. puppet = await pu.Puppet.get_by_pk(int(evt.value.sender_id))
  377. portal = await po.Portal.get_by_thread_id(evt.thread_id, receiver=self.igpk)
  378. if not puppet or not portal or not portal.mxid:
  379. return
  380. is_typing = evt.value.activity_status != TypingStatus.OFF
  381. if puppet.pk == self.igpk:
  382. self.remote_typing_status = TypingStatus.TEXT if is_typing else TypingStatus.OFF
  383. await puppet.intent_for(portal).set_typing(portal.mxid, is_typing=is_typing,
  384. timeout=evt.value.ttl)
  385. # endregion
  386. # region Database getters
  387. def _add_to_cache(self) -> None:
  388. self.by_mxid[self.mxid] = self
  389. if self.igpk:
  390. self.by_igpk[self.igpk] = self
  391. @classmethod
  392. @async_getter_lock
  393. async def get_by_mxid(cls, mxid: UserID, *, create: bool = True) -> Optional['User']:
  394. # Never allow ghosts to be users
  395. if pu.Puppet.get_id_from_mxid(mxid):
  396. return None
  397. try:
  398. return cls.by_mxid[mxid]
  399. except KeyError:
  400. pass
  401. user = cast(cls, await super().get_by_mxid(mxid))
  402. if user is not None:
  403. user._add_to_cache()
  404. return user
  405. if create:
  406. user = cls(mxid)
  407. await user.insert()
  408. user._add_to_cache()
  409. return user
  410. return None
  411. @classmethod
  412. @async_getter_lock
  413. async def get_by_igpk(cls, igpk: int) -> Optional['User']:
  414. try:
  415. return cls.by_igpk[igpk]
  416. except KeyError:
  417. pass
  418. user = cast(cls, await super().get_by_igpk(igpk))
  419. if user is not None:
  420. user._add_to_cache()
  421. return user
  422. return None
  423. @classmethod
  424. async def all_logged_in(cls) -> AsyncGenerator['User', None]:
  425. users = await super().all_logged_in()
  426. user: cls
  427. for index, user in enumerate(users):
  428. try:
  429. yield cls.by_mxid[user.mxid]
  430. except KeyError:
  431. user._add_to_cache()
  432. yield user
  433. # endregion