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");
}

View file

@ -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) {

View file

@ -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<State>(
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;
}
}
});
);

View file

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