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