user.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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. IGChallengeError,
  24. IGCheckpointError,
  25. IGConsentRequiredError,
  26. IGNotLoggedInError,
  27. IGRateLimitError,
  28. IGUserIDNotFoundError,
  29. IrisSubscribeError,
  30. MQTTConnectionUnauthorized,
  31. MQTTNotConnected,
  32. MQTTNotLoggedIn,
  33. )
  34. from mauigpapi.mqtt import (
  35. Connect,
  36. Disconnect,
  37. GraphQLSubscription,
  38. NewSequenceID,
  39. SkywalkerSubscription,
  40. )
  41. from mauigpapi.types import (
  42. ActivityIndicatorData,
  43. CurrentUser,
  44. MessageSyncEvent,
  45. Operation,
  46. RealtimeDirectEvent,
  47. Thread,
  48. ThreadSyncEvent,
  49. TypingStatus,
  50. )
  51. from mautrix.appservice import AppService
  52. from mautrix.bridge import BaseUser, async_getter_lock
  53. from mautrix.types import EventID, MessageType, RoomID, TextMessageEventContent, UserID
  54. from mautrix.util.bridge_state import BridgeState, BridgeStateEvent
  55. from mautrix.util.logging import TraceLogger
  56. from mautrix.util.opt_prometheus import Gauge, Summary, async_time
  57. from . import portal as po, puppet as pu
  58. from .config import Config
  59. from .db import Portal as DBPortal, User as DBUser
  60. if TYPE_CHECKING:
  61. from .__main__ import InstagramBridge
  62. METRIC_MESSAGE = Summary("bridge_on_message", "calls to handle_message")
  63. METRIC_THREAD_SYNC = Summary("bridge_on_thread_sync", "calls to handle_thread_sync")
  64. METRIC_RTD = Summary("bridge_on_rtd", "calls to handle_rtd")
  65. METRIC_LOGGED_IN = Gauge("bridge_logged_in", "Users logged into the bridge")
  66. METRIC_CONNECTED = Gauge("bridge_connected", "Bridged users connected to Instagram")
  67. BridgeState.human_readable_errors.update(
  68. {
  69. "ig-connection-error": "Instagram disconnected unexpectedly",
  70. "ig-refresh-connection-error": "Reconnecting failed again after refresh: {message}",
  71. "ig-connection-fatal-error": "Instagram disconnected unexpectedly",
  72. "ig-auth-error": "Authentication error from Instagram: {message}",
  73. "ig-checkpoint": "Instagram checkpoint error. Please check the Instagram website.",
  74. "ig-consent-required": "Instagram requires a consent update. Please check the Instagram website.",
  75. "ig-checkpoint-locked": "Instagram checkpoint error. Please check the Instagram website.",
  76. "ig-rate-limit": "Got Instagram ratelimit error, waiting a few minutes before retrying...",
  77. "ig-disconnected": None,
  78. "ig-no-mqtt": "You're not connected to Instagram",
  79. "logged-out": "You're not logged into Instagram",
  80. }
  81. )
  82. class User(DBUser, BaseUser):
  83. ig_base_log: TraceLogger = logging.getLogger("mau.instagram")
  84. _activity_indicator_ids: dict[str, int] = {}
  85. by_mxid: dict[UserID, User] = {}
  86. by_igpk: dict[int, User] = {}
  87. config: Config
  88. az: AppService
  89. loop: asyncio.AbstractEventLoop
  90. client: AndroidAPI | None
  91. mqtt: AndroidMQTT | None
  92. _listen_task: asyncio.Task | None = None
  93. _seq_id_save_task: asyncio.Task | None
  94. permission_level: str
  95. username: str | None
  96. _notice_room_lock: asyncio.Lock
  97. _notice_send_lock: asyncio.Lock
  98. _is_logged_in: bool
  99. _is_connected: bool
  100. shutdown: bool
  101. remote_typing_status: TypingStatus | None
  102. def __init__(
  103. self,
  104. mxid: UserID,
  105. igpk: int | None = None,
  106. state: AndroidState | None = None,
  107. notice_room: RoomID | None = None,
  108. seq_id: int | None = None,
  109. snapshot_at_ms: int | None = None,
  110. ) -> None:
  111. super().__init__(
  112. mxid=mxid,
  113. igpk=igpk,
  114. state=state,
  115. notice_room=notice_room,
  116. seq_id=seq_id,
  117. snapshot_at_ms=snapshot_at_ms,
  118. )
  119. BaseUser.__init__(self)
  120. self._notice_room_lock = asyncio.Lock()
  121. self._notice_send_lock = asyncio.Lock()
  122. perms = self.config.get_permissions(mxid)
  123. self.relay_whitelisted, self.is_whitelisted, self.is_admin, self.permission_level = perms
  124. self.client = None
  125. self.mqtt = None
  126. self.username = None
  127. self._is_logged_in = False
  128. self._is_connected = False
  129. self._is_refreshing = False
  130. self.shutdown = False
  131. self._listen_task = None
  132. self.remote_typing_status = None
  133. self._seq_id_save_task = None
  134. @classmethod
  135. def init_cls(cls, bridge: "InstagramBridge") -> AsyncIterable[Awaitable[None]]:
  136. cls.bridge = bridge
  137. cls.config = bridge.config
  138. cls.az = bridge.az
  139. cls.loop = bridge.loop
  140. return (user.try_connect() async for user in cls.all_logged_in())
  141. # region Connection management
  142. async def is_logged_in(self) -> bool:
  143. return bool(self.client) and self._is_logged_in
  144. async def get_puppet(self) -> pu.Puppet | None:
  145. if not self.igpk:
  146. return None
  147. return await pu.Puppet.get_by_pk(self.igpk)
  148. async def get_portal_with(self, puppet: pu.Puppet, create: bool = True) -> po.Portal | None:
  149. if not self.igpk:
  150. return None
  151. portal = await po.Portal.find_private_chat(self.igpk, puppet.pk)
  152. if portal:
  153. return portal
  154. if create:
  155. # TODO add error handling somewhere
  156. thread = await self.client.create_group_thread([puppet.pk])
  157. portal = await po.Portal.get_by_thread(thread, self.igpk)
  158. await portal.update_info(thread, self)
  159. return portal
  160. return None
  161. async def try_connect(self) -> None:
  162. try:
  163. await self.connect()
  164. except Exception as e:
  165. self.log.exception("Error while connecting to Instagram")
  166. await self.push_bridge_state(
  167. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  168. )
  169. @property
  170. def api_log(self) -> TraceLogger:
  171. return self.ig_base_log.getChild("http").getChild(self.mxid)
  172. @property
  173. def is_connected(self) -> bool:
  174. return bool(self.client) and bool(self.mqtt) and self._is_connected
  175. async def connect(self, user: CurrentUser | None = None) -> None:
  176. if not self.state:
  177. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error="logged-out")
  178. return
  179. client = AndroidAPI(self.state, log=self.api_log)
  180. if not user:
  181. try:
  182. resp = await client.current_user()
  183. user = resp.user
  184. except IGNotLoggedInError as e:
  185. self.log.warning(f"Failed to connect to Instagram: {e}, logging out")
  186. await self.logout(error=e)
  187. return
  188. except IGCheckpointError as e:
  189. self.log.debug("Checkpoint error content: %s", e.body)
  190. raise
  191. except (IGChallengeError, IGConsentRequiredError) as e:
  192. await self._handle_checkpoint(e, on="connect", client=client)
  193. return
  194. self.client = client
  195. self._is_logged_in = True
  196. self.igpk = user.pk
  197. self.username = user.username
  198. await self.push_bridge_state(BridgeStateEvent.CONNECTING)
  199. self._track_metric(METRIC_LOGGED_IN, True)
  200. self.by_igpk[self.igpk] = self
  201. self.mqtt = AndroidMQTT(
  202. self.state, loop=self.loop, log=self.ig_base_log.getChild("mqtt").getChild(self.mxid)
  203. )
  204. self.mqtt.add_event_handler(Connect, self.on_connect)
  205. self.mqtt.add_event_handler(Disconnect, self.on_disconnect)
  206. self.mqtt.add_event_handler(NewSequenceID, self.update_seq_id)
  207. self.mqtt.add_event_handler(MessageSyncEvent, self.handle_message)
  208. self.mqtt.add_event_handler(ThreadSyncEvent, self.handle_thread_sync)
  209. self.mqtt.add_event_handler(RealtimeDirectEvent, self.handle_rtd)
  210. await self.update()
  211. self.loop.create_task(self._try_sync_puppet(user))
  212. if not self.seq_id or self.config["bridge.resync_on_startup"]:
  213. self.loop.create_task(self._try_sync())
  214. else:
  215. self.log.debug("Connecting to MQTT directly as resync_on_startup is false")
  216. self.start_listen()
  217. async def on_connect(self, evt: Connect) -> None:
  218. self.log.debug("Connected to Instagram")
  219. self._track_metric(METRIC_CONNECTED, True)
  220. self._is_connected = True
  221. await self.send_bridge_notice("Connected to Instagram")
  222. await self.push_bridge_state(BridgeStateEvent.CONNECTED)
  223. async def on_disconnect(self, evt: Disconnect) -> None:
  224. self.log.debug("Disconnected from Instagram")
  225. self._track_metric(METRIC_CONNECTED, False)
  226. self._is_connected = False
  227. # TODO this stuff could probably be moved to mautrix-python
  228. async def get_notice_room(self) -> RoomID:
  229. if not self.notice_room:
  230. async with self._notice_room_lock:
  231. # If someone already created the room while this call was waiting,
  232. # don't make a new room
  233. if self.notice_room:
  234. return self.notice_room
  235. creation_content = {}
  236. if not self.config["bridge.federate_rooms"]:
  237. creation_content["m.federate"] = False
  238. self.notice_room = await self.az.intent.create_room(
  239. is_direct=True,
  240. invitees=[self.mxid],
  241. topic="Instagram bridge notices",
  242. creation_content=creation_content,
  243. )
  244. await self.update()
  245. return self.notice_room
  246. async def fill_bridge_state(self, state: BridgeState) -> None:
  247. await super().fill_bridge_state(state)
  248. if not state.remote_id:
  249. if self.igpk:
  250. state.remote_id = str(self.igpk)
  251. else:
  252. try:
  253. state.remote_id = self.state.user_id
  254. except IGUserIDNotFoundError:
  255. state.remote_id = None
  256. if self.username:
  257. state.remote_name = f"@{self.username}"
  258. async def get_bridge_states(self) -> list[BridgeState]:
  259. if not self.state:
  260. return []
  261. state = BridgeState(state_event=BridgeStateEvent.UNKNOWN_ERROR)
  262. if self.is_connected:
  263. state.state_event = BridgeStateEvent.CONNECTED
  264. elif self._is_refreshing or self.mqtt:
  265. state.state_event = BridgeStateEvent.TRANSIENT_DISCONNECT
  266. return [state]
  267. async def send_bridge_notice(
  268. self,
  269. text: str,
  270. edit: EventID | None = None,
  271. state_event: BridgeStateEvent | None = None,
  272. important: bool = False,
  273. error_code: str | None = None,
  274. error_message: str | None = None,
  275. info: dict | None = None,
  276. ) -> EventID | None:
  277. if state_event:
  278. await self.push_bridge_state(
  279. state_event,
  280. error=error_code,
  281. message=error_message if error_code else text,
  282. info=info,
  283. )
  284. if self.config["bridge.disable_bridge_notices"]:
  285. return None
  286. if not important and not self.config["bridge.unimportant_bridge_notices"]:
  287. self.log.debug("Not sending unimportant bridge notice: %s", text)
  288. return None
  289. event_id = None
  290. try:
  291. self.log.debug("Sending bridge notice: %s", text)
  292. content = TextMessageEventContent(
  293. body=text, msgtype=(MessageType.TEXT if important else MessageType.NOTICE)
  294. )
  295. if edit:
  296. content.set_edit(edit)
  297. # This is locked to prevent notices going out in the wrong order
  298. async with self._notice_send_lock:
  299. event_id = await self.az.intent.send_message(await self.get_notice_room(), content)
  300. except Exception:
  301. self.log.warning("Failed to send bridge notice", exc_info=True)
  302. return edit or event_id
  303. async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
  304. puppet = await pu.Puppet.get_by_pk(self.igpk)
  305. try:
  306. await puppet.update_info(user_info, self)
  307. except Exception:
  308. self.log.exception("Failed to update own puppet info")
  309. try:
  310. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  311. self.log.info(f"Automatically enabling custom puppet")
  312. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  313. except Exception:
  314. self.log.exception("Failed to automatically enable custom puppet")
  315. async def _try_sync(self) -> None:
  316. try:
  317. await self.sync()
  318. except Exception as e:
  319. self.log.exception("Exception while syncing")
  320. if isinstance(e, IGCheckpointError):
  321. self.log.debug("Checkpoint error content: %s", e.body)
  322. await self.push_bridge_state(
  323. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  324. )
  325. async def get_direct_chats(self) -> dict[UserID, list[RoomID]]:
  326. return {
  327. pu.Puppet.get_mxid_from_id(portal.other_user_pk): [portal.mxid]
  328. for portal in await DBPortal.find_private_chats_of(self.igpk)
  329. if portal.mxid
  330. }
  331. async def refresh(self, resync: bool = True) -> None:
  332. self._is_refreshing = True
  333. try:
  334. await self.stop_listen()
  335. if resync:
  336. retry_count = 0
  337. minutes = 1
  338. while True:
  339. try:
  340. await self.sync()
  341. return
  342. except Exception as e:
  343. if retry_count >= 4 and minutes < 10:
  344. minutes += 1
  345. retry_count += 1
  346. s = "s" if minutes != 1 else ""
  347. self.log.exception(
  348. f"Error while syncing for refresh, retrying in {minutes} minute{s}"
  349. )
  350. if isinstance(e, IGCheckpointError):
  351. self.log.debug("Checkpoint error content: %s", e.body)
  352. await self.push_bridge_state(
  353. BridgeStateEvent.UNKNOWN_ERROR,
  354. error="unknown-error",
  355. message="An unknown error occurred while connecting to Instagram",
  356. info={"python_error": str(e)},
  357. )
  358. await asyncio.sleep(minutes * 60)
  359. else:
  360. self.start_listen()
  361. finally:
  362. self._is_refreshing = False
  363. async def _handle_checkpoint(
  364. self,
  365. e: IGChallengeError | IGConsentRequiredError,
  366. on: str,
  367. client: AndroidAPI | None = None,
  368. ) -> None:
  369. self.log.warning(f"Got checkpoint error on {on}: {e.body.serialize()}")
  370. client = client or self.client
  371. self.client = None
  372. self.mqtt = None
  373. if isinstance(e, IGConsentRequiredError):
  374. await self.push_bridge_state(
  375. BridgeStateEvent.BAD_CREDENTIALS,
  376. error="ig-consent-required",
  377. info=e.body.serialize(),
  378. )
  379. return
  380. error_code = "ig-checkpoint"
  381. try:
  382. resp = await client.challenge_reset()
  383. info = {
  384. "challenge_context": (
  385. resp.challenge_context.serialize() if resp.challenge_context_str else None
  386. ),
  387. "step_name": resp.step_name,
  388. "step_data": resp.step_data.serialize() if resp.step_data else None,
  389. "user_id": resp.user_id,
  390. "action": resp.action,
  391. "status": resp.status,
  392. "challenge": e.body.challenge.serialize() if e.body.challenge else None,
  393. }
  394. self.log.debug(f"Challenge state: {resp.serialize()}")
  395. if resp.challenge_context.challenge_type_enum == "HACKED_LOCK":
  396. error_code = "ig-checkpoint-locked"
  397. except Exception:
  398. self.log.exception("Error resetting challenge state")
  399. info = {"challenge": e.body.challenge.serialize() if e.body.challenge else None}
  400. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=error_code, info=info)
  401. async def _sync_thread(self, thread: Thread, allow_create: bool) -> None:
  402. portal = await po.Portal.get_by_thread(thread, self.igpk)
  403. if portal.mxid:
  404. self.log.debug(f"{thread.thread_id} has a portal, syncing and backfilling...")
  405. await portal.update_matrix_room(self, thread, backfill=True)
  406. elif allow_create:
  407. self.log.debug(f"{thread.thread_id} has been active recently, creating portal...")
  408. await portal.create_matrix_room(self, thread)
  409. else:
  410. self.log.debug(f"{thread.thread_id} is not active and doesn't have a portal")
  411. async def sync(self) -> None:
  412. sleep_minutes = 2
  413. while True:
  414. try:
  415. resp = await self.client.get_inbox()
  416. break
  417. except IGNotLoggedInError as e:
  418. self.log.exception("Got not logged in error while syncing")
  419. await self.logout(error=e)
  420. return
  421. except IGRateLimitError as e:
  422. self.log.error(
  423. "Got ratelimit error while trying to get inbox (%s), retrying in %d minutes",
  424. e.body,
  425. sleep_minutes,
  426. )
  427. await self.push_bridge_state(
  428. BridgeStateEvent.TRANSIENT_DISCONNECT, error="ig-rate-limit"
  429. )
  430. await asyncio.sleep(sleep_minutes * 60)
  431. sleep_minutes += 2
  432. except IGCheckpointError as e:
  433. self.log.debug("Checkpoint error content: %s", e.body)
  434. raise
  435. except (IGChallengeError, IGConsentRequiredError) as e:
  436. await self._handle_checkpoint(e, on="sync")
  437. return
  438. self.seq_id = resp.seq_id
  439. self.snapshot_at_ms = resp.snapshot_at_ms
  440. await self.save_seq_id()
  441. if not self._listen_task:
  442. self.start_listen(is_after_sync=True)
  443. max_age = self.config["bridge.portal_create_max_age"] * 1_000_000
  444. limit = self.config["bridge.chat_sync_limit"]
  445. create_limit = self.config["bridge.chat_create_limit"]
  446. min_active_at = (time.time() * 1_000_000) - max_age
  447. i = 0
  448. await self.push_bridge_state(BridgeStateEvent.BACKFILLING)
  449. async for thread in self.client.iter_inbox(start_at=resp):
  450. try:
  451. await self._sync_thread(
  452. thread=thread,
  453. allow_create=thread.last_activity_at > min_active_at and i < create_limit,
  454. )
  455. except Exception:
  456. self.log.exception(f"Error syncing thread {thread.thread_id}")
  457. i += 1
  458. if i >= limit:
  459. break
  460. try:
  461. await self.update_direct_chats()
  462. except Exception:
  463. self.log.exception("Error updating direct chat list")
  464. def start_listen(self, is_after_sync: bool = False) -> None:
  465. self.shutdown = False
  466. task = self._listen(
  467. seq_id=self.seq_id, snapshot_at_ms=self.snapshot_at_ms, is_after_sync=is_after_sync
  468. )
  469. self._listen_task = self.loop.create_task(task)
  470. async def fetch_user_and_reconnect(self) -> None:
  471. self.log.debug("Refetching current user after disconnection")
  472. try:
  473. resp = await self.client.current_user()
  474. except IGNotLoggedInError as e:
  475. self.log.warning(f"Failed to reconnect to Instagram: {e}, logging out")
  476. await self.logout(error=e)
  477. return
  478. except (IGChallengeError, IGConsentRequiredError) as e:
  479. await self._handle_checkpoint(e, on="reconnect")
  480. return
  481. except Exception as e:
  482. self.log.exception("Error while reconnecting to Instagram")
  483. if isinstance(e, IGCheckpointError):
  484. self.log.debug("Checkpoint error content: %s", e.body)
  485. await self.push_bridge_state(
  486. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  487. )
  488. return
  489. else:
  490. self.log.debug(f"Confirmed current user {resp.user.pk}")
  491. self.start_listen()
  492. async def _listen(self, seq_id: int, snapshot_at_ms: int, is_after_sync: bool) -> None:
  493. try:
  494. await self.mqtt.listen(
  495. graphql_subs={
  496. GraphQLSubscription.app_presence(),
  497. GraphQLSubscription.direct_typing(self.state.user_id),
  498. GraphQLSubscription.direct_status(),
  499. },
  500. skywalker_subs={
  501. SkywalkerSubscription.direct_sub(self.state.user_id),
  502. SkywalkerSubscription.live_sub(self.state.user_id),
  503. },
  504. seq_id=seq_id,
  505. snapshot_at_ms=snapshot_at_ms,
  506. )
  507. except IrisSubscribeError as e:
  508. if is_after_sync:
  509. self.log.exception("Got IrisSubscribeError right after refresh")
  510. await self.send_bridge_notice(
  511. f"Reconnecting failed again after refresh: {e}",
  512. important=True,
  513. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  514. error_code="ig-refresh-connection-error",
  515. error_message=str(e),
  516. info={"python_error": str(e)},
  517. )
  518. else:
  519. self.log.warning(f"Got IrisSubscribeError {e}, refreshing...")
  520. asyncio.create_task(self.refresh())
  521. except (MQTTNotConnected, MQTTNotLoggedIn, MQTTConnectionUnauthorized) as e:
  522. self.log.warning(f"Unexpected connection error: {e}")
  523. await self.send_bridge_notice(
  524. f"Error in listener: {e}",
  525. important=True,
  526. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  527. error_code="ig-connection-error",
  528. )
  529. self.mqtt.disconnect()
  530. asyncio.create_task(self.fetch_user_and_reconnect())
  531. except Exception as e:
  532. self.log.exception("Fatal error in listener")
  533. await self.send_bridge_notice(
  534. "Fatal error in listener (see logs for more info)",
  535. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  536. important=True,
  537. error_code="ig-unknown-connection-error",
  538. info={"python_error": str(e)},
  539. )
  540. self.mqtt.disconnect()
  541. else:
  542. if not self.shutdown:
  543. await self.send_bridge_notice(
  544. "Instagram connection closed without error",
  545. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  546. error_code="ig-disconnected",
  547. )
  548. finally:
  549. self._listen_task = None
  550. self._is_connected = False
  551. self._track_metric(METRIC_CONNECTED, False)
  552. async def stop_listen(self) -> None:
  553. if self.mqtt:
  554. self.shutdown = True
  555. self.mqtt.disconnect()
  556. if self._listen_task:
  557. await self._listen_task
  558. self.shutdown = False
  559. self._track_metric(METRIC_CONNECTED, False)
  560. self._is_connected = False
  561. await self.update()
  562. async def logout(self, error: IGNotLoggedInError | None = None) -> None:
  563. if self.client and error is None:
  564. try:
  565. await self.client.logout(one_tap_app_login=False)
  566. except Exception:
  567. self.log.debug("Exception logging out", exc_info=True)
  568. if self.mqtt:
  569. self.mqtt.disconnect()
  570. self._track_metric(METRIC_CONNECTED, False)
  571. self._track_metric(METRIC_LOGGED_IN, False)
  572. if error is None:
  573. await self.push_bridge_state(BridgeStateEvent.LOGGED_OUT)
  574. puppet = await pu.Puppet.get_by_pk(self.igpk, create=False)
  575. if puppet and puppet.is_real_user:
  576. await puppet.switch_mxid(None, None)
  577. try:
  578. del self.by_igpk[self.igpk]
  579. except KeyError:
  580. pass
  581. self.igpk = None
  582. else:
  583. self.log.debug("Auth error body: %s", error.body.serialize())
  584. await self.send_bridge_notice(
  585. f"You have been logged out of Instagram: {error.proper_message}",
  586. important=True,
  587. state_event=BridgeStateEvent.BAD_CREDENTIALS,
  588. error_code="ig-auth-error",
  589. error_message=error.proper_message,
  590. )
  591. self.client = None
  592. self.mqtt = None
  593. self.state = None
  594. self.seq_id = None
  595. self.snapshot_at_ms = None
  596. self._is_logged_in = False
  597. await self.update()
  598. # endregion
  599. # region Event handlers
  600. async def _save_seq_id_after_sleep(self) -> None:
  601. await asyncio.sleep(120)
  602. self._seq_id_save_task = None
  603. self.log.trace("Saving sequence ID %d/%d", self.seq_id, self.snapshot_at_ms)
  604. try:
  605. await self.save_seq_id()
  606. except Exception:
  607. self.log.exception("Error saving sequence ID")
  608. async def update_seq_id(self, evt: NewSequenceID) -> None:
  609. self.seq_id = evt.seq_id
  610. self.snapshot_at_ms = evt.snapshot_at_ms
  611. if not self._seq_id_save_task or self._seq_id_save_task.done():
  612. self.log.trace("Starting seq id save task (%d/%d)", evt.seq_id, evt.snapshot_at_ms)
  613. self._seq_id_save_task = asyncio.create_task(self._save_seq_id_after_sleep())
  614. else:
  615. self.log.trace("Not starting seq id save task (%d/%d)", evt.seq_id, evt.snapshot_at_ms)
  616. @async_time(METRIC_MESSAGE)
  617. async def handle_message(self, evt: MessageSyncEvent) -> None:
  618. portal = await po.Portal.get_by_thread_id(evt.message.thread_id, receiver=self.igpk)
  619. if not portal or not portal.mxid:
  620. self.log.debug("Got message in thread with no portal, getting info...")
  621. resp = await self.client.get_thread(evt.message.thread_id)
  622. portal = await po.Portal.get_by_thread(resp.thread, self.igpk)
  623. self.log.debug("Got info for unknown portal, creating room")
  624. await portal.create_matrix_room(self, resp.thread)
  625. if not portal.mxid:
  626. self.log.warning(
  627. "Room creation appears to have failed, "
  628. f"dropping message in {evt.message.thread_id}"
  629. )
  630. return
  631. self.log.trace(f"Received message sync event {evt.message}")
  632. await portal.backfill_lock.wait(f"{evt.message.op} {evt.message.item_id}")
  633. if evt.message.new_reaction:
  634. sender = await pu.Puppet.get_by_pk(evt.message.new_reaction.sender_id)
  635. await portal.handle_instagram_reaction(
  636. self, sender, evt.message, remove=evt.message.op == Operation.REMOVE
  637. )
  638. return
  639. sender = await pu.Puppet.get_by_pk(evt.message.user_id) if evt.message.user_id else None
  640. if evt.message.op == Operation.ADD:
  641. if not sender:
  642. # I don't think we care about adds with no sender
  643. return
  644. await portal.handle_instagram_item(self, sender, evt.message)
  645. elif evt.message.op == Operation.REMOVE:
  646. # Removes don't have a sender, only the message sender can unsend messages anyway
  647. await portal.handle_instagram_remove(evt.message.item_id)
  648. elif evt.message.op == Operation.REPLACE:
  649. await portal.handle_instagram_update(evt.message)
  650. @async_time(METRIC_THREAD_SYNC)
  651. async def handle_thread_sync(self, evt: ThreadSyncEvent) -> None:
  652. self.log.trace("Thread sync event content: %s", evt)
  653. portal = await po.Portal.get_by_thread(evt, receiver=self.igpk)
  654. if portal.mxid:
  655. self.log.debug("Got thread sync event for %s with existing portal", portal.thread_id)
  656. await portal.update_matrix_room(self, evt)
  657. elif evt.is_group:
  658. self.log.debug(
  659. "Got thread sync event for group %s without existing portal, creating room",
  660. portal.thread_id,
  661. )
  662. await portal.create_matrix_room(self, evt)
  663. else:
  664. self.log.debug(
  665. "Got thread sync event for DM %s without existing portal, ignoring",
  666. portal.thread_id,
  667. )
  668. @async_time(METRIC_RTD)
  669. async def handle_rtd(self, evt: RealtimeDirectEvent) -> None:
  670. if not isinstance(evt.value, ActivityIndicatorData):
  671. return
  672. now = int(time.time() * 1000)
  673. date = evt.value.timestamp_ms
  674. expiry = date + evt.value.ttl
  675. if expiry < now:
  676. return
  677. if evt.activity_indicator_id in self._activity_indicator_ids:
  678. return
  679. # TODO clear expired items from this dict
  680. self._activity_indicator_ids[evt.activity_indicator_id] = expiry
  681. puppet = await pu.Puppet.get_by_pk(int(evt.value.sender_id))
  682. portal = await po.Portal.get_by_thread_id(evt.thread_id, receiver=self.igpk)
  683. if not puppet or not portal or not portal.mxid:
  684. return
  685. is_typing = evt.value.activity_status != TypingStatus.OFF
  686. if puppet.pk == self.igpk:
  687. self.remote_typing_status = TypingStatus.TEXT if is_typing else TypingStatus.OFF
  688. await puppet.intent_for(portal).set_typing(
  689. portal.mxid, is_typing=is_typing, timeout=evt.value.ttl
  690. )
  691. # endregion
  692. # region Database getters
  693. def _add_to_cache(self) -> None:
  694. self.by_mxid[self.mxid] = self
  695. if self.igpk:
  696. self.by_igpk[self.igpk] = self
  697. @classmethod
  698. @async_getter_lock
  699. async def get_by_mxid(cls, mxid: UserID, *, create: bool = True) -> User | None:
  700. # Never allow ghosts to be users
  701. if pu.Puppet.get_id_from_mxid(mxid):
  702. return None
  703. try:
  704. return cls.by_mxid[mxid]
  705. except KeyError:
  706. pass
  707. user = cast(cls, await super().get_by_mxid(mxid))
  708. if user is not None:
  709. user._add_to_cache()
  710. return user
  711. if create:
  712. user = cls(mxid)
  713. await user.insert()
  714. user._add_to_cache()
  715. return user
  716. return None
  717. @classmethod
  718. @async_getter_lock
  719. async def get_by_igpk(cls, igpk: int) -> User | None:
  720. try:
  721. return cls.by_igpk[igpk]
  722. except KeyError:
  723. pass
  724. user = cast(cls, await super().get_by_igpk(igpk))
  725. if user is not None:
  726. user._add_to_cache()
  727. return user
  728. return None
  729. @classmethod
  730. async def all_logged_in(cls) -> AsyncGenerator[User, None]:
  731. users = await super().all_logged_in()
  732. user: cls
  733. for index, user in enumerate(users):
  734. try:
  735. yield cls.by_mxid[user.mxid]
  736. except KeyError:
  737. user._add_to_cache()
  738. yield user
  739. # endregion