2023-03-23 17:00:33 +00:00
|
|
|
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-03-23 17:00:33 +00:00
|
|
|
|
|
|
|
export interface UpdateStore {
|
|
|
|
lastUpdate: number;
|
2023-04-10 18:54:31 +00:00
|
|
|
remoteVersion: string;
|
2023-03-23 17:00:33 +00:00
|
|
|
|
2023-04-10 18:54:31 +00:00
|
|
|
version: string;
|
|
|
|
getLatestVersion: (force: boolean) => Promise<string>;
|
2023-03-23 17:00:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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-03-23 17:00:33 +00:00
|
|
|
export const useUpdateStore = create<UpdateStore>()(
|
|
|
|
persist(
|
|
|
|
(set, get) => ({
|
|
|
|
lastUpdate: 0,
|
2023-04-10 18:54:31 +00:00
|
|
|
remoteVersion: "",
|
|
|
|
|
|
|
|
version: "unknown",
|
|
|
|
|
|
|
|
async getLatestVersion(force = false) {
|
|
|
|
set(() => ({ version: queryMeta("version") }));
|
2023-03-23 17:00:33 +00:00
|
|
|
|
2023-03-30 16:46:17 +00:00
|
|
|
const overTenMins = Date.now() - get().lastUpdate > 10 * 60 * 1000;
|
|
|
|
const shouldFetch = force || overTenMins;
|
2023-03-23 17:00:33 +00:00
|
|
|
if (!shouldFetch) {
|
2023-04-10 18:54:31 +00:00
|
|
|
return get().version ?? "unknown";
|
2023-03-23 17:00:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
2023-03-23 17:00:33 +00:00
|
|
|
set(() => ({
|
|
|
|
lastUpdate: Date.now(),
|
2023-04-10 18:54:31 +00:00
|
|
|
remoteVersion: remoteId,
|
2023-03-23 17:00:33 +00:00
|
|
|
}));
|
|
|
|
console.log("[Got Upstream] ", remoteId);
|
|
|
|
return remoteId;
|
|
|
|
} catch (error) {
|
|
|
|
console.error("[Fetch Upstream Commit Id]", error);
|
2023-04-10 18:54:31 +00:00
|
|
|
return get().version ?? "";
|
2023-03-23 17:00:33 +00:00
|
|
|
}
|
|
|
|
},
|
|
|
|
}),
|
|
|
|
{
|
|
|
|
name: UPDATE_KEY,
|
|
|
|
version: 1,
|
2023-03-30 16:46:17 +00:00
|
|
|
},
|
|
|
|
),
|
2023-03-23 17:00:33 +00:00
|
|
|
);
|