add automatic refresh

This commit is contained in:
nin0 2025-05-03 09:20:20 -04:00
parent 7b0485f2cd
commit 788e5262c8
Signed by: nin0
SSH key fingerprint: SHA256:NOoDnFVvZNFvqfXCIhzr6oCTDImZAbTTuyAysZ8Ufk8
4 changed files with 34 additions and 15 deletions

View file

@ -45,5 +45,6 @@ export async function getGrokAuthedCookies() {
} }
}; };
state.isRefreshPending = false;
fastify.log.info("Refreshed Grok meta"); fastify.log.info("Refreshed Grok meta");
} }

View file

@ -1,6 +1,7 @@
import Fastify from "fastify"; import Fastify from "fastify";
import { Yapper } from "./utils/Yapper"; import { Yapper } from "./utils/Yapper";
import { getGrokAuthedCookies } from "./grokCookies"; import { getGrokAuthedCookies } from "./grokCookies";
import { state } from "./utils/state";
export const fastify = Fastify({ export const fastify = Fastify({
loggerInstance: new Yapper(), loggerInstance: new Yapper(),
@ -13,10 +14,21 @@ fastify.get("/", async (request, reply) => {
}); });
try { try {
state.isRefreshPending = true;
getGrokAuthedCookies(); getGrokAuthedCookies();
setInterval(() => {
const {
expiresIn: { requests, time }
} = state.grokMeta;
if ((requests === 0 || time < Date.now()) && !state.isRefreshPending) {
state.isRefreshPending = true;
getGrokAuthedCookies();
}
}, 500);
fastify.listen({ fastify.listen({
port: 4935, port: parseInt(process.env.PORT || "4935"),
host: "0.0.0.0" host: "0.0.0.0"
}); });
} catch (err) { } catch (err) {

View file

@ -1,6 +1,6 @@
import { existsSync, readFileSync, writeFileSync } from "fs"; import { existsSync, readFileSync, writeFileSync } from "fs";
import path from "path"; import path from "path";
import { GrokMeta } from "./types"; import { State } from "./types";
export const STATE_PATH = path.join( export const STATE_PATH = path.join(
__dirname, __dirname,
@ -11,9 +11,9 @@ export const STATE_PATH = path.join(
if (!existsSync(STATE_PATH)) if (!existsSync(STATE_PATH))
writeFileSync(STATE_PATH, JSON.stringify({}), "utf-8"); writeFileSync(STATE_PATH, JSON.stringify({}), "utf-8");
export const state = new Proxy<{ export const state = new Proxy<State>(
grokMeta: GrokMeta; JSON.parse(readFileSync(STATE_PATH, "utf-8")),
}>(JSON.parse(readFileSync(STATE_PATH, "utf-8")), { {
get(target, prop) { get(target, prop) {
const data = readFileSync(STATE_PATH, "utf-8"); const data = readFileSync(STATE_PATH, "utf-8");
return JSON.parse(data)[prop]; return JSON.parse(data)[prop];
@ -24,4 +24,5 @@ export const state = new Proxy<{
writeFileSync(STATE_PATH, JSON.stringify(data)); writeFileSync(STATE_PATH, JSON.stringify(data));
return true; return true;
} }
}); }
);

View file

@ -8,3 +8,8 @@ export interface GrokMeta {
requests: 0 | 1 | 2 | 3; requests: 0 | 1 | 2 | 3;
}; };
} }
export interface State {
grokMeta: GrokMeta;
isRefreshPending: boolean;
}