update.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { create } from "zustand";
  2. import { persist } from "zustand/middleware";
  3. import { FETCH_COMMIT_URL, FETCH_TAG_URL, StoreKey } from "../constant";
  4. import { requestUsage } from "../requests";
  5. export interface UpdateStore {
  6. lastUpdate: number;
  7. remoteVersion: string;
  8. used?: number;
  9. subscription?: number;
  10. lastUpdateUsage: number;
  11. version: string;
  12. getLatestVersion: (force?: boolean) => Promise<void>;
  13. updateUsage: (force?: boolean) => Promise<void>;
  14. }
  15. function queryMeta(key: string, defaultValue?: string): string {
  16. let ret: string;
  17. if (document) {
  18. const meta = document.head.querySelector(
  19. `meta[name='${key}']`,
  20. ) as HTMLMetaElement;
  21. ret = meta?.content ?? "";
  22. } else {
  23. ret = defaultValue ?? "";
  24. }
  25. return ret;
  26. }
  27. const ONE_MINUTE = 60 * 1000;
  28. export const useUpdateStore = create<UpdateStore>()(
  29. persist(
  30. (set, get) => ({
  31. lastUpdate: 0,
  32. remoteVersion: "",
  33. lastUpdateUsage: 0,
  34. version: "unknown",
  35. async getLatestVersion(force = false) {
  36. set(() => ({ version: queryMeta("version") ?? "unknown" }));
  37. const overTenMins = Date.now() - get().lastUpdate > 10 * ONE_MINUTE;
  38. if (!force && !overTenMins) return;
  39. set(() => ({
  40. lastUpdate: Date.now(),
  41. }));
  42. try {
  43. const data = await (await fetch(FETCH_COMMIT_URL)).json();
  44. const remoteCommitTime = data[0].commit.committer.date;
  45. const remoteId = new Date(remoteCommitTime).getTime().toString();
  46. set(() => ({
  47. remoteVersion: remoteId,
  48. }));
  49. console.log("[Got Upstream] ", remoteId);
  50. } catch (error) {
  51. console.error("[Fetch Upstream Commit Id]", error);
  52. }
  53. },
  54. async updateUsage(force = false) {
  55. const overOneMinute = Date.now() - get().lastUpdateUsage >= ONE_MINUTE;
  56. if (!overOneMinute && !force) return;
  57. set(() => ({
  58. lastUpdateUsage: Date.now(),
  59. }));
  60. const usage = await requestUsage();
  61. if (usage) {
  62. set(() => usage);
  63. }
  64. },
  65. }),
  66. {
  67. name: StoreKey.Update,
  68. version: 1,
  69. },
  70. ),
  71. );