| 1 | import React, { useCallback, useEffect, useRef, useState } from "react"; |
| 2 | import { ArrowDownToLine, RefreshCw } from "lucide-react"; |
| 3 | import { native, nativeAvailable } from "./api"; |
| 4 | |
| 5 | const activePhases = new Set(["checking", "downloading", "downloaded", "verifying", "installing"]); |
| 6 | const checkInterval = 6 * 60 * 60 * 1000; |
| 7 | const retryInterval = 5 * 60 * 1000; |
| 8 | |
| 9 | export function useAppUpdates() { |
| 10 | const [state, setState] = useState({ phase: "idle", message: "" }); |
| 11 | const [startupFailure, setStartupFailure] = useState(""); |
| 12 | const [retryClock, setRetryClock] = useState(Date.now); |
| 13 | const retryAt = Date.parse(state.retryAt || ""); |
| 14 | const coolingDown = state.phase === "failed" && retryAt > Date.now(); |
| 15 | const current = useRef(state); |
| 16 | current.current = state; |
| 17 | const requestPending = useRef(false); |
| 18 | const lastCheck = useRef(0); |
| 19 | const available = nativeAvailable(); |
| 20 | const run = useCallback(async (operation) => { |
| 21 | if (!available || requestPending.current || activePhases.has(current.current.phase)) return; |
| 22 | if (["check", "install"].includes(operation) && Date.parse(current.current.retryAt || "") > Date.now()) return; |
| 23 | requestPending.current = true; |
| 24 | if (operation === "check") lastCheck.current = Date.now(); |
| 25 | if (operation === "install") setState(previous => ({ ...previous, phase: "checking" })); |
| 26 | try { |
| 27 | const next = await native("appUpdate", { operation }); |
| 28 | if (next?.phase) setState(next); |
| 29 | } catch (error) { |
| 30 | setState(previous => ({ ...previous, phase: "failed", message: error.message, retryable: true })); |
| 31 | } finally { requestPending.current = false; } |
| 32 | }, [available]); |
| 33 | |
| 34 | useEffect(() => { |
| 35 | if (!coolingDown) return; |
| 36 | const timer = setTimeout(() => setRetryClock(Date.now()), Math.min(60000, retryAt - Date.now())); |
| 37 | return () => clearTimeout(timer); |
| 38 | }, [coolingDown, retryAt, retryClock]); |
| 39 | |
| 40 | useEffect(() => { |
| 41 | if (!available) return; |
| 42 | let live = true; |
| 43 | const receive = event => { |
| 44 | if (event.detail?.phase) setState(event.detail); |
| 45 | }; |
| 46 | const check = () => { |
| 47 | if (document.visibilityState === "hidden" || window.cageWindowVisible === false) return; |
| 48 | const phase = current.current.phase; |
| 49 | const interval = ["failed", "waiting"].includes(phase) ? retryInterval : checkInterval; |
| 50 | const deadline = phase === "failed" && Number.isFinite(Date.parse(current.current.retryAt || "")) |
| 51 | ? Date.parse(current.current.retryAt) : lastCheck.current + interval; |
| 52 | if (["idle", "current", "failed", "waiting", "available"].includes(phase) && Date.now() >= deadline) void run("check"); |
| 53 | }; |
| 54 | window.addEventListener("cage-app-update", receive); |
| 55 | window.addEventListener("focus", check); |
| 56 | window.addEventListener("cage-window-visibility", check); |
| 57 | document.addEventListener("visibilitychange", check); |
| 58 | (async () => { |
| 59 | try { |
| 60 | const next = await native("appUpdate", { operation: "status" }); |
| 61 | if (!live) return; |
| 62 | if (next?.phase === "failed") setStartupFailure(next.message || "上次应用更新未完成"); |
| 63 | if (next?.phase) { current.current = next; setState(next); } |
| 64 | if (!next || ["idle", "current", "failed", "waiting"].includes(next.phase)) void run("check"); |
| 65 | } catch (error) { |
| 66 | if (live) setState({ phase: "failed", message: error.message, retryable: true }); |
| 67 | } |
| 68 | })(); |
| 69 | const timer = setInterval(check, 60 * 1000); |
| 70 | return () => { |
| 71 | live = false; |
| 72 | clearInterval(timer); |
| 73 | window.removeEventListener("cage-app-update", receive); |
| 74 | window.removeEventListener("focus", check); |
| 75 | window.removeEventListener("cage-window-visibility", check); |
| 76 | document.removeEventListener("visibilitychange", check); |
| 77 | }; |
| 78 | }, [available, run]); |
| 79 | useEffect(() => { |
| 80 | if (!startupFailure) return; |
| 81 | const timer = setTimeout(() => setStartupFailure(""), 8000); |
| 82 | return () => clearTimeout(timer); |
| 83 | }, [startupFailure]); |
| 84 | return { state, run, available, startupFailure, coolingDown }; |
| 85 | } |
| 86 | |
| 87 | export function AppUpdateButton({ updates }) { |
| 88 | const { state, run, available, startupFailure, coolingDown } = updates; |
| 89 | const busy = activePhases.has(state.phase); |
| 90 | const failed = state.phase === "failed"; |
| 91 | const visible = state.latestVersion && ["available", "ready", "failed", ...activePhases].includes(state.phase); |
| 92 | const announcedFailure = useRef(""); |
| 93 | const [failure, setFailure] = useState(""); |
| 94 | useEffect(() => { |
| 95 | if (failed && visible && state.message && announcedFailure.current !== state.message) { |
| 96 | announcedFailure.current = state.message; |
| 97 | setFailure(state.message); |
| 98 | } |
| 99 | if (!failed) { announcedFailure.current = ""; setFailure(""); } |
| 100 | }, [failed, visible, state.message]); |
| 101 | useEffect(() => { |
| 102 | if (!failure) return; |
| 103 | const timer = setTimeout(() => setFailure(""), 8000); |
| 104 | return () => clearTimeout(timer); |
| 105 | }, [failure]); |
| 106 | if (!available || (!visible && !startupFailure)) return null; |
| 107 | const downloading = state.phase === "downloading"; |
| 108 | const percent = state.totalBytes > 0 |
| 109 | ? Math.max(0, Math.min(100, Math.floor((state.receivedBytes || 0) / state.totalBytes * 100))) |
| 110 | : null; |
| 111 | const label = downloading ? `正在下载更新${percent === null ? "" : ` ${percent}%`}` |
| 112 | : state.phase === "verifying" || state.phase === "downloaded" ? "正在验证更新" |
| 113 | : state.phase === "installing" ? "正在安装更新,完成后自动重启" |
| 114 | : state.phase === "checking" ? "正在准备更新" |
| 115 | : coolingDown ? "等待重试更新" : failed ? "重试更新" : "下载更新"; |
| 116 | const hint = coolingDown ? `${state.message || "更新源请求受限"},可于 ${new Date(state.retryAt).toLocaleString()} 后重试` |
| 117 | : failed ? `${state.message || "更新未完成"},点击重试` |
| 118 | : busy ? label : `更新至 ${state.latestVersion}。请先保存工作,点击后将自动停止环境、安装并重启。`; |
| 119 | const circumference = 2 * Math.PI * 15; |
| 120 | return ( |
| 121 | <> |
| 122 | {visible && <button |
| 123 | className={`app-update-button${busy ? " busy" : ""}${failed ? " failed" : ""}`} |
| 124 | aria-label={label} |
| 125 | title={hint} |
| 126 | disabled={busy || coolingDown} |
| 127 | onClick={() => { setFailure(""); void run("install"); }} |
| 128 | > |
| 129 | {busy ? ( |
| 130 | <> |
| 131 | <svg className={`app-update-ring${downloading && percent !== null ? "" : " indeterminate"}`} |
| 132 | viewBox="0 0 36 36" role="progressbar" aria-label={downloading ? "更新下载进度" : label} |
| 133 | aria-valuemin={0} aria-valuemax={100} aria-valuenow={downloading && percent !== null ? percent : undefined}> |
| 134 | <circle className="app-update-ring-track" cx="18" cy="18" r="15" /> |
| 135 | <circle className="app-update-ring-value" cx="18" cy="18" r="15" |
| 136 | strokeDasharray={circumference} strokeDashoffset={circumference * (1 - (downloading && percent !== null ? percent / 100 : 0.25))} /> |
| 137 | </svg> |
| 138 | {downloading && percent !== null && <span className="app-update-percent">{percent}%</span>} |
| 139 | </> |
| 140 | ) : failed ? <RefreshCw size={20} /> : <ArrowDownToLine size={20} />} |
| 141 | </button>} |
| 142 | {(failure || startupFailure) && <div className="app-update-error" role="alert">{failure || startupFailure}{visible ? coolingDown ? "。请等待更新源恢复后重试。" : "。可点击更新按钮重试。" : ""}</div>} |
| 143 | </> |
| 144 | ); |
| 145 | } |