user.py 23 KB

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