user.py 47 KB

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