feat(electron-shell): 补录壳子源码(排除运行环境与构建产物)
This commit is contained in:
@@ -0,0 +1,313 @@
|
||||
// 壳子(主程序)自动更新:检查 → 用户确认下载(带进度)→ 点击重启升级。
|
||||
// 对齐 Python shell_updater.py 的状态结构与并发控制。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { spawn } = require("child_process");
|
||||
const cp = require("./cpclient");
|
||||
const config = require("./config");
|
||||
const { versionLt, sha256Hex } = require("./crypto");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("shell-updater");
|
||||
|
||||
const SHELL_CACHE = path.join(config.APP_DATA, "shell");
|
||||
const PERIODIC_INTERVAL = 30 * 60 * 1000;
|
||||
|
||||
let _checking = false;
|
||||
let _downloading = false;
|
||||
let _pendingVersion = "";
|
||||
let _pendingNotes = "";
|
||||
|
||||
const _STATE = {
|
||||
checking: false,
|
||||
check_at: 0,
|
||||
latest: "",
|
||||
notes: "",
|
||||
available: false,
|
||||
check_error: "",
|
||||
dl_version: "",
|
||||
dl_status: "idle", // idle | downloading | downloaded | failed
|
||||
dl_received: 0,
|
||||
dl_total: 0,
|
||||
dl_pct: 0,
|
||||
dl_error: "",
|
||||
applying: false,
|
||||
};
|
||||
|
||||
function shellVersionFile() {
|
||||
// 打包运行:exe 同级 shell.version
|
||||
if (process.env.ELECTRON_RUN_AS_NODE) return null;
|
||||
if (process.resourcesPath) return path.join(path.dirname(process.execPath), "shell.version");
|
||||
return null;
|
||||
}
|
||||
|
||||
function localShellVersion() {
|
||||
const vf = shellVersionFile();
|
||||
if (!vf) return ""; // 源码/CLI 开发模式:不参与自更新
|
||||
try {
|
||||
return fs.existsSync(vf) ? fs.readFileSync(vf, "utf-8").trim() : "";
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchCloudVersion() {
|
||||
if (!localShellVersion() || !config.CONTROLPLANE_URL) {
|
||||
_STATE.check_error = !localShellVersion() ? "源码开发模式,不参与自更新" : "未配置中心机地址";
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const r = await cp.request("GET", "/api/shell/version", { headers: cp.machineHeaders(), timeout: 5 });
|
||||
return r;
|
||||
} catch (e) {
|
||||
logger.info(`检查壳子更新失败(离线跳过):${e.message}`);
|
||||
_STATE.check_error = `控制面不可达(${e.constructor.name})`;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function cachedPkg(version) {
|
||||
const p = path.join(SHELL_CACHE, `setup-37du-host-${version}.exe`);
|
||||
return fs.existsSync(p) ? p : null;
|
||||
}
|
||||
|
||||
function restorePending(cloud, notes) {
|
||||
_pendingVersion = cloud;
|
||||
_pendingNotes = notes;
|
||||
_STATE.dl_version = cloud;
|
||||
_STATE.dl_status = "downloaded";
|
||||
_STATE.dl_pct = 100;
|
||||
logger.info(`壳子新版本 ${cloud} 已在缓存中,等待用户重启更新`);
|
||||
}
|
||||
|
||||
async function checkUpdate() {
|
||||
if (_checking) return;
|
||||
_checking = true;
|
||||
try {
|
||||
_STATE.checking = true;
|
||||
const cur = localShellVersion();
|
||||
const info = await fetchCloudVersion();
|
||||
_STATE.check_at = Date.now();
|
||||
if (!cur) {
|
||||
_STATE.latest = "";
|
||||
_STATE.notes = "";
|
||||
_STATE.available = false;
|
||||
return;
|
||||
}
|
||||
if (!info) {
|
||||
_STATE.available = false;
|
||||
return;
|
||||
}
|
||||
const cloud = String(info.version || "");
|
||||
const notes = String(info.notes || "");
|
||||
_STATE.latest = cloud;
|
||||
_STATE.notes = notes;
|
||||
_STATE.check_error = "";
|
||||
if (!cloud || !versionLt(cur, cloud)) {
|
||||
_STATE.available = false;
|
||||
return;
|
||||
}
|
||||
_STATE.available = true;
|
||||
if (cachedPkg(cloud)) restorePending(cloud, notes);
|
||||
} finally {
|
||||
_STATE.checking = false;
|
||||
_checking = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startCheck() {
|
||||
void checkUpdate();
|
||||
}
|
||||
|
||||
function startPeriodicCheck() {
|
||||
setInterval(() => {
|
||||
try {
|
||||
void checkUpdate();
|
||||
} catch (e) {
|
||||
logger.warning(`周期检查壳子更新失败:${e.message}`);
|
||||
}
|
||||
}, PERIODIC_INTERVAL);
|
||||
}
|
||||
|
||||
async function startDownload() {
|
||||
const cur = localShellVersion();
|
||||
if (!cur) return;
|
||||
if (_STATE.dl_status === "downloading") return;
|
||||
if (_STATE.dl_status === "downloaded" && _pendingVersion) return;
|
||||
const info = await fetchCloudVersion();
|
||||
if (!info) return;
|
||||
const cloud = String(info.version || "");
|
||||
if (!cloud || !versionLt(cur, cloud)) return;
|
||||
if (cachedPkg(cloud)) {
|
||||
restorePending(cloud, String(info.notes || ""));
|
||||
return;
|
||||
}
|
||||
if (_downloading) return;
|
||||
_downloading = true;
|
||||
_STATE.dl_version = cloud;
|
||||
_STATE.dl_status = "downloading";
|
||||
_STATE.dl_received = 0;
|
||||
_STATE.dl_total = 0;
|
||||
_STATE.dl_pct = 0;
|
||||
_STATE.dl_error = "";
|
||||
try {
|
||||
await download(cloud, info);
|
||||
} catch (e) {
|
||||
logger.warning(`下载壳子安装包失败:${e.message}`);
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = `安装包下载失败(${e.constructor.name})`;
|
||||
cleanupPart(cloud);
|
||||
} finally {
|
||||
_downloading = false;
|
||||
}
|
||||
logger.info(`开始下载壳子新版本 ${cloud}`);
|
||||
}
|
||||
|
||||
async function download(cloud, info) {
|
||||
const innerUrl = String(info.url || "").trim();
|
||||
const tmp = path.join(SHELL_CACHE, `setup-37du-host-${cloud}.exe.part`);
|
||||
const pkg = path.join(SHELL_CACHE, `setup-37du-host-${cloud}.exe`);
|
||||
const expect = String(info.sha256 || "").toLowerCase();
|
||||
fs.mkdirSync(SHELL_CACHE, { recursive: true });
|
||||
const out = fs.createWriteStream(tmp);
|
||||
const crypto = require("crypto");
|
||||
const sha = crypto.createHash("sha256");
|
||||
let received = 0;
|
||||
let total = 0;
|
||||
if (innerUrl) {
|
||||
await downloadFromUrl(innerUrl, {}, out, sha, (rcv, tot) => {
|
||||
received = rcv;
|
||||
total = tot;
|
||||
_STATE.dl_received = received;
|
||||
_STATE.dl_total = total;
|
||||
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
|
||||
});
|
||||
} else {
|
||||
const r = await cp.streamDownload("/api/shell/pkg", {
|
||||
headers: cp.machineHeaders(),
|
||||
timeout: 600,
|
||||
onData: (chunk) => {
|
||||
out.write(chunk);
|
||||
sha.update(chunk);
|
||||
},
|
||||
onProgress: (rcv, tot) => {
|
||||
received = rcv;
|
||||
total = tot;
|
||||
_STATE.dl_received = received;
|
||||
_STATE.dl_total = total;
|
||||
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
|
||||
},
|
||||
});
|
||||
received = r.received;
|
||||
total = r.contentLength;
|
||||
}
|
||||
await new Promise((res, rej) => out.end((e) => (e ? rej(e) : res())));
|
||||
const digest = sha.digest("hex");
|
||||
if (expect && digest !== expect) {
|
||||
logger.error(`壳子安装包 sha256 校验失败,放弃更新`);
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = "安装包校验失败,请重试";
|
||||
cleanupPart(cloud);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
fs.renameSync(tmp, pkg);
|
||||
} catch (e) {
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = "安装包保存失败";
|
||||
cleanupPart(cloud);
|
||||
return;
|
||||
}
|
||||
_STATE.dl_status = "downloaded";
|
||||
_STATE.dl_pct = 100;
|
||||
_STATE.dl_received = received;
|
||||
_STATE.dl_total = total;
|
||||
restorePending(cloud, String(info.notes || ""));
|
||||
}
|
||||
|
||||
async function downloadFromUrl(url, headers, out, sha, onProgress) {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 600 * 1000);
|
||||
const res = await fetch(url, { headers, signal: ctrl.signal, redirect: "follow" });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const total = parseInt(res.headers.get("content-length") || "0", 10);
|
||||
let received = 0;
|
||||
const reader = res.body.getReader();
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
out.write(value);
|
||||
sha.update(value);
|
||||
received += value.length;
|
||||
onProgress(received, total);
|
||||
}
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
function cleanupPart(cloud) {
|
||||
try {
|
||||
fs.unlinkSync(path.join(SHELL_CACHE, `setup-37du-host-${cloud}.exe.part`));
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
function pendingStatus() {
|
||||
let cur = localShellVersion();
|
||||
let downloaded = !!_pendingVersion && cachedPkg(_pendingVersion) !== null;
|
||||
if (!downloaded) {
|
||||
_pendingVersion = "";
|
||||
_pendingNotes = "";
|
||||
}
|
||||
return {
|
||||
current: cur,
|
||||
new: downloaded ? _pendingVersion : "",
|
||||
notes: downloaded ? _pendingNotes : "",
|
||||
downloaded,
|
||||
available: !!_STATE.available,
|
||||
latest: _STATE.latest || "",
|
||||
checked_at: _STATE.check_at || 0,
|
||||
checking: !!_STATE.checking,
|
||||
error: _STATE.check_error || "",
|
||||
applying: !!_STATE.applying,
|
||||
dl: {
|
||||
version: _STATE.dl_version || "",
|
||||
status: _STATE.dl_status || "idle",
|
||||
received: _STATE.dl_received || 0,
|
||||
total: _STATE.dl_total || 0,
|
||||
pct: _STATE.dl_pct || 0,
|
||||
error: _STATE.dl_error || "",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function applyUpdate() {
|
||||
const version = _pendingVersion;
|
||||
const pkg = cachedPkg(version);
|
||||
if (!pkg) throw new Error(`未找到已下载的安装包:setup-37du-host-${version}.exe`);
|
||||
_STATE.applying = true;
|
||||
logger.info(`开始静默升级到 ${version}:${pkg}`);
|
||||
const child = spawn(pkg, ["/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"], {
|
||||
cwd: path.dirname(pkg),
|
||||
windowsHide: true,
|
||||
stdio: "ignore",
|
||||
detached: true,
|
||||
});
|
||||
child.unref();
|
||||
// 给安装器接管进程,随后退出
|
||||
setTimeout(() => {
|
||||
if (typeof process.exit === "function") process.exit(0);
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
startCheck,
|
||||
startPeriodicCheck,
|
||||
startDownload,
|
||||
pendingStatus,
|
||||
applyUpdate,
|
||||
cachedPkg,
|
||||
localShellVersion,
|
||||
};
|
||||
Reference in New Issue
Block a user