user.py 47 KB

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