user.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2022 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, cast
  18. import asyncio
  19. import logging
  20. import time
  21. from mauigpapi import AndroidAPI, AndroidMQTT, AndroidState
  22. from mauigpapi.errors import (
  23. IGNotLoggedInError,
  24. IGUserIDNotFoundError,
  25. IrisSubscribeError,
  26. MQTTNotConnected,
  27. MQTTNotLoggedIn,
  28. )
  29. from mauigpapi.mqtt import Connect, Disconnect, GraphQLSubscription, SkywalkerSubscription
  30. from mauigpapi.types import (
  31. ActivityIndicatorData,
  32. CurrentUser,
  33. MessageSyncEvent,
  34. Operation,
  35. RealtimeDirectEvent,
  36. Thread,
  37. ThreadSyncEvent,
  38. TypingStatus,
  39. )
  40. from mautrix.appservice import AppService
  41. from mautrix.bridge import BaseUser, async_getter_lock
  42. from mautrix.types import EventID, MessageType, RoomID, TextMessageEventContent, UserID
  43. from mautrix.util.bridge_state import BridgeState, BridgeStateEvent
  44. from mautrix.util.logging import TraceLogger
  45. from mautrix.util.opt_prometheus import Gauge, Summary, async_time
  46. from . import portal as po, puppet as pu
  47. from .config import Config
  48. from .db import Portal as DBPortal, User as DBUser
  49. if TYPE_CHECKING:
  50. from .__main__ import InstagramBridge
  51. METRIC_MESSAGE = Summary("bridge_on_message", "calls to handle_message")
  52. METRIC_THREAD_SYNC = Summary("bridge_on_thread_sync", "calls to handle_thread_sync")
  53. METRIC_RTD = Summary("bridge_on_rtd", "calls to handle_rtd")
  54. METRIC_LOGGED_IN = Gauge("bridge_logged_in", "Users logged into the bridge")
  55. METRIC_CONNECTED = Gauge("bridge_connected", "Bridged users connected to Instagram")
  56. BridgeState.human_readable_errors.update(
  57. {
  58. "ig-connection-error": "Instagram disconnected unexpectedly",
  59. "ig-auth-error": "Authentication error from Instagram: {message}",
  60. "ig-disconnected": None,
  61. "ig-no-mqtt": "You're not connected to Instagram",
  62. "logged-out": "You're not logged into Instagram",
  63. }
  64. )
  65. class User(DBUser, BaseUser):
  66. ig_base_log: TraceLogger = logging.getLogger("mau.instagram")
  67. _activity_indicator_ids: dict[str, int] = {}
  68. by_mxid: dict[UserID, User] = {}
  69. by_igpk: dict[int, User] = {}
  70. config: Config
  71. az: AppService
  72. loop: asyncio.AbstractEventLoop
  73. client: AndroidAPI | None
  74. mqtt: AndroidMQTT | None
  75. _listen_task: asyncio.Task | None = None
  76. permission_level: str
  77. username: str | None
  78. _notice_room_lock: asyncio.Lock
  79. _notice_send_lock: asyncio.Lock
  80. _is_logged_in: bool
  81. _is_connected: bool
  82. shutdown: bool
  83. remote_typing_status: TypingStatus | None
  84. def __init__(
  85. self,
  86. mxid: UserID,
  87. igpk: int | None = None,
  88. state: AndroidState | None = None,
  89. notice_room: RoomID | None = None,
  90. ) -> None:
  91. super().__init__(mxid=mxid, igpk=igpk, state=state, notice_room=notice_room)
  92. BaseUser.__init__(self)
  93. self._notice_room_lock = asyncio.Lock()
  94. self._notice_send_lock = asyncio.Lock()
  95. perms = self.config.get_permissions(mxid)
  96. self.relay_whitelisted, self.is_whitelisted, self.is_admin, self.permission_level = perms
  97. self.client = None
  98. self.mqtt = None
  99. self.username = None
  100. self._is_logged_in = False
  101. self._is_connected = False
  102. self._is_refreshing = False
  103. self.shutdown = False
  104. self._listen_task = None
  105. self.remote_typing_status = None
  106. @classmethod
  107. def init_cls(cls, bridge: "InstagramBridge") -> AsyncIterable[Awaitable[None]]:
  108. cls.bridge = bridge
  109. cls.config = bridge.config
  110. cls.az = bridge.az
  111. cls.loop = bridge.loop
  112. return (user.try_connect() async for user in cls.all_logged_in())
  113. # region Connection management
  114. async def is_logged_in(self) -> bool:
  115. return bool(self.client) and self._is_logged_in
  116. async def get_puppet(self) -> pu.Puppet | None:
  117. if not self.igpk:
  118. return None
  119. return await pu.Puppet.get_by_pk(self.igpk)
  120. async def get_portal_with(self, puppet: pu.Puppet, create: bool = True) -> po.Portal | None:
  121. if not self.igpk:
  122. return None
  123. portal = await po.Portal.find_private_chat(self.igpk, puppet.pk)
  124. if portal:
  125. return portal
  126. if create:
  127. # TODO add error handling somewhere
  128. thread = await self.client.create_group_thread([puppet.pk])
  129. portal = await po.Portal.get_by_thread(thread, self.igpk)
  130. await portal.update_info(thread, self)
  131. return portal
  132. return None
  133. async def try_connect(self) -> None:
  134. try:
  135. await self.connect()
  136. except Exception:
  137. self.log.exception("Error while connecting to Instagram")
  138. @property
  139. def api_log(self) -> TraceLogger:
  140. return self.ig_base_log.getChild("http").getChild(self.mxid)
  141. @property
  142. def is_connected(self) -> bool:
  143. return bool(self.client) and bool(self.mqtt) and self._is_connected
  144. async def connect(self, user: CurrentUser | None = None) -> None:
  145. if not self.state:
  146. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error="logged-out")
  147. return
  148. client = AndroidAPI(self.state, log=self.api_log)
  149. if not user:
  150. try:
  151. resp = await client.current_user()
  152. user = resp.user
  153. except IGNotLoggedInError as e:
  154. self.log.warning(f"Failed to connect to Instagram: {e}, logging out")
  155. await self.logout(error=e)
  156. return
  157. self.client = client
  158. self._is_logged_in = True
  159. self.igpk = user.pk
  160. self.username = user.username
  161. await self.push_bridge_state(BridgeStateEvent.CONNECTING)
  162. self._track_metric(METRIC_LOGGED_IN, True)
  163. self.by_igpk[self.igpk] = self
  164. self.mqtt = AndroidMQTT(
  165. self.state, loop=self.loop, log=self.ig_base_log.getChild("mqtt").getChild(self.mxid)
  166. )
  167. self.mqtt.add_event_handler(Connect, self.on_connect)
  168. self.mqtt.add_event_handler(Disconnect, self.on_disconnect)
  169. self.mqtt.add_event_handler(MessageSyncEvent, self.handle_message)
  170. self.mqtt.add_event_handler(ThreadSyncEvent, self.handle_thread_sync)
  171. self.mqtt.add_event_handler(RealtimeDirectEvent, self.handle_rtd)
  172. await self.update()
  173. self.loop.create_task(self._try_sync_puppet(user))
  174. self.loop.create_task(self._try_sync())
  175. async def on_connect(self, evt: Connect) -> None:
  176. self.log.debug("Connected to Instagram")
  177. self._track_metric(METRIC_CONNECTED, True)
  178. self._is_connected = True
  179. await self.send_bridge_notice("Connected to Instagram")
  180. await self.push_bridge_state(BridgeStateEvent.CONNECTED)
  181. async def on_disconnect(self, evt: Disconnect) -> None:
  182. self.log.debug("Disconnected from Instagram")
  183. self._track_metric(METRIC_CONNECTED, False)
  184. self._is_connected = False
  185. # TODO this stuff could probably be moved to mautrix-python
  186. async def get_notice_room(self) -> RoomID:
  187. if not self.notice_room:
  188. async with self._notice_room_lock:
  189. # If someone already created the room while this call was waiting,
  190. # don't make a new room
  191. if self.notice_room:
  192. return self.notice_room
  193. creation_content = {}
  194. if not self.config["bridge.federate_rooms"]:
  195. creation_content["m.federate"] = False
  196. self.notice_room = await self.az.intent.create_room(
  197. is_direct=True,
  198. invitees=[self.mxid],
  199. topic="Instagram bridge notices",
  200. creation_content=creation_content,
  201. )
  202. await self.update()
  203. return self.notice_room
  204. async def fill_bridge_state(self, state: BridgeState) -> None:
  205. await super().fill_bridge_state(state)
  206. if not state.remote_id:
  207. if self.igpk:
  208. state.remote_id = str(self.igpk)
  209. else:
  210. try:
  211. state.remote_id = self.state.user_id
  212. except IGUserIDNotFoundError:
  213. state.remote_id = None
  214. if self.username:
  215. state.remote_name = f"@{self.username}"
  216. async def get_bridge_states(self) -> list[BridgeState]:
  217. if not self.state:
  218. return []
  219. state = BridgeState(state_event=BridgeStateEvent.UNKNOWN_ERROR)
  220. if self.is_connected:
  221. state.state_event = BridgeStateEvent.CONNECTED
  222. elif self._is_refreshing or self.mqtt:
  223. state.state_event = BridgeStateEvent.TRANSIENT_DISCONNECT
  224. return [state]
  225. async def send_bridge_notice(
  226. self,
  227. text: str,
  228. edit: EventID | None = None,
  229. state_event: BridgeStateEvent | None = None,
  230. important: bool = False,
  231. error_code: str | None = None,
  232. error_message: str | None = None,
  233. ) -> EventID | None:
  234. if state_event:
  235. await self.push_bridge_state(
  236. state_event, error=error_code, message=error_message if error_code else text
  237. )
  238. if self.config["bridge.disable_bridge_notices"]:
  239. return None
  240. if not important and not self.config["bridge.unimportant_bridge_notices"]:
  241. self.log.debug("Not sending unimportant bridge notice: %s", text)
  242. return None
  243. event_id = None
  244. try:
  245. self.log.debug("Sending bridge notice: %s", text)
  246. content = TextMessageEventContent(
  247. body=text, msgtype=(MessageType.TEXT if important else MessageType.NOTICE)
  248. )
  249. if edit:
  250. content.set_edit(edit)
  251. # This is locked to prevent notices going out in the wrong order
  252. async with self._notice_send_lock:
  253. event_id = await self.az.intent.send_message(await self.get_notice_room(), content)
  254. except Exception:
  255. self.log.warning("Failed to send bridge notice", exc_info=True)
  256. return edit or event_id
  257. async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
  258. puppet = await pu.Puppet.get_by_pk(self.igpk)
  259. try:
  260. await puppet.update_info(user_info, self)
  261. except Exception:
  262. self.log.exception("Failed to update own puppet info")
  263. try:
  264. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  265. self.log.info(f"Automatically enabling custom puppet")
  266. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  267. except Exception:
  268. self.log.exception("Failed to automatically enable custom puppet")
  269. async def _try_sync(self) -> None:
  270. try:
  271. await self.sync()
  272. except Exception:
  273. self.log.exception("Exception while syncing")
  274. await self.push_bridge_state(BridgeStateEvent.UNKNOWN_ERROR)
  275. async def get_direct_chats(self) -> dict[UserID, list[RoomID]]:
  276. return {
  277. pu.Puppet.get_mxid_from_id(portal.other_user_pk): [portal.mxid]
  278. for portal in await DBPortal.find_private_chats_of(self.igpk)
  279. if portal.mxid
  280. }
  281. async def refresh(self, resync: bool = True) -> None:
  282. self._is_refreshing = True
  283. try:
  284. await self.stop_listen()
  285. if resync:
  286. retry_count = 0
  287. while True:
  288. try:
  289. await self.sync()
  290. return
  291. except IGNotLoggedInError as e:
  292. self.log.exception("Got not logged in error while syncing for refresh")
  293. await self.logout(error=e)
  294. except Exception:
  295. if retry_count >= 4:
  296. raise
  297. retry_count += 1
  298. self.log.exception("Error while syncing for refresh, retrying in 1 minute")
  299. await self.push_bridge_state(BridgeStateEvent.UNKNOWN_ERROR)
  300. await asyncio.sleep(60)
  301. else:
  302. await self.start_listen()
  303. finally:
  304. self._is_refreshing = False
  305. async def _sync_thread(self, thread: Thread, min_active_at: int) -> None:
  306. portal = await po.Portal.get_by_thread(thread, self.igpk)
  307. if portal.mxid:
  308. self.log.debug(f"{thread.thread_id} has a portal, syncing and backfilling...")
  309. await portal.update_matrix_room(self, thread, backfill=True)
  310. elif thread.last_activity_at > min_active_at:
  311. self.log.debug(f"{thread.thread_id} has been active recently, creating portal...")
  312. await portal.create_matrix_room(self, thread)
  313. else:
  314. self.log.debug(f"{thread.thread_id} is not active and doesn't have a portal")
  315. async def sync(self) -> None:
  316. resp = await self.client.get_inbox()
  317. if not self._listen_task:
  318. await self.start_listen(resp.seq_id, resp.snapshot_at_ms)
  319. max_age = self.config["bridge.portal_create_max_age"] * 1_000_000
  320. limit = self.config["bridge.chat_sync_limit"]
  321. min_active_at = (time.time() * 1_000_000) - max_age
  322. i = 0
  323. await self.push_bridge_state(BridgeStateEvent.BACKFILLING)
  324. async for thread in self.client.iter_inbox(start_at=resp):
  325. try:
  326. await self._sync_thread(thread, min_active_at)
  327. except Exception:
  328. self.log.exception(f"Error syncing thread {thread.thread_id}")
  329. i += 1
  330. if i >= limit:
  331. break
  332. try:
  333. await self.update_direct_chats()
  334. except Exception:
  335. self.log.exception("Error updating direct chat list")
  336. async def start_listen(
  337. self, seq_id: int | None = None, snapshot_at_ms: int | None = None
  338. ) -> None:
  339. self.shutdown = False
  340. if not seq_id:
  341. resp = await self.client.get_inbox(limit=1)
  342. seq_id, snapshot_at_ms = resp.seq_id, resp.snapshot_at_ms
  343. task = self.listen(seq_id=seq_id, snapshot_at_ms=snapshot_at_ms)
  344. self._listen_task = self.loop.create_task(task)
  345. async def listen(self, seq_id: int, snapshot_at_ms: int) -> None:
  346. try:
  347. await self.mqtt.listen(
  348. graphql_subs={
  349. GraphQLSubscription.app_presence(),
  350. GraphQLSubscription.direct_typing(self.state.user_id),
  351. GraphQLSubscription.direct_status(),
  352. },
  353. skywalker_subs={
  354. SkywalkerSubscription.direct_sub(self.state.user_id),
  355. SkywalkerSubscription.live_sub(self.state.user_id),
  356. },
  357. seq_id=seq_id,
  358. snapshot_at_ms=snapshot_at_ms,
  359. )
  360. except IrisSubscribeError as e:
  361. self.log.warning(f"Got IrisSubscribeError {e}, refreshing...")
  362. await self.refresh()
  363. except (MQTTNotConnected, MQTTNotLoggedIn) as e:
  364. await self.send_bridge_notice(
  365. f"Error in listener: {e}",
  366. important=True,
  367. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  368. error_code="ig-connection-error",
  369. )
  370. self.mqtt.disconnect()
  371. except Exception:
  372. self.log.exception("Fatal error in listener")
  373. await self.send_bridge_notice(
  374. "Fatal error in listener (see logs for more info)",
  375. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  376. important=True,
  377. error_code="ig-connection-error",
  378. )
  379. self.mqtt.disconnect()
  380. else:
  381. if not self.shutdown:
  382. await self.send_bridge_notice(
  383. "Instagram connection closed without error",
  384. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  385. error_code="ig-disconnected",
  386. )
  387. finally:
  388. self._listen_task = None
  389. self._is_connected = False
  390. self._track_metric(METRIC_CONNECTED, False)
  391. async def stop_listen(self) -> None:
  392. if self.mqtt:
  393. self.shutdown = True
  394. self.mqtt.disconnect()
  395. if self._listen_task:
  396. await self._listen_task
  397. self.shutdown = False
  398. self._track_metric(METRIC_CONNECTED, False)
  399. self._is_connected = False
  400. await self.update()
  401. async def logout(self, error: IGNotLoggedInError | None = None) -> None:
  402. if self.client and error is None:
  403. try:
  404. await self.client.logout(one_tap_app_login=False)
  405. except Exception:
  406. self.log.debug("Exception logging out", exc_info=True)
  407. if self.mqtt:
  408. self.mqtt.disconnect()
  409. self._track_metric(METRIC_CONNECTED, False)
  410. self._track_metric(METRIC_LOGGED_IN, False)
  411. if error is None:
  412. await self.push_bridge_state(BridgeStateEvent.LOGGED_OUT)
  413. puppet = await pu.Puppet.get_by_pk(self.igpk, create=False)
  414. if puppet and puppet.is_real_user:
  415. await puppet.switch_mxid(None, None)
  416. try:
  417. del self.by_igpk[self.igpk]
  418. except KeyError:
  419. pass
  420. self.igpk = None
  421. else:
  422. self.log.debug("Auth error body: %s", error.body.serialize())
  423. await self.send_bridge_notice(
  424. f"You have been logged out of Instagram: {error.proper_message}",
  425. important=True,
  426. state_event=BridgeStateEvent.BAD_CREDENTIALS,
  427. error_code="ig-auth-error",
  428. error_message=error.proper_message,
  429. )
  430. self.client = None
  431. self.mqtt = None
  432. self.state = None
  433. self._is_logged_in = False
  434. await self.update()
  435. # endregion
  436. # region Event handlers
  437. @async_time(METRIC_MESSAGE)
  438. async def handle_message(self, evt: MessageSyncEvent) -> None:
  439. portal = await po.Portal.get_by_thread_id(evt.message.thread_id, receiver=self.igpk)
  440. if not portal or not portal.mxid:
  441. self.log.debug("Got message in thread with no portal, getting info...")
  442. resp = await self.client.get_thread(evt.message.thread_id)
  443. portal = await po.Portal.get_by_thread(resp.thread, self.igpk)
  444. self.log.debug("Got info for unknown portal, creating room")
  445. await portal.create_matrix_room(self, resp.thread)
  446. if not portal.mxid:
  447. self.log.warning(
  448. "Room creation appears to have failed, "
  449. f"dropping message in {evt.message.thread_id}"
  450. )
  451. return
  452. self.log.trace(f"Received message sync event {evt.message}")
  453. sender = await pu.Puppet.get_by_pk(evt.message.user_id) if evt.message.user_id else None
  454. if evt.message.op == Operation.ADD:
  455. if not sender:
  456. # I don't think we care about adds with no sender
  457. return
  458. await portal.handle_instagram_item(self, sender, evt.message)
  459. elif evt.message.op == Operation.REMOVE:
  460. # Removes don't have a sender, only the message sender can unsend messages anyway
  461. await portal.handle_instagram_remove(evt.message.item_id)
  462. elif evt.message.op == Operation.REPLACE:
  463. await portal.handle_instagram_update(evt.message)
  464. @async_time(METRIC_THREAD_SYNC)
  465. async def handle_thread_sync(self, evt: ThreadSyncEvent) -> None:
  466. self.log.trace("Received thread sync event %s", evt)
  467. portal = await po.Portal.get_by_thread(evt, receiver=self.igpk)
  468. await portal.create_matrix_room(self, evt)
  469. @async_time(METRIC_RTD)
  470. async def handle_rtd(self, evt: RealtimeDirectEvent) -> None:
  471. if not isinstance(evt.value, ActivityIndicatorData):
  472. return
  473. now = int(time.time() * 1000)
  474. date = evt.value.timestamp_ms
  475. expiry = date + evt.value.ttl
  476. if expiry < now:
  477. return
  478. if evt.activity_indicator_id in self._activity_indicator_ids:
  479. return
  480. # TODO clear expired items from this dict
  481. self._activity_indicator_ids[evt.activity_indicator_id] = expiry
  482. puppet = await pu.Puppet.get_by_pk(int(evt.value.sender_id))
  483. portal = await po.Portal.get_by_thread_id(evt.thread_id, receiver=self.igpk)
  484. if not puppet or not portal or not portal.mxid:
  485. return
  486. is_typing = evt.value.activity_status != TypingStatus.OFF
  487. if puppet.pk == self.igpk:
  488. self.remote_typing_status = TypingStatus.TEXT if is_typing else TypingStatus.OFF
  489. await puppet.intent_for(portal).set_typing(
  490. portal.mxid, is_typing=is_typing, timeout=evt.value.ttl
  491. )
  492. # endregion
  493. # region Database getters
  494. def _add_to_cache(self) -> None:
  495. self.by_mxid[self.mxid] = self
  496. if self.igpk:
  497. self.by_igpk[self.igpk] = self
  498. @classmethod
  499. @async_getter_lock
  500. async def get_by_mxid(cls, mxid: UserID, *, create: bool = True) -> User | None:
  501. # Never allow ghosts to be users
  502. if pu.Puppet.get_id_from_mxid(mxid):
  503. return None
  504. try:
  505. return cls.by_mxid[mxid]
  506. except KeyError:
  507. pass
  508. user = cast(cls, await super().get_by_mxid(mxid))
  509. if user is not None:
  510. user._add_to_cache()
  511. return user
  512. if create:
  513. user = cls(mxid)
  514. await user.insert()
  515. user._add_to_cache()
  516. return user
  517. return None
  518. @classmethod
  519. @async_getter_lock
  520. async def get_by_igpk(cls, igpk: int) -> User | None:
  521. try:
  522. return cls.by_igpk[igpk]
  523. except KeyError:
  524. pass
  525. user = cast(cls, await super().get_by_igpk(igpk))
  526. if user is not None:
  527. user._add_to_cache()
  528. return user
  529. return None
  530. @classmethod
  531. async def all_logged_in(cls) -> AsyncGenerator[User, None]:
  532. users = await super().all_logged_in()
  533. user: cls
  534. for index, user in enumerate(users):
  535. try:
  536. yield cls.by_mxid[user.mxid]
  537. except KeyError:
  538. user._add_to_cache()
  539. yield user
  540. # endregion