user.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2023 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, Callable, cast
  18. from datetime import datetime, timedelta
  19. from functools import partial
  20. import asyncio
  21. import logging
  22. import time
  23. from mauigpapi import AndroidAPI, AndroidMQTT, AndroidState
  24. from mauigpapi.errors import (
  25. IGChallengeError,
  26. IGCheckpointError,
  27. IGConsentRequiredError,
  28. IGNotLoggedInError,
  29. IGRateLimitError,
  30. IGUnknownError,
  31. IGUserIDNotFoundError,
  32. IrisSubscribeError,
  33. MQTTConnectionUnauthorized,
  34. MQTTNotConnected,
  35. MQTTNotLoggedIn,
  36. MQTTReconnectionError,
  37. )
  38. from mauigpapi.mqtt import (
  39. Connect,
  40. Disconnect,
  41. GraphQLSubscription,
  42. NewSequenceID,
  43. ProxyUpdate,
  44. SkywalkerSubscription,
  45. )
  46. from mauigpapi.types import (
  47. ActivityIndicatorData,
  48. CurrentUser,
  49. MessageSyncEvent,
  50. Operation,
  51. RealtimeDirectEvent,
  52. Thread,
  53. ThreadRemoveEvent,
  54. ThreadSyncEvent,
  55. TypingStatus,
  56. )
  57. from mauigpapi.types.direct_inbox import DMInbox, DMInboxResponse
  58. from mautrix.appservice import AppService
  59. from mautrix.bridge import BaseUser, async_getter_lock
  60. from mautrix.types import EventID, MessageType, RoomID, TextMessageEventContent, UserID
  61. from mautrix.util import background_task
  62. from mautrix.util.bridge_state import BridgeState, BridgeStateEvent
  63. from mautrix.util.logging import TraceLogger
  64. from mautrix.util.opt_prometheus import Gauge, Summary, async_time
  65. from mautrix.util.proxy import RETRYABLE_PROXY_EXCEPTIONS, ProxyHandler
  66. from mautrix.util.simple_lock import SimpleLock
  67. from . import portal as po, puppet as pu
  68. from .config import Config
  69. from .db import Backfill, Message as DBMessage, Portal as DBPortal, User as DBUser
  70. if TYPE_CHECKING:
  71. from .__main__ import InstagramBridge
  72. METRIC_MESSAGE = Summary("bridge_on_message", "calls to handle_message")
  73. METRIC_THREAD_SYNC = Summary("bridge_on_thread_sync", "calls to handle_thread_sync")
  74. METRIC_RTD = Summary("bridge_on_rtd", "calls to handle_rtd")
  75. METRIC_LOGGED_IN = Gauge("bridge_logged_in", "Users logged into the bridge")
  76. METRIC_CONNECTED = Gauge("bridge_connected", "Bridged users connected to Instagram")
  77. BridgeState.human_readable_errors.update(
  78. {
  79. "ig-connection-error": "Instagram disconnected unexpectedly",
  80. "ig-refresh-connection-error": "Reconnecting failed again after refresh: {message}",
  81. "ig-connection-fatal-error": "Instagram disconnected unexpectedly",
  82. "ig-auth-error": "Authentication error from Instagram: {message}, please login again to continue",
  83. "ig-checkpoint": "Instagram checkpoint error. Please check the Instagram website.",
  84. "ig-consent-required": "Instagram requires a consent update. Please check the Instagram website.",
  85. "ig-checkpoint-locked": "Instagram checkpoint error. Please check the Instagram website.",
  86. "ig-rate-limit": "Got Instagram ratelimit error, waiting a few minutes before retrying...",
  87. "ig-disconnected": None,
  88. "logged-out": "You've been logged out of instagram, please login again to continue",
  89. }
  90. )
  91. class User(DBUser, BaseUser):
  92. ig_base_log: TraceLogger = logging.getLogger("mau.instagram")
  93. _activity_indicator_ids: dict[str, int] = {}
  94. by_mxid: dict[UserID, User] = {}
  95. by_igpk: dict[int, User] = {}
  96. config: Config
  97. az: AppService
  98. loop: asyncio.AbstractEventLoop
  99. client: AndroidAPI | None
  100. mqtt: AndroidMQTT | None
  101. _listen_task: asyncio.Task | None = None
  102. _sync_lock: SimpleLock
  103. _backfill_loop_task: asyncio.Task | None
  104. _thread_sync_task: asyncio.Task | None
  105. _seq_id_save_task: asyncio.Task | None
  106. permission_level: str
  107. username: str | None
  108. _notice_room_lock: asyncio.Lock
  109. _notice_send_lock: asyncio.Lock
  110. _is_logged_in: bool
  111. _is_connected: bool
  112. shutdown: bool
  113. remote_typing_status: TypingStatus | None
  114. def __init__(
  115. self,
  116. mxid: UserID,
  117. igpk: int | None = None,
  118. state: AndroidState | None = None,
  119. notice_room: RoomID | None = None,
  120. seq_id: int | None = None,
  121. snapshot_at_ms: int | None = None,
  122. oldest_cursor: str | None = None,
  123. total_backfilled_portals: int | None = None,
  124. thread_sync_completed: bool = False,
  125. ) -> None:
  126. super().__init__(
  127. mxid=mxid,
  128. igpk=igpk,
  129. state=state,
  130. notice_room=notice_room,
  131. seq_id=seq_id,
  132. snapshot_at_ms=snapshot_at_ms,
  133. oldest_cursor=oldest_cursor,
  134. total_backfilled_portals=total_backfilled_portals,
  135. thread_sync_completed=thread_sync_completed,
  136. )
  137. BaseUser.__init__(self)
  138. self._notice_room_lock = asyncio.Lock()
  139. self._notice_send_lock = asyncio.Lock()
  140. perms = self.config.get_permissions(mxid)
  141. self.relay_whitelisted, self.is_whitelisted, self.is_admin, self.permission_level = perms
  142. self.client = None
  143. self.mqtt = None
  144. self.username = None
  145. self._is_logged_in = False
  146. self._is_connected = False
  147. self._is_refreshing = False
  148. self.shutdown = False
  149. self._sync_lock = SimpleLock(
  150. "Waiting for thread sync to finish before handling %s", log=self.log
  151. )
  152. self._listen_task = None
  153. self._thread_sync_task = None
  154. self._backfill_loop_task = None
  155. self.remote_typing_status = None
  156. self._seq_id_save_task = None
  157. self.proxy_handler = ProxyHandler(
  158. api_url=self.config["bridge.get_proxy_api_url"],
  159. )
  160. @classmethod
  161. def init_cls(cls, bridge: "InstagramBridge") -> AsyncIterable[Awaitable[None]]:
  162. cls.bridge = bridge
  163. cls.config = bridge.config
  164. cls.az = bridge.az
  165. cls.loop = bridge.loop
  166. return (user.try_connect() async for user in cls.all_logged_in())
  167. # region Connection management
  168. async def is_logged_in(self) -> bool:
  169. return bool(self.client) and self._is_logged_in
  170. async def get_puppet(self) -> pu.Puppet | None:
  171. if not self.igpk:
  172. return None
  173. return await pu.Puppet.get_by_pk(self.igpk)
  174. async def get_portal_with(self, puppet: pu.Puppet, create: bool = True) -> po.Portal | None:
  175. if not self.igpk:
  176. return None
  177. portal = await po.Portal.find_private_chat(self.igpk, puppet.pk)
  178. if portal:
  179. return portal
  180. if create:
  181. # TODO add error handling somewhere
  182. thread = await self.client.create_group_thread([puppet.pk])
  183. portal = await po.Portal.get_by_thread(thread, self.igpk)
  184. await portal.update_info(thread, self)
  185. return portal
  186. return None
  187. async def try_connect(self) -> None:
  188. while True:
  189. try:
  190. await self.connect()
  191. except RETRYABLE_PROXY_EXCEPTIONS as e:
  192. # These are retried by the client up to 10 times, but we actually want to retry
  193. # these indefinitely so we capture them here again and retry.
  194. self.log.warning(
  195. f"Proxy error connecting to Instagram: {e}, retrying in 1 minute",
  196. )
  197. await asyncio.sleep(60)
  198. continue
  199. except Exception as e:
  200. self.log.exception("Error while connecting to Instagram")
  201. await self.push_bridge_state(
  202. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  203. )
  204. return
  205. @property
  206. def api_log(self) -> TraceLogger:
  207. return self.ig_base_log.getChild("http").getChild(self.mxid)
  208. @property
  209. def is_connected(self) -> bool:
  210. return bool(self.client) and bool(self.mqtt) and self._is_connected
  211. async def ensure_connected(self, max_wait_seconds: int = 5) -> None:
  212. sleep_interval = 0.1
  213. max_attempts = max_wait_seconds / sleep_interval
  214. attempts = 0
  215. while True:
  216. if self.is_connected:
  217. return
  218. attempts += 1
  219. if attempts > max_attempts:
  220. raise Exception("You're not connected to instagram")
  221. await asyncio.sleep(sleep_interval)
  222. async def connect(self, user: CurrentUser | None = None) -> None:
  223. if not self.state:
  224. await self.push_bridge_state(
  225. BridgeStateEvent.BAD_CREDENTIALS,
  226. error="logged-out",
  227. info={"cnd_action": "reauth"},
  228. )
  229. return
  230. client = AndroidAPI(
  231. self.state,
  232. log=self.api_log,
  233. proxy_handler=self.proxy_handler,
  234. on_proxy_update=self.on_proxy_update,
  235. )
  236. if not user:
  237. try:
  238. resp = await client.current_user()
  239. user = resp.user
  240. except IGNotLoggedInError as e:
  241. self.log.warning(f"Failed to connect to Instagram: {e}, logging out")
  242. await self.logout(error=e)
  243. return
  244. except IGCheckpointError as e:
  245. self.log.debug("Checkpoint error content: %s", e.body)
  246. raise
  247. except (IGChallengeError, IGConsentRequiredError) as e:
  248. await self._handle_checkpoint(e, on="connect", client=client)
  249. return
  250. self.client = client
  251. self._is_logged_in = True
  252. self.igpk = user.pk
  253. self.username = user.username
  254. await self.push_bridge_state(BridgeStateEvent.CONNECTING)
  255. self._track_metric(METRIC_LOGGED_IN, True)
  256. self.by_igpk[self.igpk] = self
  257. self.mqtt = AndroidMQTT(
  258. self.state,
  259. log=self.ig_base_log.getChild("mqtt").getChild(self.mxid),
  260. proxy_handler=self.proxy_handler,
  261. )
  262. self.mqtt.add_event_handler(Connect, self.on_connect)
  263. self.mqtt.add_event_handler(Disconnect, self.on_disconnect)
  264. self.mqtt.add_event_handler(NewSequenceID, self.update_seq_id)
  265. self.mqtt.add_event_handler(MessageSyncEvent, self.handle_message)
  266. self.mqtt.add_event_handler(ThreadSyncEvent, self.handle_thread_sync)
  267. self.mqtt.add_event_handler(ThreadRemoveEvent, self.handle_thread_remove)
  268. self.mqtt.add_event_handler(RealtimeDirectEvent, self.handle_rtd)
  269. self.mqtt.add_event_handler(ProxyUpdate, self.on_proxy_update)
  270. await self.update()
  271. self.loop.create_task(self._try_sync_puppet(user))
  272. self.loop.create_task(self._post_connect())
  273. async def _post_connect(self):
  274. # Backfill requests are handled synchronously so as not to overload the homeserver.
  275. # Users can configure their backfill stages to be more or less aggressive with backfilling
  276. # to try and avoid getting banned.
  277. if not self._backfill_loop_task or self._backfill_loop_task.done():
  278. self._backfill_loop_task = asyncio.create_task(self._handle_backfill_requests_loop())
  279. if not self.seq_id:
  280. await self._try_sync()
  281. else:
  282. self.log.debug("Connecting to MQTT directly as resync_on_startup is false")
  283. self.start_listen()
  284. if self.config["bridge.backfill.enable"]:
  285. if self._thread_sync_task and not self._thread_sync_task.done():
  286. self.log.warning("Cancelling existing background thread sync task")
  287. self._thread_sync_task.cancel()
  288. self._thread_sync_task = asyncio.create_task(self.backfill_threads())
  289. async def _handle_backfill_requests_loop(self) -> None:
  290. if not self.config["bridge.backfill.enable"] or not self.config["bridge.backfill.msc2716"]:
  291. return
  292. while True:
  293. await self._sync_lock.wait("backfill request")
  294. req = await Backfill.get_next(self.mxid)
  295. if not req:
  296. await asyncio.sleep(30)
  297. continue
  298. self.log.info("Backfill request %s", req)
  299. try:
  300. portal = await po.Portal.get_by_thread_id(
  301. req.portal_thread_id, receiver=req.portal_receiver
  302. )
  303. await req.mark_dispatched()
  304. await portal.backfill(self, req)
  305. await req.mark_done()
  306. except IGNotLoggedInError as e:
  307. self.log.exception("User got logged out during backfill loop")
  308. await self.logout(error=e)
  309. break
  310. except (IGChallengeError, IGConsentRequiredError) as e:
  311. self.log.exception("User got a challenge during backfill loop")
  312. await self._handle_checkpoint(e, on="backfill")
  313. break
  314. except Exception as e:
  315. self.log.exception("Failed to backfill portal %s: %s", req.portal_thread_id, e)
  316. # Don't try again to backfill this portal for a minute.
  317. await req.set_cooldown_timeout(60)
  318. self._backfill_loop_task = None
  319. async def on_connect(self, evt: Connect) -> None:
  320. self.log.debug("Connected to Instagram")
  321. self._track_metric(METRIC_CONNECTED, True)
  322. self._is_connected = True
  323. await self.send_bridge_notice("Connected to Instagram")
  324. await self.push_bridge_state(BridgeStateEvent.CONNECTED)
  325. async def on_disconnect(self, evt: Disconnect) -> None:
  326. self.log.debug("Disconnected from Instagram")
  327. self._track_metric(METRIC_CONNECTED, False)
  328. self._is_connected = False
  329. async def on_proxy_update(self, evt: ProxyUpdate | None = None) -> None:
  330. if self.client:
  331. self.client.setup_http(self.state.cookies.jar)
  332. if self.mqtt:
  333. self.mqtt.setup_proxy()
  334. # TODO this stuff could probably be moved to mautrix-python
  335. async def get_notice_room(self) -> RoomID:
  336. if not self.notice_room:
  337. async with self._notice_room_lock:
  338. # If someone already created the room while this call was waiting,
  339. # don't make a new room
  340. if self.notice_room:
  341. return self.notice_room
  342. creation_content = {}
  343. if not self.config["bridge.federate_rooms"]:
  344. creation_content["m.federate"] = False
  345. self.notice_room = await self.az.intent.create_room(
  346. is_direct=True,
  347. invitees=[self.mxid],
  348. topic="Instagram bridge notices",
  349. creation_content=creation_content,
  350. )
  351. await self.update()
  352. return self.notice_room
  353. async def fill_bridge_state(self, state: BridgeState) -> None:
  354. await super().fill_bridge_state(state)
  355. if not state.remote_id:
  356. if self.igpk:
  357. state.remote_id = str(self.igpk)
  358. else:
  359. try:
  360. state.remote_id = self.state.user_id
  361. except IGUserIDNotFoundError:
  362. state.remote_id = None
  363. if self.username:
  364. state.remote_name = f"@{self.username}"
  365. async def get_bridge_states(self) -> list[BridgeState]:
  366. if not self.state:
  367. return []
  368. state = BridgeState(state_event=BridgeStateEvent.UNKNOWN_ERROR)
  369. if self.is_connected:
  370. state.state_event = BridgeStateEvent.CONNECTED
  371. elif self._is_refreshing or self.mqtt:
  372. state.state_event = BridgeStateEvent.TRANSIENT_DISCONNECT
  373. return [state]
  374. async def send_bridge_notice(
  375. self,
  376. text: str,
  377. edit: EventID | None = None,
  378. state_event: BridgeStateEvent | None = None,
  379. important: bool = False,
  380. error_code: str | None = None,
  381. error_message: str | None = None,
  382. info: dict | None = None,
  383. ) -> EventID | None:
  384. if state_event:
  385. await self.push_bridge_state(
  386. state_event,
  387. error=error_code,
  388. message=error_message if error_code else text,
  389. info=info,
  390. )
  391. if self.config["bridge.disable_bridge_notices"]:
  392. return None
  393. if not important and not self.config["bridge.unimportant_bridge_notices"]:
  394. self.log.debug("Not sending unimportant bridge notice: %s", text)
  395. return None
  396. event_id = None
  397. try:
  398. self.log.debug("Sending bridge notice: %s", text)
  399. content = TextMessageEventContent(
  400. body=text, msgtype=(MessageType.TEXT if important else MessageType.NOTICE)
  401. )
  402. if edit:
  403. content.set_edit(edit)
  404. # This is locked to prevent notices going out in the wrong order
  405. async with self._notice_send_lock:
  406. event_id = await self.az.intent.send_message(await self.get_notice_room(), content)
  407. except Exception:
  408. self.log.warning("Failed to send bridge notice", exc_info=True)
  409. return edit or event_id
  410. async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
  411. puppet = await pu.Puppet.get_by_pk(self.igpk)
  412. try:
  413. await puppet.update_info(user_info, self)
  414. except Exception:
  415. self.log.exception("Failed to update own puppet info")
  416. try:
  417. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  418. self.log.info("Automatically enabling custom puppet")
  419. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  420. except Exception:
  421. self.log.exception("Failed to automatically enable custom puppet")
  422. async def _try_sync(self) -> None:
  423. try:
  424. await self.sync()
  425. except Exception as e:
  426. self.log.exception("Exception while syncing")
  427. if isinstance(e, IGCheckpointError):
  428. self.log.debug("Checkpoint error content: %s", e.body)
  429. await self.push_bridge_state(
  430. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  431. )
  432. async def get_direct_chats(self) -> dict[UserID, list[RoomID]]:
  433. return {
  434. pu.Puppet.get_mxid_from_id(portal.other_user_pk): [portal.mxid]
  435. for portal in await DBPortal.find_private_chats_of(self.igpk)
  436. if portal.mxid
  437. }
  438. async def refresh(self, resync: bool = True, update_proxy: bool = False) -> None:
  439. self._is_refreshing = True
  440. try:
  441. await self.stop_listen()
  442. self.state.reset_pigeon_session_id()
  443. if update_proxy and self.proxy_handler.update_proxy_url(reason="reconnect"):
  444. await self.on_proxy_update()
  445. if resync:
  446. retry_count = 0
  447. minutes = 1
  448. while True:
  449. try:
  450. await self.sync()
  451. return
  452. except Exception as e:
  453. if retry_count >= 4 and minutes < 10:
  454. minutes += 1
  455. retry_count += 1
  456. s = "s" if minutes != 1 else ""
  457. self.log.exception(
  458. f"Error while syncing for refresh, retrying in {minutes} minute{s}"
  459. )
  460. if isinstance(e, IGCheckpointError):
  461. self.log.debug("Checkpoint error content: %s", e.body)
  462. await self.push_bridge_state(
  463. BridgeStateEvent.UNKNOWN_ERROR,
  464. error="unknown-error",
  465. message="An unknown error occurred while connecting to Instagram",
  466. info={"python_error": str(e)},
  467. )
  468. await asyncio.sleep(minutes * 60)
  469. else:
  470. self.start_listen()
  471. finally:
  472. self._is_refreshing = False
  473. async def _handle_checkpoint(
  474. self,
  475. e: IGChallengeError | IGConsentRequiredError,
  476. on: str,
  477. client: AndroidAPI | None = None,
  478. ) -> None:
  479. self.log.warning(f"Got checkpoint error on {on}: {e.body.serialize()}")
  480. client = client or self.client
  481. self.client = None
  482. self.mqtt = None
  483. if isinstance(e, IGConsentRequiredError):
  484. await self.push_bridge_state(
  485. BridgeStateEvent.BAD_CREDENTIALS,
  486. error="ig-consent-required",
  487. info=e.body.serialize(),
  488. )
  489. return
  490. error_code = "ig-checkpoint"
  491. try:
  492. resp = await client.challenge_reset()
  493. info = {
  494. "challenge_context": (
  495. resp.challenge_context.serialize() if resp.challenge_context_str else None
  496. ),
  497. "step_name": resp.step_name,
  498. "step_data": resp.step_data.serialize() if resp.step_data else None,
  499. "user_id": resp.user_id,
  500. "action": resp.action,
  501. "status": resp.status,
  502. "challenge": e.body.challenge.serialize() if e.body.challenge else None,
  503. }
  504. self.log.debug(f"Challenge state: {resp.serialize()}")
  505. if resp.challenge_context.challenge_type_enum == "HACKED_LOCK":
  506. error_code = "ig-checkpoint-locked"
  507. except Exception:
  508. self.log.exception("Error resetting challenge state")
  509. info = {"challenge": e.body.challenge.serialize() if e.body.challenge else None}
  510. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=error_code, info=info)
  511. async def _sync_thread(self, thread: Thread) -> bool:
  512. """
  513. Sync a specific thread. Returns whether the thread had messages after the last message in
  514. the database before the sync.
  515. """
  516. self.log.debug(f"Syncing thread {thread.thread_id}")
  517. forward_messages = thread.items
  518. assert self.client
  519. portal = await po.Portal.get_by_thread(thread, self.igpk)
  520. assert portal
  521. # Create or update the Matrix room
  522. if not portal.mxid:
  523. await portal.create_matrix_room(self, thread)
  524. else:
  525. await portal.update_matrix_room(self, thread)
  526. if not self.config["bridge.backfill.enable_initial"]:
  527. return True
  528. last_message = await DBMessage.get_last(portal.mxid)
  529. cursor = thread.oldest_cursor
  530. if last_message:
  531. original_number_of_messages = len(thread.items)
  532. new_messages = [
  533. m for m in thread.items if last_message.ig_timestamp_ms < m.timestamp_ms
  534. ]
  535. forward_messages = new_messages
  536. portal.log.debug(
  537. f"{len(new_messages)}/{original_number_of_messages} messages are after most recent"
  538. " message."
  539. )
  540. # Fetch more messages until we get back to messages that have been bridged already.
  541. while len(new_messages) > 0 and len(new_messages) == original_number_of_messages:
  542. await asyncio.sleep(self.config["bridge.backfill.incremental.page_delay"])
  543. portal.log.debug("Fetching more messages for forward backfill")
  544. resp = await self.client.get_thread(portal.thread_id, cursor=cursor)
  545. if len(resp.thread.items) == 0:
  546. break
  547. original_number_of_messages = len(resp.thread.items)
  548. new_messages = [
  549. m for m in resp.thread.items if last_message.ig_timestamp_ms < m.timestamp_ms
  550. ]
  551. forward_messages = new_messages + forward_messages
  552. cursor = resp.thread.oldest_cursor
  553. portal.log.debug(
  554. f"{len(new_messages)}/{original_number_of_messages} messages are after most "
  555. "recent message."
  556. )
  557. elif not portal.first_event_id:
  558. self.log.debug(
  559. f"Skipping backfilling {portal.thread_id} as the first event ID is not known"
  560. )
  561. return False
  562. if forward_messages:
  563. portal.cursor = cursor
  564. await portal.update()
  565. mark_read = thread.read_state == 0 or (
  566. (hours := self.config["bridge.backfill.unread_hours_threshold"]) > 0
  567. and (
  568. datetime.fromtimestamp(forward_messages[0].timestamp_ms / 1000)
  569. < datetime.now() - timedelta(hours=hours)
  570. )
  571. )
  572. base_insertion_event_id = await portal.backfill_message_page(
  573. self,
  574. list(reversed(forward_messages)),
  575. forward=True,
  576. last_message=last_message,
  577. mark_read=mark_read,
  578. )
  579. if (
  580. not self.bridge.homeserver_software.is_hungry
  581. and self.config["bridge.backfill.msc2716"]
  582. ):
  583. await portal.send_post_backfill_dummy(
  584. forward_messages[0].timestamp, base_insertion_event_id=base_insertion_event_id
  585. )
  586. if (
  587. mark_read
  588. and not self.bridge.homeserver_software.is_hungry
  589. and (puppet := await self.get_puppet())
  590. ):
  591. last_message = await DBMessage.get_last(portal.mxid)
  592. if last_message:
  593. await puppet.intent_for(portal).mark_read(portal.mxid, last_message.mxid)
  594. await portal._update_read_receipts(thread.last_seen_at)
  595. if self.config["bridge.backfill.msc2716"]:
  596. await portal.enqueue_immediate_backfill(self, 1)
  597. return len(forward_messages) > 0
  598. async def sync(self, increment_total_backfilled_portals: bool = False) -> None:
  599. await self.run_with_sync_lock(partial(self._sync, increment_total_backfilled_portals))
  600. async def _sync(self, increment_total_backfilled_portals: bool = False) -> None:
  601. if not self._listen_task:
  602. self.state.reset_pigeon_session_id()
  603. sleep_minutes = 2
  604. while True:
  605. try:
  606. resp = await self.client.get_inbox()
  607. break
  608. except IGNotLoggedInError as e:
  609. self.log.exception("Got not logged in error while syncing")
  610. await self.logout(error=e)
  611. return
  612. except IGRateLimitError as e:
  613. self.log.error(
  614. "Got ratelimit error while trying to get inbox (%s), retrying in %d minutes",
  615. e.body,
  616. sleep_minutes,
  617. )
  618. await self.push_bridge_state(
  619. BridgeStateEvent.TRANSIENT_DISCONNECT, error="ig-rate-limit"
  620. )
  621. await asyncio.sleep(sleep_minutes * 60)
  622. sleep_minutes += 2
  623. except IGCheckpointError as e:
  624. self.log.debug("Checkpoint error content: %s", e.body)
  625. raise
  626. except (IGChallengeError, IGConsentRequiredError) as e:
  627. await self._handle_checkpoint(e, on="sync")
  628. return
  629. self.seq_id = resp.seq_id
  630. self.snapshot_at_ms = resp.snapshot_at_ms
  631. await self.save_seq_id()
  632. if not self._listen_task:
  633. self.start_listen(is_after_sync=True)
  634. sync_count = min(
  635. self.config["bridge.backfill.max_conversations"],
  636. self.config["bridge.max_startup_thread_sync_count"],
  637. )
  638. self.log.debug(f"Fetching {sync_count} threads, 20 at a time...")
  639. local_limit: int | None = sync_count
  640. if sync_count == 0:
  641. return
  642. elif sync_count < 0:
  643. local_limit = None
  644. await self._sync_threads_with_delay(
  645. self.client.iter_inbox(
  646. self._update_seq_id_and_cursor, start_at=resp, local_limit=local_limit
  647. ),
  648. stop_when_threads_have_no_messages_to_backfill=True,
  649. increment_total_backfilled_portals=increment_total_backfilled_portals,
  650. local_limit=local_limit,
  651. )
  652. try:
  653. await self.update_direct_chats()
  654. except Exception:
  655. self.log.exception("Error updating direct chat list")
  656. async def backfill_threads(self):
  657. try:
  658. await self.run_with_sync_lock(self._backfill_threads)
  659. except Exception:
  660. self.log.exception("Error in thread backfill loop")
  661. async def _backfill_threads(self):
  662. assert self.client
  663. if not self.config["bridge.backfill.enable"]:
  664. return
  665. max_conversations = self.config["bridge.backfill.max_conversations"] or 0
  666. if 0 <= max_conversations <= (self.total_backfilled_portals or 0):
  667. self.log.info("Backfill max_conversations count reached, not syncing any more portals")
  668. return
  669. elif self.thread_sync_completed:
  670. self.log.debug("Thread backfill is marked as completed, not syncing more portals")
  671. return
  672. local_limit = (
  673. max_conversations - (self.total_backfilled_portals or 0)
  674. if max_conversations >= 0
  675. else None
  676. )
  677. start_at = None
  678. if self.oldest_cursor:
  679. start_at = DMInboxResponse(
  680. status="",
  681. seq_id=self.seq_id,
  682. snapshot_at_ms=0,
  683. pending_requests_total=0,
  684. has_pending_top_requests=False,
  685. viewer=None,
  686. inbox=DMInbox(
  687. threads=[],
  688. has_older=True,
  689. unseen_count=0,
  690. unseen_count_ts=0,
  691. blended_inbox_enabled=False,
  692. oldest_cursor=self.oldest_cursor,
  693. ),
  694. )
  695. backoff = self.config.get("bridge.backfill.backoff.thread_list", 300)
  696. await self._sync_threads_with_delay(
  697. self.client.iter_inbox(
  698. self._update_seq_id_and_cursor,
  699. start_at=start_at,
  700. local_limit=local_limit,
  701. rate_limit_exceeded_backoff=backoff,
  702. ),
  703. increment_total_backfilled_portals=True,
  704. local_limit=local_limit,
  705. )
  706. await self.update_direct_chats()
  707. def _update_seq_id_and_cursor(self, seq_id: int, cursor: str | None):
  708. self.seq_id = seq_id
  709. if cursor:
  710. self.oldest_cursor = cursor
  711. async def _sync_threads_with_delay(
  712. self,
  713. threads: AsyncIterable[Thread],
  714. increment_total_backfilled_portals: bool = False,
  715. stop_when_threads_have_no_messages_to_backfill: bool = False,
  716. local_limit: int | None = None,
  717. ):
  718. sync_delay = self.config["bridge.backfill.min_sync_thread_delay"]
  719. last_thread_sync_ts = 0.0
  720. found_thread_count = 0
  721. async for thread in threads:
  722. found_thread_count += 1
  723. now = time.monotonic()
  724. if now < last_thread_sync_ts + sync_delay:
  725. delay = last_thread_sync_ts + sync_delay - now
  726. self.log.debug("Thread sync is happening too quickly. Waiting for %ds", delay)
  727. await asyncio.sleep(delay)
  728. last_thread_sync_ts = time.monotonic()
  729. had_new_messages = await self._sync_thread(thread)
  730. if not had_new_messages and stop_when_threads_have_no_messages_to_backfill:
  731. self.log.debug("Got to threads with no new messages. Stopping sync.")
  732. return
  733. if increment_total_backfilled_portals:
  734. self.total_backfilled_portals = (self.total_backfilled_portals or 0) + 1
  735. await self.update()
  736. if local_limit is None or found_thread_count < local_limit:
  737. if local_limit is None:
  738. self.log.info(
  739. "Reached end of thread list with no limit, marking thread sync as completed"
  740. )
  741. else:
  742. self.log.info(
  743. f"Reached end of thread list (got {found_thread_count} with "
  744. f"limit {local_limit}), marking thread sync as completed"
  745. )
  746. self.thread_sync_completed = True
  747. await self.update()
  748. async def run_with_sync_lock(self, func: Callable[[], Awaitable]):
  749. with self._sync_lock:
  750. retry_count = 0
  751. while retry_count < 5:
  752. try:
  753. retry_count += 1
  754. await func()
  755. # The sync was successful. Exit the loop.
  756. return
  757. except IGNotLoggedInError as e:
  758. await self.logout(error=e)
  759. return
  760. except Exception:
  761. self.log.exception(
  762. "Failed to sync threads. Waiting 30 seconds before retrying sync."
  763. )
  764. await asyncio.sleep(30)
  765. # If we get here, it means that the sync has failed five times. If this happens, most
  766. # likely something very bad has happened.
  767. self.log.error("Failed to sync threads five times. Will not retry.")
  768. def start_listen(self, is_after_sync: bool = False) -> None:
  769. self.shutdown = False
  770. task = self._listen(
  771. seq_id=self.seq_id, snapshot_at_ms=self.snapshot_at_ms, is_after_sync=is_after_sync
  772. )
  773. self._listen_task = self.loop.create_task(task)
  774. async def delayed_start_listen(self, sleep: int) -> None:
  775. await asyncio.sleep(sleep)
  776. if self.is_connected:
  777. self.log.debug(
  778. "Already reconnected before delay after MQTT reconnection error finished"
  779. )
  780. else:
  781. self.log.debug("Reconnecting after MQTT connection error")
  782. self.start_listen()
  783. async def fetch_user_and_reconnect(self, sleep_first: int | None = None) -> None:
  784. if sleep_first:
  785. await asyncio.sleep(sleep_first)
  786. if self.is_connected:
  787. self.log.debug("Canceling user fetch, already reconnected")
  788. return
  789. self.log.debug("Refetching current user after disconnection")
  790. errors = 0
  791. while True:
  792. try:
  793. resp = await self.client.current_user()
  794. except RETRYABLE_PROXY_EXCEPTIONS as e:
  795. # These are retried by the client up to 10 times, but we actually want to retry
  796. # these indefinitely so we capture them here again and retry.
  797. self.log.warning(
  798. f"Proxy error fetching user from Instagram: {e}, retrying in 1 minute",
  799. )
  800. await asyncio.sleep(60)
  801. except IGNotLoggedInError as e:
  802. self.log.warning(f"Failed to reconnect to Instagram: {e}, logging out")
  803. await self.logout(error=e)
  804. return
  805. except (IGChallengeError, IGConsentRequiredError) as e:
  806. await self._handle_checkpoint(e, on="reconnect")
  807. return
  808. except IGUnknownError as e:
  809. if "non-JSON body" not in e:
  810. raise
  811. errors += 1
  812. if errors > 10:
  813. raise
  814. self.log.warning(
  815. "Non-JSON body while trying to check user for reconnection, retrying in 10s"
  816. )
  817. await asyncio.sleep(10)
  818. except Exception as e:
  819. self.log.exception("Error while reconnecting to Instagram")
  820. if isinstance(e, IGCheckpointError):
  821. self.log.debug("Checkpoint error content: %s", e.body)
  822. await self.push_bridge_state(
  823. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  824. )
  825. return
  826. else:
  827. self.log.debug(f"Confirmed current user {resp.user.pk}")
  828. self.start_listen()
  829. return
  830. async def _listen(self, seq_id: int, snapshot_at_ms: int, is_after_sync: bool) -> None:
  831. try:
  832. await self.mqtt.listen(
  833. graphql_subs={
  834. GraphQLSubscription.app_presence(),
  835. GraphQLSubscription.direct_typing(self.state.user_id),
  836. GraphQLSubscription.direct_status(),
  837. },
  838. skywalker_subs={
  839. SkywalkerSubscription.direct_sub(self.state.user_id),
  840. SkywalkerSubscription.live_sub(self.state.user_id),
  841. },
  842. seq_id=seq_id,
  843. snapshot_at_ms=snapshot_at_ms,
  844. )
  845. except IrisSubscribeError as e:
  846. if is_after_sync:
  847. self.log.exception("Got IrisSubscribeError right after refresh")
  848. await self.send_bridge_notice(
  849. f"Reconnecting failed again after refresh: {e}",
  850. important=True,
  851. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  852. error_code="ig-refresh-connection-error",
  853. error_message=str(e),
  854. info={"python_error": str(e)},
  855. )
  856. else:
  857. self.log.warning(f"Got IrisSubscribeError {e}, refreshing...")
  858. background_task.create(self.refresh())
  859. except MQTTReconnectionError as e:
  860. self.log.warning(
  861. f"Unexpected connection error: {e}, reconnecting in 1 minute", exc_info=True
  862. )
  863. await self.send_bridge_notice(
  864. f"Error in listener: {e}",
  865. important=True,
  866. state_event=BridgeStateEvent.TRANSIENT_DISCONNECT,
  867. error_code="ig-connection-error-socket",
  868. )
  869. self.mqtt.disconnect()
  870. background_task.create(self.delayed_start_listen(sleep=60))
  871. except (MQTTNotConnected, MQTTNotLoggedIn, MQTTConnectionUnauthorized) as e:
  872. self.log.warning(f"Unexpected connection error: {e}, checking auth and reconnecting")
  873. await self.send_bridge_notice(
  874. f"Error in listener: {e}",
  875. important=True,
  876. state_event=BridgeStateEvent.TRANSIENT_DISCONNECT,
  877. error_code="ig-connection-error-maybe-auth",
  878. )
  879. self.mqtt.disconnect()
  880. background_task.create(self.fetch_user_and_reconnect())
  881. except Exception as e:
  882. self.log.exception("Fatal error in listener, reconnecting in 5 minutes")
  883. await self.send_bridge_notice(
  884. "Fatal error in listener (see logs for more info)",
  885. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  886. important=True,
  887. error_code="ig-unknown-connection-error",
  888. info={"python_error": str(e)},
  889. )
  890. self.mqtt.disconnect()
  891. background_task.create(self.fetch_user_and_reconnect(sleep_first=300))
  892. else:
  893. if not self.shutdown:
  894. await self.send_bridge_notice(
  895. "Instagram connection closed without error",
  896. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  897. error_code="ig-disconnected",
  898. )
  899. finally:
  900. self._listen_task = None
  901. self._is_connected = False
  902. self._track_metric(METRIC_CONNECTED, False)
  903. async def stop_listen(self) -> None:
  904. if self.mqtt:
  905. self.shutdown = True
  906. self.mqtt.disconnect()
  907. if self._listen_task:
  908. await self._listen_task
  909. self.shutdown = False
  910. self._track_metric(METRIC_CONNECTED, False)
  911. self._is_connected = False
  912. await self.update()
  913. def stop_backfill_tasks(self) -> None:
  914. if self._backfill_loop_task:
  915. self._backfill_loop_task.cancel()
  916. self._backfill_loop_task = None
  917. if self._thread_sync_task:
  918. self._thread_sync_task.cancel()
  919. self._thread_sync_task = None
  920. async def logout(self, error: IGNotLoggedInError | None = None) -> None:
  921. await self.stop_listen()
  922. self.stop_backfill_tasks()
  923. if self.client and error is None:
  924. try:
  925. await self.client.logout(one_tap_app_login=False)
  926. except Exception:
  927. self.log.debug("Exception logging out", exc_info=True)
  928. if self.mqtt:
  929. self.mqtt.disconnect()
  930. self._track_metric(METRIC_CONNECTED, False)
  931. self._track_metric(METRIC_LOGGED_IN, False)
  932. if error is None:
  933. await self.push_bridge_state(BridgeStateEvent.LOGGED_OUT)
  934. puppet = await pu.Puppet.get_by_pk(self.igpk, create=False)
  935. if puppet and puppet.is_real_user:
  936. await puppet.switch_mxid(None, None)
  937. try:
  938. del self.by_igpk[self.igpk]
  939. except KeyError:
  940. pass
  941. self.igpk = None
  942. else:
  943. self.log.debug("Auth error body: %s", error.body.serialize())
  944. await self.send_bridge_notice(
  945. f"You have been logged out of Instagram: {error.proper_message}",
  946. important=True,
  947. state_event=BridgeStateEvent.BAD_CREDENTIALS,
  948. error_code="ig-auth-error",
  949. error_message=error.proper_message,
  950. info={"cnd_action": "reauth"},
  951. )
  952. self.client = None
  953. self.mqtt = None
  954. self.state = None
  955. self.seq_id = None
  956. self.snapshot_at_ms = None
  957. self.thread_sync_completed = False
  958. self._is_logged_in = False
  959. await self.update()
  960. # endregion
  961. # region Event handlers
  962. async def _save_seq_id_after_sleep(self) -> None:
  963. await asyncio.sleep(120)
  964. self._seq_id_save_task = None
  965. self.log.trace("Saving sequence ID %d/%d", self.seq_id, self.snapshot_at_ms)
  966. try:
  967. await self.save_seq_id()
  968. except Exception:
  969. self.log.exception("Error saving sequence ID")
  970. async def update_seq_id(self, evt: NewSequenceID) -> None:
  971. self.seq_id = evt.seq_id
  972. self.snapshot_at_ms = evt.snapshot_at_ms
  973. if not self._seq_id_save_task or self._seq_id_save_task.done():
  974. self.log.trace("Starting seq id save task (%d/%d)", evt.seq_id, evt.snapshot_at_ms)
  975. self._seq_id_save_task = asyncio.create_task(self._save_seq_id_after_sleep())
  976. else:
  977. self.log.trace("Not starting seq id save task (%d/%d)", evt.seq_id, evt.snapshot_at_ms)
  978. @async_time(METRIC_MESSAGE)
  979. async def handle_message(self, evt: MessageSyncEvent) -> None:
  980. portal = await po.Portal.get_by_thread_id(evt.message.thread_id, receiver=self.igpk)
  981. if not portal or not portal.mxid:
  982. self.log.debug("Got message in thread with no portal, getting info...")
  983. resp = await self.client.get_thread(evt.message.thread_id)
  984. portal = await po.Portal.get_by_thread(resp.thread, self.igpk)
  985. self.log.debug("Got info for unknown portal, creating room")
  986. await portal.create_matrix_room(self, resp.thread)
  987. if not portal.mxid:
  988. self.log.warning(
  989. "Room creation appears to have failed, "
  990. f"dropping message in {evt.message.thread_id}"
  991. )
  992. return
  993. self.log.trace(f"Received message sync event {evt.message}")
  994. if evt.message.new_reaction:
  995. await portal.handle_instagram_reaction(
  996. evt.message, remove=evt.message.op == Operation.REMOVE
  997. )
  998. return
  999. sender = await pu.Puppet.get_by_pk(evt.message.user_id) if evt.message.user_id else None
  1000. if evt.message.op == Operation.ADD:
  1001. if not sender:
  1002. # I don't think we care about adds with no sender
  1003. return
  1004. await portal.handle_instagram_item(self, sender, evt.message)
  1005. elif evt.message.op == Operation.REMOVE:
  1006. # Removes don't have a sender, only the message sender can unsend messages anyway
  1007. await portal.handle_instagram_remove(evt.message.item_id)
  1008. elif evt.message.op == Operation.REPLACE:
  1009. await portal.handle_instagram_update(evt.message)
  1010. @async_time(METRIC_THREAD_SYNC)
  1011. async def handle_thread_sync(self, evt: ThreadSyncEvent) -> None:
  1012. self.log.trace("Thread sync event content: %s", evt)
  1013. portal = await po.Portal.get_by_thread(evt, receiver=self.igpk)
  1014. if portal.mxid:
  1015. self.log.debug("Got thread sync event for %s with existing portal", portal.thread_id)
  1016. await portal.update_matrix_room(self, evt)
  1017. elif evt.is_group:
  1018. self.log.debug(
  1019. "Got thread sync event for group %s without existing portal, creating room",
  1020. portal.thread_id,
  1021. )
  1022. await portal.create_matrix_room(self, evt)
  1023. else:
  1024. self.log.debug(
  1025. "Got thread sync event for DM %s without existing portal, ignoring",
  1026. portal.thread_id,
  1027. )
  1028. async def handle_thread_remove(self, evt: ThreadRemoveEvent) -> None:
  1029. self.log.debug("Got thread remove event: %s", evt.serialize())
  1030. @async_time(METRIC_RTD)
  1031. async def handle_rtd(self, evt: RealtimeDirectEvent) -> None:
  1032. if not isinstance(evt.value, ActivityIndicatorData):
  1033. return
  1034. now = int(time.time() * 1000)
  1035. date = evt.value.timestamp_ms
  1036. expiry = date + evt.value.ttl
  1037. if expiry < now:
  1038. return
  1039. if evt.activity_indicator_id in self._activity_indicator_ids:
  1040. return
  1041. # TODO clear expired items from this dict
  1042. self._activity_indicator_ids[evt.activity_indicator_id] = expiry
  1043. puppet = await pu.Puppet.get_by_pk(int(evt.value.sender_id))
  1044. portal = await po.Portal.get_by_thread_id(evt.thread_id, receiver=self.igpk)
  1045. if not puppet or not portal or not portal.mxid:
  1046. return
  1047. is_typing = evt.value.activity_status != TypingStatus.OFF
  1048. if puppet.pk == self.igpk:
  1049. self.remote_typing_status = TypingStatus.TEXT if is_typing else TypingStatus.OFF
  1050. await puppet.intent_for(portal).set_typing(portal.mxid, timeout=evt.value.ttl)
  1051. # endregion
  1052. # region Database getters
  1053. def _add_to_cache(self) -> None:
  1054. self.by_mxid[self.mxid] = self
  1055. if self.igpk:
  1056. self.by_igpk[self.igpk] = self
  1057. @classmethod
  1058. @async_getter_lock
  1059. async def get_by_mxid(cls, mxid: UserID, *, create: bool = True) -> User | None:
  1060. # Never allow ghosts to be users
  1061. if pu.Puppet.get_id_from_mxid(mxid):
  1062. return None
  1063. try:
  1064. return cls.by_mxid[mxid]
  1065. except KeyError:
  1066. pass
  1067. user = cast(cls, await super().get_by_mxid(mxid))
  1068. if user is not None:
  1069. user._add_to_cache()
  1070. return user
  1071. if create:
  1072. user = cls(mxid)
  1073. await user.insert()
  1074. user._add_to_cache()
  1075. return user
  1076. return None
  1077. @classmethod
  1078. @async_getter_lock
  1079. async def get_by_igpk(cls, igpk: int) -> User | None:
  1080. try:
  1081. return cls.by_igpk[igpk]
  1082. except KeyError:
  1083. pass
  1084. user = cast(cls, await super().get_by_igpk(igpk))
  1085. if user is not None:
  1086. user._add_to_cache()
  1087. return user
  1088. return None
  1089. @classmethod
  1090. async def all_logged_in(cls) -> AsyncGenerator[User, None]:
  1091. users = await super().all_logged_in()
  1092. user: cls
  1093. for index, user in enumerate(users):
  1094. try:
  1095. yield cls.by_mxid[user.mxid]
  1096. except KeyError:
  1097. user._add_to_cache()
  1098. yield user
  1099. # endregion