feat: close #2190 improve app auto updater

This commit is contained in:
Yidadaa
2023-06-30 00:26:03 +08:00
parent 3937dad6a6
commit be4834688d
4 changed files with 87 additions and 40 deletions

View File

@@ -1,48 +1,96 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { FETCH_COMMIT_URL, StoreKey } from "../constant";
import { FETCH_COMMIT_URL, FETCH_TAG_URL, StoreKey } from "../constant";
import { api } from "../client/api";
import { getClientConfig } from "../config/client";
export interface UpdateStore {
versionType: "date" | "tag";
lastUpdate: number;
version: string;
remoteVersion: string;
used?: number;
subscription?: number;
lastUpdateUsage: number;
version: string;
getLatestVersion: (force?: boolean) => Promise<void>;
updateUsage: (force?: boolean) => Promise<void>;
formatVersion: (version: string) => string;
}
const ONE_MINUTE = 60 * 1000;
function formatVersionDate(t: string) {
const d = new Date(+t);
const year = d.getUTCFullYear();
const month = d.getUTCMonth() + 1;
const day = d.getUTCDate();
return [
year.toString(),
month.toString().padStart(2, "0"),
day.toString().padStart(2, "0"),
].join("");
}
async function getVersion(type: "date" | "tag") {
if (type === "date") {
const data = (await (await fetch(FETCH_COMMIT_URL)).json()) as {
commit: {
author: { name: string; date: string };
};
sha: string;
}[];
const remoteCommitTime = data[0].commit.author.date;
const remoteId = new Date(remoteCommitTime).getTime().toString();
return remoteId;
} else if (type === "tag") {
const data = (await (await fetch(FETCH_TAG_URL)).json()) as {
commit: { sha: string; url: string };
name: string;
}[];
return data.at(0)?.name;
}
}
export const useUpdateStore = create<UpdateStore>()(
persist(
(set, get) => ({
versionType: "tag",
lastUpdate: 0,
version: "unknown",
remoteVersion: "",
lastUpdateUsage: 0,
version: "unknown",
formatVersion(version: string) {
if (get().versionType === "date") {
version = formatVersionDate(version);
}
return version;
},
async getLatestVersion(force = false) {
set(() => ({ version: getClientConfig()?.commitId ?? "unknown" }));
const versionType = get().versionType;
let version =
versionType === "date"
? getClientConfig()?.commitDate
: getClientConfig()?.version;
const overTenMins = Date.now() - get().lastUpdate > 10 * ONE_MINUTE;
if (!force && !overTenMins) return;
set(() => ({ version }));
const shouldCheck =
Date.now() - get().lastUpdate > 24 * 60 * ONE_MINUTE;
if (!force && !shouldCheck) return;
set(() => ({
lastUpdate: Date.now(),
}));
try {
const data = await (await fetch(FETCH_COMMIT_URL)).json();
const remoteCommitTime = data[0].commit.committer.date;
const remoteId = new Date(remoteCommitTime).getTime().toString();
const remoteId = await getVersion(versionType);
set(() => ({
remoteVersion: remoteId,
}));