ChatGPT-Next-Web/app/store/update.ts

92 lines
2.2 KiB
TypeScript
Raw Normal View History

import { create } from "zustand";
import { persist } from "zustand/middleware";
2023-03-30 16:46:17 +00:00
import { FETCH_COMMIT_URL, FETCH_TAG_URL } from "../constant";
2023-04-17 15:12:27 +00:00
import { requestUsage } from "../requests";
export interface UpdateStore {
lastUpdate: number;
2023-04-10 18:54:31 +00:00
remoteVersion: string;
2023-04-17 15:12:27 +00:00
used?: number;
subscription?: number;
lastUpdateUsage: number;
2023-04-10 18:54:31 +00:00
version: string;
2023-04-17 15:12:27 +00:00
getLatestVersion: (force?: boolean) => Promise<void>;
updateUsage: (force?: boolean) => Promise<void>;
}
export const UPDATE_KEY = "chat-update";
2023-04-10 18:54:31 +00:00
function queryMeta(key: string, defaultValue?: string): string {
let ret: string;
if (document) {
const meta = document.head.querySelector(
`meta[name='${key}']`,
) as HTMLMetaElement;
ret = meta?.content ?? "";
} else {
ret = defaultValue ?? "";
}
return ret;
}
2023-04-17 15:12:27 +00:00
const ONE_MINUTE = 60 * 1000;
export const useUpdateStore = create<UpdateStore>()(
persist(
(set, get) => ({
lastUpdate: 0,
2023-04-10 18:54:31 +00:00
remoteVersion: "",
2023-04-17 15:12:27 +00:00
lastUpdateUsage: 0,
2023-04-10 18:54:31 +00:00
version: "unknown",
async getLatestVersion(force = false) {
2023-04-17 15:12:27 +00:00
set(() => ({ version: queryMeta("version") ?? "unknown" }));
2023-04-17 15:12:27 +00:00
const overTenMins = Date.now() - get().lastUpdate > 10 * ONE_MINUTE;
if (!force && !overTenMins) return;
2023-04-17 17:34:12 +00:00
set(() => ({
lastUpdate: Date.now(),
}));
try {
2023-03-30 18:15:49 +00:00
// const data = await (await fetch(FETCH_TAG_URL)).json();
// const remoteId = data[0].name as string;
const data = await (await fetch(FETCH_COMMIT_URL)).json();
const remoteId = (data[0].sha as string).substring(0, 7);
set(() => ({
2023-04-10 18:54:31 +00:00
remoteVersion: remoteId,
}));
console.log("[Got Upstream] ", remoteId);
} catch (error) {
console.error("[Fetch Upstream Commit Id]", error);
2023-04-17 15:12:27 +00:00
}
},
async updateUsage(force = false) {
const overOneMinute = Date.now() - get().lastUpdateUsage >= ONE_MINUTE;
if (!overOneMinute && !force) return;
2023-04-17 17:34:12 +00:00
set(() => ({
lastUpdateUsage: Date.now(),
}));
2023-04-17 15:12:27 +00:00
const usage = await requestUsage();
if (usage) {
set(() => usage);
}
},
}),
{
name: UPDATE_KEY,
version: 1,
2023-03-30 16:46:17 +00:00
},
),
);