user.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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. if self.bridge.homeserver_software.is_hungry:
  290. self.log.info("Updating contact info for all users")
  291. asyncio.gather(*[puppet.update_contact_info() async for puppet in pu.Puppet.get_all()])
  292. async def _handle_backfill_requests_loop(self) -> None:
  293. if not self.config["bridge.backfill.enable"] or not self.config["bridge.backfill.msc2716"]:
  294. return
  295. while True:
  296. await self._sync_lock.wait("backfill request")
  297. req = await Backfill.get_next(self.mxid)
  298. if not req:
  299. await asyncio.sleep(30)
  300. continue
  301. self.log.info("Backfill request %s", req)
  302. try:
  303. portal = await po.Portal.get_by_thread_id(
  304. req.portal_thread_id, receiver=req.portal_receiver
  305. )
  306. await req.mark_dispatched()
  307. await portal.backfill(self, req)
  308. await req.mark_done()
  309. except IGNotLoggedInError as e:
  310. self.log.exception("User got logged out during backfill loop")
  311. await self.logout(error=e)
  312. break
  313. except (IGChallengeError, IGConsentRequiredError) as e:
  314. self.log.exception("User got a challenge during backfill loop")
  315. await self._handle_checkpoint(e, on="backfill")
  316. break
  317. except Exception as e:
  318. self.log.exception("Failed to backfill portal %s: %s", req.portal_thread_id, e)
  319. # Don't try again to backfill this portal for a minute.
  320. await req.set_cooldown_timeout(60)
  321. self._backfill_loop_task = None
  322. async def on_connect(self, evt: Connect) -> None:
  323. self.log.debug("Connected to Instagram")
  324. self._track_metric(METRIC_CONNECTED, True)
  325. self._is_connected = True
  326. await self.send_bridge_notice("Connected to Instagram")
  327. await self.push_bridge_state(BridgeStateEvent.CONNECTED)
  328. async def on_disconnect(self, evt: Disconnect) -> None:
  329. self.log.debug("Disconnected from Instagram")
  330. self._track_metric(METRIC_CONNECTED, False)
  331. self._is_connected = False
  332. async def on_proxy_update(self, evt: ProxyUpdate | None = None) -> None:
  333. if self.client:
  334. self.client.setup_http(self.state.cookies.jar)
  335. if self.mqtt:
  336. self.mqtt.setup_proxy()
  337. # TODO this stuff could probably be moved to mautrix-python
  338. async def get_notice_room(self) -> RoomID:
  339. if not self.notice_room:
  340. async with self._notice_room_lock:
  341. # If someone already created the room while this call was waiting,
  342. # don't make a new room
  343. if self.notice_room:
  344. return self.notice_room
  345. creation_content = {}
  346. if not self.config["bridge.federate_rooms"]:
  347. creation_content["m.federate"] = False
  348. self.notice_room = await self.az.intent.create_room(
  349. is_direct=True,
  350. invitees=[self.mxid],
  351. topic="Instagram bridge notices",
  352. creation_content=creation_content,
  353. )
  354. await self.update()
  355. return self.notice_room
  356. async def fill_bridge_state(self, state: BridgeState) -> None:
  357. await super().fill_bridge_state(state)
  358. if not state.remote_id:
  359. if self.igpk:
  360. state.remote_id = str(self.igpk)
  361. else:
  362. try:
  363. state.remote_id = self.state.user_id
  364. except IGUserIDNotFoundError:
  365. state.remote_id = None
  366. if self.username:
  367. state.remote_name = f"@{self.username}"
  368. async def get_bridge_states(self) -> list[BridgeState]:
  369. if not self.state:
  370. return []
  371. state = BridgeState(state_event=BridgeStateEvent.UNKNOWN_ERROR)
  372. if self.is_connected:
  373. state.state_event = BridgeStateEvent.CONNECTED
  374. elif self._is_refreshing or self.mqtt:
  375. state.state_event = BridgeStateEvent.TRANSIENT_DISCONNECT
  376. return [state]
  377. async def send_bridge_notice(
  378. self,
  379. text: str,
  380. edit: EventID | None = None,
  381. state_event: BridgeStateEvent | None = None,
  382. important: bool = False,
  383. error_code: str | None = None,
  384. error_message: str | None = None,
  385. info: dict | None = None,
  386. ) -> EventID | None:
  387. if state_event:
  388. await self.push_bridge_state(
  389. state_event,
  390. error=error_code,
  391. message=error_message if error_code else text,
  392. info=info,
  393. )
  394. if self.config["bridge.disable_bridge_notices"]:
  395. return None
  396. if not important and not self.config["bridge.unimportant_bridge_notices"]:
  397. self.log.debug("Not sending unimportant bridge notice: %s", text)
  398. return None
  399. event_id = None
  400. try:
  401. self.log.debug("Sending bridge notice: %s", text)
  402. content = TextMessageEventContent(
  403. body=text, msgtype=(MessageType.TEXT if important else MessageType.NOTICE)
  404. )
  405. if edit:
  406. content.set_edit(edit)
  407. # This is locked to prevent notices going out in the wrong order
  408. async with self._notice_send_lock:
  409. event_id = await self.az.intent.send_message(await self.get_notice_room(), content)
  410. except Exception:
  411. self.log.warning("Failed to send bridge notice", exc_info=True)
  412. return edit or event_id
  413. async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
  414. puppet = await pu.Puppet.get_by_pk(self.igpk)
  415. try:
  416. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  417. self.log.info("Automatically enabling custom puppet")
  418. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  419. except Exception:
  420. self.log.exception("Failed to automatically enable custom puppet")
  421. try:
  422. await puppet.update_info(user_info, self)
  423. except Exception:
  424. self.log.exception("Failed to update own puppet info")
  425. async def _try_sync(self) -> None:
  426. try:
  427. await self.sync()
  428. except Exception as e:
  429. self.log.exception("Exception while syncing")
  430. if isinstance(e, IGCheckpointError):
  431. self.log.debug("Checkpoint error content: %s", e.body)
  432. await self.push_bridge_state(
  433. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  434. )
  435. async def get_direct_chats(self) -> dict[UserID, list[RoomID]]:
  436. return {
  437. pu.Puppet.get_mxid_from_id(portal.other_user_pk): [portal.mxid]
  438. for portal in await DBPortal.find_private_chats_of(self.igpk)
  439. if portal.mxid
  440. }
  441. async def refresh(self, resync: bool = True, update_proxy: bool = False) -> None:
  442. self._is_refreshing = True
  443. try:
  444. await self.stop_listen()
  445. self.state.reset_pigeon_session_id()
  446. if update_proxy and self.proxy_handler.update_proxy_url(reason="reconnect"):
  447. await self.on_proxy_update()
  448. if resync:
  449. retry_count = 0
  450. minutes = 1
  451. while True:
  452. try:
  453. await self.sync()
  454. return
  455. except Exception as e:
  456. if retry_count >= 4 and minutes < 10:
  457. minutes += 1
  458. retry_count += 1
  459. s = "s" if minutes != 1 else ""
  460. self.log.exception(
  461. f"Error while syncing for refresh, retrying in {minutes} minute{s}"
  462. )
  463. if isinstance(e, IGCheckpointError):
  464. self.log.debug("Checkpoint error content: %s", e.body)
  465. await self.push_bridge_state(
  466. BridgeStateEvent.UNKNOWN_ERROR,
  467. error="unknown-error",
  468. message="An unknown error occurred while connecting to Instagram",
  469. info={"python_error": str(e)},
  470. )
  471. await asyncio.sleep(minutes * 60)
  472. else:
  473. self.start_listen()
  474. finally:
  475. self._is_refreshing = False
  476. async def _handle_checkpoint(
  477. self,
  478. e: IGChallengeError | IGConsentRequiredError,
  479. on: str,
  480. client: AndroidAPI | None = None,
  481. ) -> None:
  482. self.log.warning(f"Got checkpoint error on {on}: {e.body.serialize()}")
  483. client = client or self.client
  484. self.client = None
  485. self.mqtt = None
  486. if isinstance(e, IGConsentRequiredError):
  487. await self.push_bridge_state(
  488. BridgeStateEvent.BAD_CREDENTIALS,
  489. error="ig-consent-required",
  490. info=e.body.serialize(),
  491. )
  492. return
  493. error_code = "ig-checkpoint"
  494. try:
  495. resp = await client.challenge_reset()
  496. info = {
  497. "challenge_context": (
  498. resp.challenge_context.serialize() if resp.challenge_context_str else None
  499. ),
  500. "step_name": resp.step_name,
  501. "step_data": resp.step_data.serialize() if resp.step_data else None,
  502. "user_id": resp.user_id,
  503. "action": resp.action,
  504. "status": resp.status,
  505. "challenge": e.body.challenge.serialize() if e.body.challenge else None,
  506. }
  507. self.log.debug(f"Challenge state: {resp.serialize()}")
  508. if resp.challenge_context.challenge_type_enum == "HACKED_LOCK":
  509. error_code = "ig-checkpoint-locked"
  510. except Exception:
  511. self.log.exception("Error resetting challenge state")
  512. info = {"challenge": e.body.challenge.serialize() if e.body.challenge else None}
  513. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=error_code, info=info)
  514. async def _sync_thread(self, thread: Thread) -> bool:
  515. """
  516. Sync a specific thread. Returns whether the thread had messages after the last message in
  517. the database before the sync.
  518. """
  519. self.log.debug(f"Syncing thread {thread.thread_id}")
  520. forward_messages = thread.items
  521. assert self.client
  522. portal = await po.Portal.get_by_thread(thread, self.igpk)
  523. assert portal
  524. # Create or update the Matrix room
  525. if not portal.mxid:
  526. await portal.create_matrix_room(self, thread)
  527. else:
  528. await portal.update_matrix_room(self, thread)
  529. if not self.config["bridge.backfill.enable_initial"]:
  530. return True
  531. last_message = await DBMessage.get_last(portal.mxid)
  532. cursor = thread.oldest_cursor
  533. if last_message:
  534. original_number_of_messages = len(thread.items)
  535. new_messages = [
  536. m for m in thread.items if last_message.ig_timestamp_ms < m.timestamp_ms
  537. ]
  538. forward_messages = new_messages
  539. portal.log.debug(
  540. f"{len(new_messages)}/{original_number_of_messages} messages are after most recent"
  541. " message."
  542. )
  543. # Fetch more messages until we get back to messages that have been bridged already.
  544. while len(new_messages) > 0 and len(new_messages) == original_number_of_messages:
  545. await asyncio.sleep(self.config["bridge.backfill.incremental.page_delay"])
  546. portal.log.debug("Fetching more messages for forward backfill")
  547. resp = await self.client.get_thread(portal.thread_id, cursor=cursor)
  548. if len(resp.thread.items) == 0:
  549. break
  550. original_number_of_messages = len(resp.thread.items)
  551. new_messages = [
  552. m for m in resp.thread.items if last_message.ig_timestamp_ms < m.timestamp_ms
  553. ]
  554. forward_messages = new_messages + forward_messages
  555. cursor = resp.thread.oldest_cursor
  556. portal.log.debug(
  557. f"{len(new_messages)}/{original_number_of_messages} messages are after most "
  558. "recent message."
  559. )
  560. elif not portal.first_event_id:
  561. self.log.debug(
  562. f"Skipping backfilling {portal.thread_id} as the first event ID is not known"
  563. )
  564. return False
  565. if forward_messages:
  566. portal.cursor = cursor
  567. await portal.update()
  568. mark_read = thread.read_state == 0 or (
  569. (hours := self.config["bridge.backfill.unread_hours_threshold"]) > 0
  570. and (
  571. datetime.fromtimestamp(forward_messages[0].timestamp_ms / 1000)
  572. < datetime.now() - timedelta(hours=hours)
  573. )
  574. )
  575. base_insertion_event_id = await portal.backfill_message_page(
  576. self,
  577. list(reversed(forward_messages)),
  578. forward=True,
  579. last_message=last_message,
  580. mark_read=mark_read,
  581. )
  582. if (
  583. not self.bridge.homeserver_software.is_hungry
  584. and self.config["bridge.backfill.msc2716"]
  585. ):
  586. await portal.send_post_backfill_dummy(
  587. forward_messages[0].timestamp, base_insertion_event_id=base_insertion_event_id
  588. )
  589. if (
  590. mark_read
  591. and not self.bridge.homeserver_software.is_hungry
  592. and (puppet := await self.get_puppet())
  593. ):
  594. last_message = await DBMessage.get_last(portal.mxid)
  595. if last_message:
  596. await puppet.intent_for(portal).mark_read(portal.mxid, last_message.mxid)
  597. await portal._update_read_receipts(thread.last_seen_at)
  598. if self.config["bridge.backfill.msc2716"]:
  599. await portal.enqueue_immediate_backfill(self, 1)
  600. return len(forward_messages) > 0
  601. async def sync(self, increment_total_backfilled_portals: bool = False) -> None:
  602. await self.run_with_sync_lock(partial(self._sync, increment_total_backfilled_portals))
  603. async def _sync(self, increment_total_backfilled_portals: bool = False) -> None:
  604. if not self._listen_task:
  605. self.state.reset_pigeon_session_id()
  606. sleep_minutes = 2
  607. while True:
  608. try:
  609. resp = await self.client.get_inbox()
  610. break
  611. except IGNotLoggedInError as e:
  612. self.log.exception("Got not logged in error while syncing")
  613. await self.logout(error=e)
  614. return
  615. except IGRateLimitError as e:
  616. self.log.error(
  617. "Got ratelimit error while trying to get inbox (%s), retrying in %d minutes",
  618. e.body,
  619. sleep_minutes,
  620. )
  621. await self.push_bridge_state(
  622. BridgeStateEvent.TRANSIENT_DISCONNECT, error="ig-rate-limit"
  623. )
  624. await asyncio.sleep(sleep_minutes * 60)
  625. sleep_minutes += 2
  626. except IGCheckpointError as e:
  627. self.log.debug("Checkpoint error content: %s", e.body)
  628. raise
  629. except (IGChallengeError, IGConsentRequiredError) as e:
  630. await self._handle_checkpoint(e, on="sync")
  631. return
  632. self.seq_id = resp.seq_id
  633. self.snapshot_at_ms = resp.snapshot_at_ms
  634. await self.save_seq_id()
  635. if not self._listen_task:
  636. self.start_listen(is_after_sync=True)
  637. sync_count = min(
  638. self.config["bridge.backfill.max_conversations"],
  639. self.config["bridge.max_startup_thread_sync_count"],
  640. )
  641. self.log.debug(f"Fetching {sync_count} threads, 20 at a time...")
  642. local_limit: int | None = sync_count
  643. if sync_count == 0:
  644. return
  645. elif sync_count < 0:
  646. local_limit = None
  647. await self._sync_threads_with_delay(
  648. self.client.iter_inbox(
  649. self._update_seq_id_and_cursor, start_at=resp, local_limit=local_limit
  650. ),
  651. stop_when_threads_have_no_messages_to_backfill=True,
  652. increment_total_backfilled_portals=increment_total_backfilled_portals,
  653. local_limit=local_limit,
  654. )
  655. try:
  656. await self.update_direct_chats()
  657. except Exception:
  658. self.log.exception("Error updating direct chat list")
  659. async def backfill_threads(self):
  660. try:
  661. await self.run_with_sync_lock(self._backfill_threads)
  662. except Exception:
  663. self.log.exception("Error in thread backfill loop")
  664. async def _backfill_threads(self):
  665. assert self.client
  666. if not self.config["bridge.backfill.enable"]:
  667. return
  668. max_conversations = self.config["bridge.backfill.max_conversations"] or 0
  669. if 0 <= max_conversations <= (self.total_backfilled_portals or 0):
  670. self.log.info("Backfill max_conversations count reached, not syncing any more portals")
  671. return
  672. elif self.thread_sync_completed:
  673. self.log.debug("Thread backfill is marked as completed, not syncing more portals")
  674. return
  675. local_limit = (
  676. max_conversations - (self.total_backfilled_portals or 0)
  677. if max_conversations >= 0
  678. else None
  679. )
  680. start_at = None
  681. if self.oldest_cursor:
  682. start_at = DMInboxResponse(
  683. status="",
  684. seq_id=self.seq_id,
  685. snapshot_at_ms=0,
  686. pending_requests_total=0,
  687. has_pending_top_requests=False,
  688. viewer=None,
  689. inbox=DMInbox(
  690. threads=[],
  691. has_older=True,
  692. unseen_count=0,
  693. unseen_count_ts=0,
  694. blended_inbox_enabled=False,
  695. oldest_cursor=self.oldest_cursor,
  696. ),
  697. )
  698. backoff = self.config.get("bridge.backfill.backoff.thread_list", 300)
  699. await self._sync_threads_with_delay(
  700. self.client.iter_inbox(
  701. self._update_seq_id_and_cursor,
  702. start_at=start_at,
  703. local_limit=local_limit,
  704. rate_limit_exceeded_backoff=backoff,
  705. ),
  706. increment_total_backfilled_portals=True,
  707. local_limit=local_limit,
  708. )
  709. await self.update_direct_chats()
  710. def _update_seq_id_and_cursor(self, seq_id: int, cursor: str | None):
  711. self.seq_id = seq_id
  712. if cursor:
  713. self.oldest_cursor = cursor
  714. async def _sync_threads_with_delay(
  715. self,
  716. threads: AsyncIterable[Thread],
  717. increment_total_backfilled_portals: bool = False,
  718. stop_when_threads_have_no_messages_to_backfill: bool = False,
  719. local_limit: int | None = None,
  720. ):
  721. sync_delay = self.config["bridge.backfill.min_sync_thread_delay"]
  722. last_thread_sync_ts = 0.0
  723. found_thread_count = 0
  724. async for thread in threads:
  725. found_thread_count += 1
  726. now = time.monotonic()
  727. if now < last_thread_sync_ts + sync_delay:
  728. delay = last_thread_sync_ts + sync_delay - now
  729. self.log.debug("Thread sync is happening too quickly. Waiting for %ds", delay)
  730. await asyncio.sleep(delay)
  731. last_thread_sync_ts = time.monotonic()
  732. had_new_messages = await self._sync_thread(thread)
  733. if not had_new_messages and stop_when_threads_have_no_messages_to_backfill:
  734. self.log.debug("Got to threads with no new messages. Stopping sync.")
  735. return
  736. if increment_total_backfilled_portals:
  737. self.total_backfilled_portals = (self.total_backfilled_portals or 0) + 1
  738. await self.update()
  739. if local_limit is None or found_thread_count < local_limit:
  740. if local_limit is None:
  741. self.log.info(
  742. "Reached end of thread list with no limit, marking thread sync as completed"
  743. )
  744. else:
  745. self.log.info(
  746. f"Reached end of thread list (got {found_thread_count} with "
  747. f"limit {local_limit}), marking thread sync as completed"
  748. )
  749. self.thread_sync_completed = True
  750. await self.update()
  751. async def run_with_sync_lock(self, func: Callable[[], Awaitable]):
  752. with self._sync_lock:
  753. retry_count = 0
  754. while retry_count < 5:
  755. try:
  756. retry_count += 1
  757. await func()
  758. # The sync was successful. Exit the loop.
  759. return
  760. except IGNotLoggedInError as e:
  761. await self.logout(error=e)
  762. return
  763. except Exception:
  764. self.log.exception(
  765. "Failed to sync threads. Waiting 30 seconds before retrying sync."
  766. )
  767. await asyncio.sleep(30)
  768. # If we get here, it means that the sync has failed five times. If this happens, most
  769. # likely something very bad has happened.
  770. self.log.error("Failed to sync threads five times. Will not retry.")
  771. def start_listen(self, is_after_sync: bool = False) -> None:
  772. self.shutdown = False
  773. task = self._listen(
  774. seq_id=self.seq_id, snapshot_at_ms=self.snapshot_at_ms, is_after_sync=is_after_sync
  775. )
  776. self._listen_task = self.loop.create_task(task)
  777. async def delayed_start_listen(self, sleep: int) -> None:
  778. await asyncio.sleep(sleep)
  779. if self.is_connected:
  780. self.log.debug(
  781. "Already reconnected before delay after MQTT reconnection error finished"
  782. )
  783. else:
  784. self.log.debug("Reconnecting after MQTT connection error")
  785. self.start_listen()
  786. async def fetch_user_and_reconnect(self, sleep_first: int | None = None) -> None:
  787. if sleep_first:
  788. await asyncio.sleep(sleep_first)
  789. if self.is_connected:
  790. self.log.debug("Canceling user fetch, already reconnected")
  791. return
  792. self.log.debug("Refetching current user after disconnection")
  793. errors = 0
  794. while True:
  795. try:
  796. resp = await self.client.current_user()
  797. except RETRYABLE_PROXY_EXCEPTIONS as e:
  798. # These are retried by the client up to 10 times, but we actually want to retry
  799. # these indefinitely so we capture them here again and retry.
  800. self.log.warning(
  801. f"Proxy error fetching user from Instagram: {e}, retrying in 1 minute",
  802. )
  803. await asyncio.sleep(60)
  804. except IGNotLoggedInError as e:
  805. self.log.warning(f"Failed to reconnect to Instagram: {e}, logging out")
  806. await self.logout(error=e)
  807. return
  808. except (IGChallengeError, IGConsentRequiredError) as e:
  809. await self._handle_checkpoint(e, on="reconnect")
  810. return
  811. except IGUnknownError as e:
  812. if "non-JSON body" not in e:
  813. raise
  814. errors += 1
  815. if errors > 10:
  816. raise
  817. self.log.warning(
  818. "Non-JSON body while trying to check user for reconnection, retrying in 10s"
  819. )
  820. await asyncio.sleep(10)
  821. except Exception as e:
  822. self.log.exception("Error while reconnecting to Instagram")
  823. if isinstance(e, IGCheckpointError):
  824. self.log.debug("Checkpoint error content: %s", e.body)
  825. await self.push_bridge_state(
  826. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  827. )
  828. return
  829. else:
  830. self.log.debug(f"Confirmed current user {resp.user.pk}")
  831. self.start_listen()
  832. return
  833. async def _listen(self, seq_id: int, snapshot_at_ms: int, is_after_sync: bool) -> None:
  834. try:
  835. await self.mqtt.listen(
  836. graphql_subs={
  837. GraphQLSubscription.app_presence(),
  838. GraphQLSubscription.direct_typing(self.state.user_id),
  839. GraphQLSubscription.direct_status(),
  840. },
  841. skywalker_subs={
  842. SkywalkerSubscription.direct_sub(self.state.user_id),
  843. SkywalkerSubscription.live_sub(self.state.user_id),
  844. },
  845. seq_id=seq_id,
  846. snapshot_at_ms=snapshot_at_ms,
  847. )
  848. except IrisSubscribeError as e:
  849. if is_after_sync:
  850. self.log.exception("Got IrisSubscribeError right after refresh")
  851. await self.send_bridge_notice(
  852. f"Reconnecting failed again after refresh: {e}",
  853. important=True,
  854. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  855. error_code="ig-refresh-connection-error",
  856. error_message=str(e),
  857. info={"python_error": str(e)},
  858. )
  859. else:
  860. self.log.warning(f"Got IrisSubscribeError {e}, refreshing...")
  861. background_task.create(self.refresh())
  862. except MQTTReconnectionError as e:
  863. self.log.warning(
  864. f"Unexpected connection error: {e}, reconnecting in 1 minute", exc_info=True
  865. )
  866. await self.send_bridge_notice(
  867. f"Error in listener: {e}",
  868. important=True,
  869. state_event=BridgeStateEvent.TRANSIENT_DISCONNECT,
  870. error_code="ig-connection-error-socket",
  871. )
  872. self.mqtt.disconnect()
  873. background_task.create(self.delayed_start_listen(sleep=60))
  874. except (MQTTNotConnected, MQTTNotLoggedIn, MQTTConnectionUnauthorized) as e:
  875. self.log.warning(f"Unexpected connection error: {e}, checking auth and reconnecting")
  876. await self.send_bridge_notice(
  877. f"Error in listener: {e}",
  878. important=True,
  879. state_event=BridgeStateEvent.TRANSIENT_DISCONNECT,
  880. error_code="ig-connection-error-maybe-auth",
  881. )
  882. self.mqtt.disconnect()
  883. background_task.create(self.fetch_user_and_reconnect())
  884. except Exception as e:
  885. self.log.exception("Fatal error in listener, reconnecting in 5 minutes")
  886. await self.send_bridge_notice(
  887. "Fatal error in listener (see logs for more info)",
  888. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  889. important=True,
  890. error_code="ig-unknown-connection-error",
  891. info={"python_error": str(e)},
  892. )
  893. self.mqtt.disconnect()
  894. background_task.create(self.fetch_user_and_reconnect(sleep_first=300))
  895. else:
  896. if not self.shutdown:
  897. await self.send_bridge_notice(
  898. "Instagram connection closed without error",
  899. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  900. error_code="ig-disconnected",
  901. )
  902. finally:
  903. self._listen_task = None
  904. self._is_connected = False
  905. self._track_metric(METRIC_CONNECTED, False)
  906. async def stop_listen(self) -> None:
  907. if self.mqtt:
  908. self.shutdown = True
  909. self.mqtt.disconnect()
  910. if self._listen_task:
  911. await self._listen_task
  912. self.shutdown = False
  913. self._track_metric(METRIC_CONNECTED, False)
  914. self._is_connected = False
  915. await self.update()
  916. def stop_backfill_tasks(self) -> None:
  917. if self._backfill_loop_task:
  918. self._backfill_loop_task.cancel()
  919. self._backfill_loop_task = None
  920. if self._thread_sync_task:
  921. self._thread_sync_task.cancel()
  922. self._thread_sync_task = None
  923. async def logout(self, error: IGNotLoggedInError | None = None) -> None:
  924. await self.stop_listen()
  925. self.stop_backfill_tasks()
  926. if self.client and error is None:
  927. try:
  928. await self.client.logout(one_tap_app_login=False)
  929. except Exception:
  930. self.log.debug("Exception logging out", exc_info=True)
  931. if self.mqtt:
  932. self.mqtt.disconnect()
  933. self._track_metric(METRIC_CONNECTED, False)
  934. self._track_metric(METRIC_LOGGED_IN, False)
  935. if error is None:
  936. await self.push_bridge_state(BridgeStateEvent.LOGGED_OUT)
  937. puppet = await pu.Puppet.get_by_pk(self.igpk, create=False)
  938. if puppet and puppet.is_real_user:
  939. await puppet.switch_mxid(None, None)
  940. try:
  941. del self.by_igpk[self.igpk]
  942. except KeyError:
  943. pass
  944. self.igpk = None
  945. else:
  946. self.log.debug("Auth error body: %s", error.body.serialize())
  947. await self.send_bridge_notice(
  948. f"You have been logged out of Instagram: {error.proper_message}",
  949. important=True,
  950. state_event=BridgeStateEvent.BAD_CREDENTIALS,
  951. error_code="ig-auth-error",
  952. error_message=error.proper_message,
  953. info={"cnd_action": "reauth"},
  954. )
  955. self.client = None
  956. self.mqtt = None
  957. self.state = None
  958. self.seq_id = None
  959. self.snapshot_at_ms = None
  960. self.thread_sync_completed = False
  961. self._is_logged_in = False
  962. await self.update()
  963. # endregion
  964. # region Event handlers
  965. async def _save_seq_id_after_sleep(self) -> None:
  966. await asyncio.sleep(120)
  967. self._seq_id_save_task = None
  968. self.log.trace("Saving sequence ID %d/%d", self.seq_id, self.snapshot_at_ms)
  969. try:
  970. await self.save_seq_id()
  971. except Exception:
  972. self.log.exception("Error saving sequence ID")
  973. async def update_seq_id(self, evt: NewSequenceID) -> None:
  974. self.seq_id = evt.seq_id
  975. self.snapshot_at_ms = evt.snapshot_at_ms
  976. if not self._seq_id_save_task or self._seq_id_save_task.done():
  977. self.log.trace("Starting seq id save task (%d/%d)", evt.seq_id, evt.snapshot_at_ms)
  978. self._seq_id_save_task = asyncio.create_task(self._save_seq_id_after_sleep())
  979. else:
  980. self.log.trace("Not starting seq id save task (%d/%d)", evt.seq_id, evt.snapshot_at_ms)
  981. @async_time(METRIC_MESSAGE)
  982. async def handle_message(self, evt: MessageSyncEvent) -> None:
  983. portal = await po.Portal.get_by_thread_id(evt.message.thread_id, receiver=self.igpk)
  984. if not portal or not portal.mxid:
  985. self.log.debug("Got message in thread with no portal, getting info...")
  986. resp = await self.client.get_thread(evt.message.thread_id)
  987. portal = await po.Portal.get_by_thread(resp.thread, self.igpk)
  988. self.log.debug("Got info for unknown portal, creating room")
  989. await portal.create_matrix_room(self, resp.thread)
  990. if not portal.mxid:
  991. self.log.warning(
  992. "Room creation appears to have failed, "
  993. f"dropping message in {evt.message.thread_id}"
  994. )
  995. return
  996. self.log.trace(f"Received message sync event {evt.message}")
  997. if evt.message.new_reaction:
  998. await portal.handle_instagram_reaction(
  999. evt.message, remove=evt.message.op == Operation.REMOVE
  1000. )
  1001. return
  1002. sender = await pu.Puppet.get_by_pk(evt.message.user_id) if evt.message.user_id else None
  1003. if evt.message.op == Operation.ADD:
  1004. if not sender:
  1005. # I don't think we care about adds with no sender
  1006. return
  1007. await portal.handle_instagram_item(self, sender, evt.message)
  1008. elif evt.message.op == Operation.REMOVE:
  1009. # Removes don't have a sender, only the message sender can unsend messages anyway
  1010. await portal.handle_instagram_remove(evt.message.item_id)
  1011. elif evt.message.op == Operation.REPLACE:
  1012. await portal.handle_instagram_update(evt.message)
  1013. @async_time(METRIC_THREAD_SYNC)
  1014. async def handle_thread_sync(self, evt: ThreadSyncEvent) -> None:
  1015. self.log.trace("Thread sync event content: %s", evt)
  1016. portal = await po.Portal.get_by_thread(evt, receiver=self.igpk)
  1017. if portal.mxid:
  1018. self.log.debug("Got thread sync event for %s with existing portal", portal.thread_id)
  1019. await portal.update_matrix_room(self, evt)
  1020. elif evt.is_group:
  1021. self.log.debug(
  1022. "Got thread sync event for group %s without existing portal, creating room",
  1023. portal.thread_id,
  1024. )
  1025. await portal.create_matrix_room(self, evt)
  1026. else:
  1027. self.log.debug(
  1028. "Got thread sync event for DM %s without existing portal, ignoring",
  1029. portal.thread_id,
  1030. )
  1031. async def handle_thread_remove(self, evt: ThreadRemoveEvent) -> None:
  1032. self.log.debug("Got thread remove event: %s", evt.serialize())
  1033. @async_time(METRIC_RTD)
  1034. async def handle_rtd(self, evt: RealtimeDirectEvent) -> None:
  1035. if not isinstance(evt.value, ActivityIndicatorData):
  1036. return
  1037. now = int(time.time() * 1000)
  1038. date = evt.value.timestamp_ms
  1039. expiry = date + evt.value.ttl
  1040. if expiry < now:
  1041. return
  1042. if evt.activity_indicator_id in self._activity_indicator_ids:
  1043. return
  1044. # TODO clear expired items from this dict
  1045. self._activity_indicator_ids[evt.activity_indicator_id] = expiry
  1046. puppet = await pu.Puppet.get_by_pk(int(evt.value.sender_id))
  1047. portal = await po.Portal.get_by_thread_id(evt.thread_id, receiver=self.igpk)
  1048. if not puppet or not portal or not portal.mxid:
  1049. return
  1050. is_typing = evt.value.activity_status != TypingStatus.OFF
  1051. if puppet.pk == self.igpk:
  1052. self.remote_typing_status = TypingStatus.TEXT if is_typing else TypingStatus.OFF
  1053. await puppet.intent_for(portal).set_typing(portal.mxid, timeout=evt.value.ttl)
  1054. # endregion
  1055. # region Database getters
  1056. def _add_to_cache(self) -> None:
  1057. self.by_mxid[self.mxid] = self
  1058. if self.igpk:
  1059. self.by_igpk[self.igpk] = self
  1060. @classmethod
  1061. @async_getter_lock
  1062. async def get_by_mxid(cls, mxid: UserID, *, create: bool = True) -> User | None:
  1063. # Never allow ghosts to be users
  1064. if pu.Puppet.get_id_from_mxid(mxid):
  1065. return None
  1066. try:
  1067. return cls.by_mxid[mxid]
  1068. except KeyError:
  1069. pass
  1070. user = cast(cls, await super().get_by_mxid(mxid))
  1071. if user is not None:
  1072. user._add_to_cache()
  1073. return user
  1074. if create:
  1075. user = cls(mxid)
  1076. await user.insert()
  1077. user._add_to_cache()
  1078. return user
  1079. return None
  1080. @classmethod
  1081. @async_getter_lock
  1082. async def get_by_igpk(cls, igpk: int) -> User | None:
  1083. try:
  1084. return cls.by_igpk[igpk]
  1085. except KeyError:
  1086. pass
  1087. user = cast(cls, await super().get_by_igpk(igpk))
  1088. if user is not None:
  1089. user._add_to_cache()
  1090. return user
  1091. return None
  1092. @classmethod
  1093. async def all_logged_in(cls) -> AsyncGenerator[User, None]:
  1094. users = await super().all_logged_in()
  1095. user: cls
  1096. for index, user in enumerate(users):
  1097. try:
  1098. yield cls.by_mxid[user.mxid]
  1099. except KeyError:
  1100. user._add_to_cache()
  1101. yield user
  1102. # endregion