user.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2023 Tulir Asokan
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from __future__ import annotations
  17. from typing import TYPE_CHECKING, AsyncGenerator, AsyncIterable, Awaitable, Callable, cast
  18. from datetime import datetime, timedelta
  19. from functools import partial
  20. import asyncio
  21. import logging
  22. import time
  23. from aiohttp import ClientConnectionError
  24. from mauigpapi import AndroidAPI, AndroidMQTT, AndroidState, ProxyHandler
  25. from mauigpapi.errors import (
  26. IGChallengeError,
  27. IGCheckpointError,
  28. IGConsentRequiredError,
  29. IGNotLoggedInError,
  30. IGRateLimitError,
  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.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}",
  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're not logged into Instagram",
  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(BridgeStateEvent.BAD_CREDENTIALS, error="logged-out")
  210. return
  211. client = AndroidAPI(
  212. self.state,
  213. log=self.api_log,
  214. proxy_handler=self.proxy_handler,
  215. )
  216. if not user:
  217. try:
  218. resp = await client.current_user()
  219. user = resp.user
  220. except IGNotLoggedInError as e:
  221. self.log.warning(f"Failed to connect to Instagram: {e}, logging out")
  222. await self.logout(error=e)
  223. return
  224. except IGCheckpointError as e:
  225. self.log.debug("Checkpoint error content: %s", e.body)
  226. raise
  227. except (IGChallengeError, IGConsentRequiredError) as e:
  228. await self._handle_checkpoint(e, on="connect", client=client)
  229. return
  230. self.client = client
  231. self._is_logged_in = True
  232. self.igpk = user.pk
  233. self.username = user.username
  234. await self.push_bridge_state(BridgeStateEvent.CONNECTING)
  235. self._track_metric(METRIC_LOGGED_IN, True)
  236. self.by_igpk[self.igpk] = self
  237. self.mqtt = AndroidMQTT(
  238. self.state,
  239. log=self.ig_base_log.getChild("mqtt").getChild(self.mxid),
  240. proxy_handler=self.proxy_handler,
  241. )
  242. self.mqtt.add_event_handler(Connect, self.on_connect)
  243. self.mqtt.add_event_handler(Disconnect, self.on_disconnect)
  244. self.mqtt.add_event_handler(NewSequenceID, self.update_seq_id)
  245. self.mqtt.add_event_handler(MessageSyncEvent, self.handle_message)
  246. self.mqtt.add_event_handler(ThreadSyncEvent, self.handle_thread_sync)
  247. self.mqtt.add_event_handler(ThreadRemoveEvent, self.handle_thread_remove)
  248. self.mqtt.add_event_handler(RealtimeDirectEvent, self.handle_rtd)
  249. self.mqtt.add_event_handler(ProxyUpdate, self.on_proxy_update)
  250. await self.update()
  251. self.loop.create_task(self._try_sync_puppet(user))
  252. self.loop.create_task(self._post_connect())
  253. async def _post_connect(self):
  254. # Backfill requests are handled synchronously so as not to overload the homeserver.
  255. # Users can configure their backfill stages to be more or less aggressive with backfilling
  256. # to try and avoid getting banned.
  257. if not self._backfill_loop_task or self._backfill_loop_task.done():
  258. self._backfill_loop_task = asyncio.create_task(self._handle_backfill_requests_loop())
  259. if not self.seq_id:
  260. await self._try_sync()
  261. else:
  262. self.log.debug("Connecting to MQTT directly as resync_on_startup is false")
  263. self.start_listen()
  264. if self.config["bridge.backfill.enable"]:
  265. if self._thread_sync_task and not self._thread_sync_task.done():
  266. self.log.warning("Cancelling existing background thread sync task")
  267. self._thread_sync_task.cancel()
  268. self._thread_sync_task = asyncio.create_task(self.backfill_threads())
  269. async def _handle_backfill_requests_loop(self) -> None:
  270. if not self.config["bridge.backfill.enable"] or not self.config["bridge.backfill.msc2716"]:
  271. return
  272. while True:
  273. await self._sync_lock.wait("backfill request")
  274. req = await Backfill.get_next(self.mxid)
  275. if not req:
  276. await asyncio.sleep(30)
  277. continue
  278. self.log.info("Backfill request %s", req)
  279. try:
  280. portal = await po.Portal.get_by_thread_id(
  281. req.portal_thread_id, receiver=req.portal_receiver
  282. )
  283. await req.mark_dispatched()
  284. await portal.backfill(self, req)
  285. await req.mark_done()
  286. except IGNotLoggedInError as e:
  287. self.log.exception("User got logged out during backfill loop")
  288. await self.logout(error=e)
  289. break
  290. except (IGChallengeError, IGConsentRequiredError) as e:
  291. self.log.exception("User got a challenge during backfill loop")
  292. await self._handle_checkpoint(e, on="backfill")
  293. break
  294. except Exception as e:
  295. self.log.exception("Failed to backfill portal %s: %s", req.portal_thread_id, e)
  296. # Don't try again to backfill this portal for a minute.
  297. await req.set_cooldown_timeout(60)
  298. self._backfill_loop_task = None
  299. async def on_connect(self, evt: Connect) -> None:
  300. self.log.debug("Connected to Instagram")
  301. self._track_metric(METRIC_CONNECTED, True)
  302. self._is_connected = True
  303. await self.send_bridge_notice("Connected to Instagram")
  304. await self.push_bridge_state(BridgeStateEvent.CONNECTED)
  305. async def on_disconnect(self, evt: Disconnect) -> None:
  306. self.log.debug("Disconnected from Instagram")
  307. self._track_metric(METRIC_CONNECTED, False)
  308. self._is_connected = False
  309. async def on_proxy_update(self, evt: ProxyUpdate | None = None) -> None:
  310. if self.client:
  311. self.client.setup_http(self.state.cookies.jar)
  312. # TODO this stuff could probably be moved to mautrix-python
  313. async def get_notice_room(self) -> RoomID:
  314. if not self.notice_room:
  315. async with self._notice_room_lock:
  316. # If someone already created the room while this call was waiting,
  317. # don't make a new room
  318. if self.notice_room:
  319. return self.notice_room
  320. creation_content = {}
  321. if not self.config["bridge.federate_rooms"]:
  322. creation_content["m.federate"] = False
  323. self.notice_room = await self.az.intent.create_room(
  324. is_direct=True,
  325. invitees=[self.mxid],
  326. topic="Instagram bridge notices",
  327. creation_content=creation_content,
  328. )
  329. await self.update()
  330. return self.notice_room
  331. async def fill_bridge_state(self, state: BridgeState) -> None:
  332. await super().fill_bridge_state(state)
  333. if not state.remote_id:
  334. if self.igpk:
  335. state.remote_id = str(self.igpk)
  336. else:
  337. try:
  338. state.remote_id = self.state.user_id
  339. except IGUserIDNotFoundError:
  340. state.remote_id = None
  341. if self.username:
  342. state.remote_name = f"@{self.username}"
  343. async def get_bridge_states(self) -> list[BridgeState]:
  344. if not self.state:
  345. return []
  346. state = BridgeState(state_event=BridgeStateEvent.UNKNOWN_ERROR)
  347. if self.is_connected:
  348. state.state_event = BridgeStateEvent.CONNECTED
  349. elif self._is_refreshing or self.mqtt:
  350. state.state_event = BridgeStateEvent.TRANSIENT_DISCONNECT
  351. return [state]
  352. async def send_bridge_notice(
  353. self,
  354. text: str,
  355. edit: EventID | None = None,
  356. state_event: BridgeStateEvent | None = None,
  357. important: bool = False,
  358. error_code: str | None = None,
  359. error_message: str | None = None,
  360. info: dict | None = None,
  361. ) -> EventID | None:
  362. if state_event:
  363. await self.push_bridge_state(
  364. state_event,
  365. error=error_code,
  366. message=error_message if error_code else text,
  367. info=info,
  368. )
  369. if self.config["bridge.disable_bridge_notices"]:
  370. return None
  371. if not important and not self.config["bridge.unimportant_bridge_notices"]:
  372. self.log.debug("Not sending unimportant bridge notice: %s", text)
  373. return None
  374. event_id = None
  375. try:
  376. self.log.debug("Sending bridge notice: %s", text)
  377. content = TextMessageEventContent(
  378. body=text, msgtype=(MessageType.TEXT if important else MessageType.NOTICE)
  379. )
  380. if edit:
  381. content.set_edit(edit)
  382. # This is locked to prevent notices going out in the wrong order
  383. async with self._notice_send_lock:
  384. event_id = await self.az.intent.send_message(await self.get_notice_room(), content)
  385. except Exception:
  386. self.log.warning("Failed to send bridge notice", exc_info=True)
  387. return edit or event_id
  388. async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
  389. puppet = await pu.Puppet.get_by_pk(self.igpk)
  390. try:
  391. await puppet.update_info(user_info, self)
  392. except Exception:
  393. self.log.exception("Failed to update own puppet info")
  394. try:
  395. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  396. self.log.info(f"Automatically enabling custom puppet")
  397. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  398. except Exception:
  399. self.log.exception("Failed to automatically enable custom puppet")
  400. async def _try_sync(self) -> None:
  401. try:
  402. await self.sync()
  403. except Exception as e:
  404. self.log.exception("Exception while syncing")
  405. if isinstance(e, IGCheckpointError):
  406. self.log.debug("Checkpoint error content: %s", e.body)
  407. await self.push_bridge_state(
  408. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  409. )
  410. async def get_direct_chats(self) -> dict[UserID, list[RoomID]]:
  411. return {
  412. pu.Puppet.get_mxid_from_id(portal.other_user_pk): [portal.mxid]
  413. for portal in await DBPortal.find_private_chats_of(self.igpk)
  414. if portal.mxid
  415. }
  416. async def refresh(self, resync: bool = True) -> None:
  417. self._is_refreshing = True
  418. try:
  419. await self.stop_listen()
  420. self.state.reset_pigeon_session_id()
  421. if resync:
  422. retry_count = 0
  423. minutes = 1
  424. while True:
  425. try:
  426. await self.sync()
  427. return
  428. except Exception as e:
  429. if retry_count >= 4 and minutes < 10:
  430. minutes += 1
  431. retry_count += 1
  432. s = "s" if minutes != 1 else ""
  433. self.log.exception(
  434. f"Error while syncing for refresh, retrying in {minutes} minute{s}"
  435. )
  436. if isinstance(e, IGCheckpointError):
  437. self.log.debug("Checkpoint error content: %s", e.body)
  438. await self.push_bridge_state(
  439. BridgeStateEvent.UNKNOWN_ERROR,
  440. error="unknown-error",
  441. message="An unknown error occurred while connecting to Instagram",
  442. info={"python_error": str(e)},
  443. )
  444. await asyncio.sleep(minutes * 60)
  445. else:
  446. self.start_listen()
  447. finally:
  448. self._is_refreshing = False
  449. self.proxy_handler.update_proxy_url()
  450. async def _handle_checkpoint(
  451. self,
  452. e: IGChallengeError | IGConsentRequiredError,
  453. on: str,
  454. client: AndroidAPI | None = None,
  455. ) -> None:
  456. self.log.warning(f"Got checkpoint error on {on}: {e.body.serialize()}")
  457. client = client or self.client
  458. self.client = None
  459. self.mqtt = None
  460. if isinstance(e, IGConsentRequiredError):
  461. await self.push_bridge_state(
  462. BridgeStateEvent.BAD_CREDENTIALS,
  463. error="ig-consent-required",
  464. info=e.body.serialize(),
  465. )
  466. return
  467. error_code = "ig-checkpoint"
  468. try:
  469. resp = await client.challenge_reset()
  470. info = {
  471. "challenge_context": (
  472. resp.challenge_context.serialize() if resp.challenge_context_str else None
  473. ),
  474. "step_name": resp.step_name,
  475. "step_data": resp.step_data.serialize() if resp.step_data else None,
  476. "user_id": resp.user_id,
  477. "action": resp.action,
  478. "status": resp.status,
  479. "challenge": e.body.challenge.serialize() if e.body.challenge else None,
  480. }
  481. self.log.debug(f"Challenge state: {resp.serialize()}")
  482. if resp.challenge_context.challenge_type_enum == "HACKED_LOCK":
  483. error_code = "ig-checkpoint-locked"
  484. except Exception:
  485. self.log.exception("Error resetting challenge state")
  486. info = {"challenge": e.body.challenge.serialize() if e.body.challenge else None}
  487. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=error_code, info=info)
  488. async def _sync_thread(self, thread: Thread) -> bool:
  489. """
  490. Sync a specific thread. Returns whether the thread had messages after the last message in
  491. the database before the sync.
  492. """
  493. self.log.debug(f"Syncing thread {thread.thread_id}")
  494. forward_messages = thread.items
  495. assert self.client
  496. portal = await po.Portal.get_by_thread(thread, self.igpk)
  497. assert portal
  498. # Create or update the Matrix room
  499. if not portal.mxid:
  500. await portal.create_matrix_room(self, thread)
  501. else:
  502. await portal.update_matrix_room(self, thread)
  503. if not self.config["bridge.backfill.enable_initial"]:
  504. return True
  505. last_message = await DBMessage.get_last(portal.mxid)
  506. cursor = thread.oldest_cursor
  507. if last_message:
  508. original_number_of_messages = len(thread.items)
  509. new_messages = [
  510. m for m in thread.items if last_message.ig_timestamp_ms < m.timestamp_ms
  511. ]
  512. forward_messages = new_messages
  513. portal.log.debug(
  514. f"{len(new_messages)}/{original_number_of_messages} messages are after most recent"
  515. " message."
  516. )
  517. # Fetch more messages until we get back to messages that have been bridged already.
  518. while len(new_messages) > 0 and len(new_messages) == original_number_of_messages:
  519. await asyncio.sleep(self.config["bridge.backfill.incremental.page_delay"])
  520. portal.log.debug("Fetching more messages for forward backfill")
  521. resp = await self.client.get_thread(portal.thread_id, cursor=cursor)
  522. if len(resp.thread.items) == 0:
  523. break
  524. original_number_of_messages = len(resp.thread.items)
  525. new_messages = [
  526. m for m in resp.thread.items if last_message.ig_timestamp_ms < m.timestamp_ms
  527. ]
  528. forward_messages = new_messages + forward_messages
  529. cursor = resp.thread.oldest_cursor
  530. portal.log.debug(
  531. f"{len(new_messages)}/{original_number_of_messages} messages are after most "
  532. "recent message."
  533. )
  534. elif not portal.first_event_id:
  535. self.log.debug(
  536. f"Skipping backfilling {portal.thread_id} as the first event ID is not known"
  537. )
  538. return False
  539. if forward_messages:
  540. portal.cursor = cursor
  541. await portal.update()
  542. mark_read = thread.read_state == 0 or (
  543. (hours := self.config["bridge.backfill.unread_hours_threshold"]) > 0
  544. and (
  545. datetime.fromtimestamp(forward_messages[0].timestamp_ms / 1000)
  546. < datetime.now() - timedelta(hours=hours)
  547. )
  548. )
  549. base_insertion_event_id = await portal.backfill_message_page(
  550. self,
  551. list(reversed(forward_messages)),
  552. forward=True,
  553. last_message=last_message,
  554. mark_read=mark_read,
  555. )
  556. if (
  557. not self.bridge.homeserver_software.is_hungry
  558. and self.config["bridge.backfill.msc2716"]
  559. ):
  560. await portal.send_post_backfill_dummy(
  561. forward_messages[0].timestamp, base_insertion_event_id=base_insertion_event_id
  562. )
  563. if (
  564. mark_read
  565. and not self.bridge.homeserver_software.is_hungry
  566. and (puppet := await self.get_puppet())
  567. ):
  568. last_message = await DBMessage.get_last(portal.mxid)
  569. if last_message:
  570. await puppet.intent_for(portal).mark_read(portal.mxid, last_message.mxid)
  571. await portal._update_read_receipts(thread.last_seen_at)
  572. if self.config["bridge.backfill.msc2716"]:
  573. await portal.enqueue_immediate_backfill(self, 1)
  574. return len(forward_messages) > 0
  575. async def _maybe_update_proxy(self, source: str) -> None:
  576. if not self._listen_task:
  577. self.proxy_handler.update_proxy_url()
  578. await self.on_proxy_update()
  579. else:
  580. self.log.debug(f"Not updating proxy: listen_task is still running? (caller: {source})")
  581. async def sync(self, increment_total_backfilled_portals: bool = False) -> None:
  582. await self.run_with_sync_lock(partial(self._sync, increment_total_backfilled_portals))
  583. async def _sync(self, increment_total_backfilled_portals: bool = False) -> None:
  584. if not self._listen_task:
  585. self.state.reset_pigeon_session_id()
  586. sleep_minutes = 2
  587. errors = 0
  588. while True:
  589. try:
  590. resp = await self.client.get_inbox()
  591. break
  592. except (
  593. ProxyError,
  594. ProxyTimeoutError,
  595. ProxyConnectionError,
  596. ClientConnectionError,
  597. ConnectionError,
  598. asyncio.TimeoutError,
  599. ) as e:
  600. errors += 1
  601. wait = min(errors * 10, 60)
  602. self.log.warning(
  603. f"{e.__class__.__name__} while trying to sync, retrying in {wait} seconds: {e}"
  604. )
  605. await asyncio.sleep(wait)
  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 (
  794. ProxyError,
  795. ProxyTimeoutError,
  796. ProxyConnectionError,
  797. ClientConnectionError,
  798. ConnectionError,
  799. asyncio.TimeoutError,
  800. ) as e:
  801. errors += 1
  802. wait = min(errors * 10, 60)
  803. self.log.warning(
  804. f"{e.__class__.__name__} while trying to check user for reconnection, "
  805. f"retrying in {wait} seconds: {e}"
  806. )
  807. await asyncio.sleep(wait)
  808. await self._maybe_update_proxy("fetch_user_and_reconnect error")
  809. except IGNotLoggedInError as e:
  810. self.log.warning(f"Failed to reconnect to Instagram: {e}, logging out")
  811. await self.logout(error=e)
  812. return
  813. except (IGChallengeError, IGConsentRequiredError) as e:
  814. await self._handle_checkpoint(e, on="reconnect")
  815. return
  816. except Exception as e:
  817. self.log.exception("Error while reconnecting to Instagram")
  818. if isinstance(e, IGCheckpointError):
  819. self.log.debug("Checkpoint error content: %s", e.body)
  820. await self.push_bridge_state(
  821. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  822. )
  823. return
  824. else:
  825. self.log.debug(f"Confirmed current user {resp.user.pk}")
  826. self.start_listen()
  827. return
  828. async def _listen(self, seq_id: int, snapshot_at_ms: int, is_after_sync: bool) -> None:
  829. try:
  830. await self.mqtt.listen(
  831. graphql_subs={
  832. GraphQLSubscription.app_presence(),
  833. GraphQLSubscription.direct_typing(self.state.user_id),
  834. GraphQLSubscription.direct_status(),
  835. },
  836. skywalker_subs={
  837. SkywalkerSubscription.direct_sub(self.state.user_id),
  838. SkywalkerSubscription.live_sub(self.state.user_id),
  839. },
  840. seq_id=seq_id,
  841. snapshot_at_ms=snapshot_at_ms,
  842. )
  843. except IrisSubscribeError as e:
  844. if is_after_sync:
  845. self.log.exception("Got IrisSubscribeError right after refresh")
  846. await self.send_bridge_notice(
  847. f"Reconnecting failed again after refresh: {e}",
  848. important=True,
  849. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  850. error_code="ig-refresh-connection-error",
  851. error_message=str(e),
  852. info={"python_error": str(e)},
  853. )
  854. else:
  855. self.log.warning(f"Got IrisSubscribeError {e}, refreshing...")
  856. background_task.create(self.refresh())
  857. except MQTTReconnectionError as e:
  858. self.log.warning(
  859. f"Unexpected connection error: {e}, reconnecting in 1 minute", exc_info=True
  860. )
  861. await self.send_bridge_notice(
  862. f"Error in listener: {e}",
  863. important=True,
  864. state_event=BridgeStateEvent.TRANSIENT_DISCONNECT,
  865. error_code="ig-connection-error-socket",
  866. )
  867. self.mqtt.disconnect()
  868. background_task.create(self.delayed_start_listen(sleep=60))
  869. except (MQTTNotConnected, MQTTNotLoggedIn, MQTTConnectionUnauthorized) as e:
  870. self.log.warning(f"Unexpected connection error: {e}, checking auth and reconnecting")
  871. await self.send_bridge_notice(
  872. f"Error in listener: {e}",
  873. important=True,
  874. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  875. error_code="ig-connection-error-maybe-auth",
  876. )
  877. self.mqtt.disconnect()
  878. background_task.create(self.fetch_user_and_reconnect())
  879. except Exception as e:
  880. self.log.exception("Fatal error in listener, reconnecting in 5 minutes")
  881. await self.send_bridge_notice(
  882. "Fatal error in listener (see logs for more info)",
  883. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  884. important=True,
  885. error_code="ig-unknown-connection-error",
  886. info={"python_error": str(e)},
  887. )
  888. self.mqtt.disconnect()
  889. background_task.create(self.fetch_user_and_reconnect(sleep_first=300))
  890. else:
  891. if not self.shutdown:
  892. await self.send_bridge_notice(
  893. "Instagram connection closed without error",
  894. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  895. error_code="ig-disconnected",
  896. )
  897. finally:
  898. self._listen_task = None
  899. self._is_connected = False
  900. self._track_metric(METRIC_CONNECTED, False)
  901. async def stop_listen(self) -> None:
  902. if self.mqtt:
  903. self.shutdown = True
  904. self.mqtt.disconnect()
  905. if self._listen_task:
  906. await self._listen_task
  907. self.shutdown = False
  908. self._track_metric(METRIC_CONNECTED, False)
  909. self._is_connected = False
  910. await self.update()
  911. def stop_backfill_tasks(self) -> None:
  912. if self._backfill_loop_task:
  913. self._backfill_loop_task.cancel()
  914. self._backfill_loop_task = None
  915. if self._thread_sync_task:
  916. self._thread_sync_task.cancel()
  917. self._thread_sync_task = None
  918. async def logout(self, error: IGNotLoggedInError | None = None) -> None:
  919. await self.stop_listen()
  920. self.stop_backfill_tasks()
  921. if self.client and error is None:
  922. try:
  923. await self.client.logout(one_tap_app_login=False)
  924. except Exception:
  925. self.log.debug("Exception logging out", exc_info=True)
  926. if self.mqtt:
  927. self.mqtt.disconnect()
  928. self._track_metric(METRIC_CONNECTED, False)
  929. self._track_metric(METRIC_LOGGED_IN, False)
  930. if error is None:
  931. await self.push_bridge_state(BridgeStateEvent.LOGGED_OUT)
  932. puppet = await pu.Puppet.get_by_pk(self.igpk, create=False)
  933. if puppet and puppet.is_real_user:
  934. await puppet.switch_mxid(None, None)
  935. try:
  936. del self.by_igpk[self.igpk]
  937. except KeyError:
  938. pass
  939. self.igpk = None
  940. else:
  941. self.log.debug("Auth error body: %s", error.body.serialize())
  942. await self.send_bridge_notice(
  943. f"You have been logged out of Instagram: {error.proper_message}",
  944. important=True,
  945. state_event=BridgeStateEvent.BAD_CREDENTIALS,
  946. error_code="ig-auth-error",
  947. error_message=error.proper_message,
  948. )
  949. self.client = None
  950. self.mqtt = None
  951. self.state = None
  952. self.seq_id = None
  953. self.snapshot_at_ms = None
  954. self.thread_sync_completed = False
  955. self._is_logged_in = False
  956. await self.update()
  957. # endregion
  958. # region Event handlers
  959. async def _save_seq_id_after_sleep(self) -> None:
  960. await asyncio.sleep(120)
  961. self._seq_id_save_task = None
  962. self.log.trace("Saving sequence ID %d/%d", self.seq_id, self.snapshot_at_ms)
  963. try:
  964. await self.save_seq_id()
  965. except Exception:
  966. self.log.exception("Error saving sequence ID")
  967. async def update_seq_id(self, evt: NewSequenceID) -> None:
  968. self.seq_id = evt.seq_id
  969. self.snapshot_at_ms = evt.snapshot_at_ms
  970. if not self._seq_id_save_task or self._seq_id_save_task.done():
  971. self.log.trace("Starting seq id save task (%d/%d)", evt.seq_id, evt.snapshot_at_ms)
  972. self._seq_id_save_task = asyncio.create_task(self._save_seq_id_after_sleep())
  973. else:
  974. self.log.trace("Not starting seq id save task (%d/%d)", evt.seq_id, evt.snapshot_at_ms)
  975. @async_time(METRIC_MESSAGE)
  976. async def handle_message(self, evt: MessageSyncEvent) -> None:
  977. portal = await po.Portal.get_by_thread_id(evt.message.thread_id, receiver=self.igpk)
  978. if not portal or not portal.mxid:
  979. self.log.debug("Got message in thread with no portal, getting info...")
  980. resp = await self.client.get_thread(evt.message.thread_id)
  981. portal = await po.Portal.get_by_thread(resp.thread, self.igpk)
  982. self.log.debug("Got info for unknown portal, creating room")
  983. await portal.create_matrix_room(self, resp.thread)
  984. if not portal.mxid:
  985. self.log.warning(
  986. "Room creation appears to have failed, "
  987. f"dropping message in {evt.message.thread_id}"
  988. )
  989. return
  990. self.log.trace(f"Received message sync event {evt.message}")
  991. if evt.message.new_reaction:
  992. await portal.handle_instagram_reaction(
  993. evt.message, remove=evt.message.op == Operation.REMOVE
  994. )
  995. return
  996. sender = await pu.Puppet.get_by_pk(evt.message.user_id) if evt.message.user_id else None
  997. if evt.message.op == Operation.ADD:
  998. if not sender:
  999. # I don't think we care about adds with no sender
  1000. return
  1001. await portal.handle_instagram_item(self, sender, evt.message)
  1002. elif evt.message.op == Operation.REMOVE:
  1003. # Removes don't have a sender, only the message sender can unsend messages anyway
  1004. await portal.handle_instagram_remove(evt.message.item_id)
  1005. elif evt.message.op == Operation.REPLACE:
  1006. await portal.handle_instagram_update(evt.message)
  1007. @async_time(METRIC_THREAD_SYNC)
  1008. async def handle_thread_sync(self, evt: ThreadSyncEvent) -> None:
  1009. self.log.trace("Thread sync event content: %s", evt)
  1010. portal = await po.Portal.get_by_thread(evt, receiver=self.igpk)
  1011. if portal.mxid:
  1012. self.log.debug("Got thread sync event for %s with existing portal", portal.thread_id)
  1013. await portal.update_matrix_room(self, evt)
  1014. elif evt.is_group:
  1015. self.log.debug(
  1016. "Got thread sync event for group %s without existing portal, creating room",
  1017. portal.thread_id,
  1018. )
  1019. await portal.create_matrix_room(self, evt)
  1020. else:
  1021. self.log.debug(
  1022. "Got thread sync event for DM %s without existing portal, ignoring",
  1023. portal.thread_id,
  1024. )
  1025. async def handle_thread_remove(self, evt: ThreadRemoveEvent) -> None:
  1026. self.log.debug("Got thread remove event: %s", evt.serialize())
  1027. @async_time(METRIC_RTD)
  1028. async def handle_rtd(self, evt: RealtimeDirectEvent) -> None:
  1029. if not isinstance(evt.value, ActivityIndicatorData):
  1030. return
  1031. now = int(time.time() * 1000)
  1032. date = evt.value.timestamp_ms
  1033. expiry = date + evt.value.ttl
  1034. if expiry < now:
  1035. return
  1036. if evt.activity_indicator_id in self._activity_indicator_ids:
  1037. return
  1038. # TODO clear expired items from this dict
  1039. self._activity_indicator_ids[evt.activity_indicator_id] = expiry
  1040. puppet = await pu.Puppet.get_by_pk(int(evt.value.sender_id))
  1041. portal = await po.Portal.get_by_thread_id(evt.thread_id, receiver=self.igpk)
  1042. if not puppet or not portal or not portal.mxid:
  1043. return
  1044. is_typing = evt.value.activity_status != TypingStatus.OFF
  1045. if puppet.pk == self.igpk:
  1046. self.remote_typing_status = TypingStatus.TEXT if is_typing else TypingStatus.OFF
  1047. await puppet.intent_for(portal).set_typing(portal.mxid, timeout=evt.value.ttl)
  1048. # endregion
  1049. # region Database getters
  1050. def _add_to_cache(self) -> None:
  1051. self.by_mxid[self.mxid] = self
  1052. if self.igpk:
  1053. self.by_igpk[self.igpk] = self
  1054. @classmethod
  1055. @async_getter_lock
  1056. async def get_by_mxid(cls, mxid: UserID, *, create: bool = True) -> User | None:
  1057. # Never allow ghosts to be users
  1058. if pu.Puppet.get_id_from_mxid(mxid):
  1059. return None
  1060. try:
  1061. return cls.by_mxid[mxid]
  1062. except KeyError:
  1063. pass
  1064. user = cast(cls, await super().get_by_mxid(mxid))
  1065. if user is not None:
  1066. user._add_to_cache()
  1067. return user
  1068. if create:
  1069. user = cls(mxid)
  1070. await user.insert()
  1071. user._add_to_cache()
  1072. return user
  1073. return None
  1074. @classmethod
  1075. @async_getter_lock
  1076. async def get_by_igpk(cls, igpk: int) -> User | None:
  1077. try:
  1078. return cls.by_igpk[igpk]
  1079. except KeyError:
  1080. pass
  1081. user = cast(cls, await super().get_by_igpk(igpk))
  1082. if user is not None:
  1083. user._add_to_cache()
  1084. return user
  1085. return None
  1086. @classmethod
  1087. async def all_logged_in(cls) -> AsyncGenerator[User, None]:
  1088. users = await super().all_logged_in()
  1089. user: cls
  1090. for index, user in enumerate(users):
  1091. try:
  1092. yield cls.by_mxid[user.mxid]
  1093. except KeyError:
  1094. user._add_to_cache()
  1095. yield user
  1096. # endregion