diff --git a/src/grokCookies.ts b/src/grokCookies.ts index 6026aef..99d1aae 100644 --- a/src/grokCookies.ts +++ b/src/grokCookies.ts @@ -45,5 +45,6 @@ export async function getGrokAuthedCookies() { } }; + state.isRefreshPending = false; fastify.log.info("Refreshed Grok meta"); } diff --git a/src/index.ts b/src/index.ts index 6125a89..b70e2cd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ import Fastify from "fastify"; import { Yapper } from "./utils/Yapper"; import { getGrokAuthedCookies } from "./grokCookies"; +import { state } from "./utils/state"; export const fastify = Fastify({ loggerInstance: new Yapper(), @@ -13,10 +14,21 @@ fastify.get("/", async (request, reply) => { }); try { + state.isRefreshPending = true; getGrokAuthedCookies(); + setInterval(() => { + const { + expiresIn: { requests, time } + } = state.grokMeta; + + if ((requests === 0 || time < Date.now()) && !state.isRefreshPending) { + state.isRefreshPending = true; + getGrokAuthedCookies(); + } + }, 500); fastify.listen({ - port: 4935, + port: parseInt(process.env.PORT || "4935"), host: "0.0.0.0" }); } catch (err) { diff --git a/src/utils/state.ts b/src/utils/state.ts index a1e8187..e7c87d8 100644 --- a/src/utils/state.ts +++ b/src/utils/state.ts @@ -1,6 +1,6 @@ import { existsSync, readFileSync, writeFileSync } from "fs"; import path from "path"; -import { GrokMeta } from "./types"; +import { State } from "./types"; export const STATE_PATH = path.join( __dirname, @@ -11,17 +11,18 @@ export const STATE_PATH = path.join( if (!existsSync(STATE_PATH)) writeFileSync(STATE_PATH, JSON.stringify({}), "utf-8"); -export const state = new Proxy<{ - grokMeta: GrokMeta; -}>(JSON.parse(readFileSync(STATE_PATH, "utf-8")), { - get(target, prop) { - const data = readFileSync(STATE_PATH, "utf-8"); - return JSON.parse(data)[prop]; - }, - set(target, prop, value) { - const data = JSON.parse(readFileSync(STATE_PATH, "utf-8")); - data[prop] = value; - writeFileSync(STATE_PATH, JSON.stringify(data)); - return true; +export const state = new Proxy( + JSON.parse(readFileSync(STATE_PATH, "utf-8")), + { + get(target, prop) { + const data = readFileSync(STATE_PATH, "utf-8"); + return JSON.parse(data)[prop]; + }, + set(target, prop, value) { + const data = JSON.parse(readFileSync(STATE_PATH, "utf-8")); + data[prop] = value; + writeFileSync(STATE_PATH, JSON.stringify(data)); + return true; + } } -}); +); diff --git a/src/utils/types.ts b/src/utils/types.ts index 407d6c6..8fdb393 100644 --- a/src/utils/types.ts +++ b/src/utils/types.ts @@ -8,3 +8,8 @@ export interface GrokMeta { requests: 0 | 1 | 2 | 3; }; } + +export interface State { + grokMeta: GrokMeta; + isRefreshPending: boolean; +}