user.py 48 KB

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