feat(electron-shell): 启动链路修复与执行/配置收口插件侧
- 启动链路 P1-P7 修复:预算对齐、完成事件推送、端口占用提示、前端阶段文案接管 - 静态缓存按 IS_FROZEN 区分开发/打包态,bootPhaseOwned 竞态修复 - 一键执行与参数配置统一收口到插件界面,定时任务引用 config_id - 环境包迁移到 %LOCALAPPDATA%\37duAutomation\python-env,重装零解压 - shell-updater:缓存包 sha256 校验、静默升级后自动拉起新版、自动清理旧安装包 - after-pack 钩子生成 shell.version 修复打包态版本识别 - 插件 xq0031/xq0045 迁移至 plugins/XQ0001-0100/ 号段分桶中文目录
This commit is contained in:
@@ -16,6 +16,7 @@ const tasks = require("./tasks");
|
||||
const shellUpdater = require("./shell-updater");
|
||||
const chromeManager = require("./chrome-manager");
|
||||
const envSync = require("./env-sync");
|
||||
const { HUB } = require("./hub");
|
||||
const { makeLogger, setLogFile } = require("./logger");
|
||||
|
||||
const logger = makeLogger("app");
|
||||
@@ -72,6 +73,7 @@ async function init(options = {}) {
|
||||
setLogFile(path.join(config.APP_DATA, "logs", "shell.log"));
|
||||
}
|
||||
|
||||
state.setBootStep("加载配置与本地服务");
|
||||
scheduler.initActive();
|
||||
|
||||
// 账号:优先 .env,其次最近活跃本机会话
|
||||
@@ -79,6 +81,7 @@ async function init(options = {}) {
|
||||
if (config.CONTROLPLANE_URL) {
|
||||
// 权限白名单(fail-closed)
|
||||
try {
|
||||
state.setBootStep("同步权限白名单");
|
||||
const allowed = await pluginSync.resolveAllowed(account);
|
||||
state.setAllowed(allowed);
|
||||
} catch (e) {
|
||||
@@ -87,6 +90,7 @@ async function init(options = {}) {
|
||||
|
||||
// 敏感凭证中心化下发(在线拉取 RSA 解密 / 本地缓存兜底;失败不阻断启动)
|
||||
try {
|
||||
state.setBootStep("下发敏感凭证");
|
||||
const creds = await require("./creds-sync").load(account);
|
||||
if (creds && Object.keys(creds).length) {
|
||||
config.applyCreds(creds);
|
||||
@@ -99,6 +103,7 @@ async function init(options = {}) {
|
||||
// 启动同步离线授权票据
|
||||
if (account) {
|
||||
try {
|
||||
state.setBootStep("同步授权票据");
|
||||
await licensing.syncLicensing(account);
|
||||
logger.info(`启动同步离线授权票据成功(账号 ${account})`);
|
||||
} catch (e) {
|
||||
@@ -116,12 +121,15 @@ async function init(options = {}) {
|
||||
const manifest = await pluginSync.cloudPluginManifest(firstAcct);
|
||||
if (manifest !== null) state.setAllowed(new Set(manifest.map((p) => p.id)));
|
||||
logger.info(`启动插件更新完成(账号 ${firstAcct})`);
|
||||
try { HUB.publish({ t: "plugins_synced" }); } catch (e) { /* 忽略 */ }
|
||||
})
|
||||
.catch((e) => logger.warning(`启动插件更新失败:${e.message}`));
|
||||
}
|
||||
|
||||
// 环境包(便携 Python 运行时):启动即检查(异步不阻塞),缺失/有新版本自动下载;
|
||||
// 插件执行/平台登录在环境包就绪前会报"环境包未就绪",由设置页提供状态与手动更新
|
||||
state.setBootStep("检查便携环境包");
|
||||
envSync.migrateLegacyEnvRoot(); // 一次性:把旧版装在安装目录的环境包迁到 APP_DATA(重装不丢)
|
||||
void envSync
|
||||
.checkAndSync()
|
||||
.then((r) => logger.info(`环境包检查:${r.ok ? `就绪 v${r.version || ""}` : `未就绪(${r.reason})`}`))
|
||||
@@ -131,7 +139,8 @@ async function init(options = {}) {
|
||||
void envSync.checkAndSync().catch((e) => logger.warning(`环境包周期检查异常:${e.message}`));
|
||||
}, 30 * 60 * 1000);
|
||||
|
||||
// 壳子更新:启动检查 + 常驻周期检查
|
||||
// 壳子更新:启动检查 + 常驻周期检查(顺带清扫升级遗留的安装包/批处理)
|
||||
shellUpdater.cleanupStalePackages();
|
||||
shellUpdater.startCheck();
|
||||
shellUpdater.startPeriodicCheck();
|
||||
|
||||
@@ -151,6 +160,8 @@ async function init(options = {}) {
|
||||
|
||||
logger.info(`插件根目录:${registry.pluginRoot()}`);
|
||||
logger.info(`数据根目录:${config.APP_DATA}`);
|
||||
state.setBootStep("启动就绪", "本地服务已就绪");
|
||||
state.setBootDone();
|
||||
return { deviceId: deviceId(), account };
|
||||
}
|
||||
|
||||
|
||||
@@ -126,12 +126,13 @@ async function status() {
|
||||
return {
|
||||
installed: !!_STATE.installed,
|
||||
version: _STATE.version || "",
|
||||
downloaded: !!pkgOk,
|
||||
// 已安装时不再暴露"安装包已就绪",避免前端误触发重新安装
|
||||
downloaded: !_STATE.installed && !!pkgOk,
|
||||
cloud_available: !!_STATE.cloud_available,
|
||||
error: _STATE.check_error || "",
|
||||
installing: !!_STATE.installing,
|
||||
dl: {
|
||||
status: _STATE.dl_status || "idle",
|
||||
status: _STATE.installed && _STATE.dl_status === "downloaded" ? "idle" : (_STATE.dl_status || "idle"),
|
||||
received: _STATE.dl_received || 0,
|
||||
total: _STATE.dl_total || 0,
|
||||
pct: _STATE.dl_pct || 0,
|
||||
@@ -268,6 +269,8 @@ async function pollInstall() {
|
||||
_STATE.installing = false;
|
||||
_STATE.installed = true;
|
||||
_STATE.version = local.version;
|
||||
_STATE.dl_status = "idle"; // 已安装,安装包不再参与状态,避免重复安装
|
||||
_pendingPkg = null; // 释放安装包句柄,后续点击走「重新检测」而非再装
|
||||
logger.info(`Chrome 安装完成:${_STATE.version}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -23,20 +23,25 @@ const DESKTOP_ROOT = path.resolve(SHELL_ROOT, "..");
|
||||
|
||||
// ==================== 轻量 .env 加载(仅本模块目录,变量已存在则不覆盖) ====================
|
||||
function loadDotEnv() {
|
||||
const envPath = path.join(SHELL_ROOT, ".env");
|
||||
if (!fs.existsSync(envPath)) return;
|
||||
try {
|
||||
const text = fs.readFileSync(envPath, "utf-8");
|
||||
for (const rawLine of text.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith("#") || !line.includes("=")) continue;
|
||||
const idx = line.indexOf("=");
|
||||
const key = line.slice(0, idx).trim();
|
||||
const value = line.slice(idx + 1).trim();
|
||||
if (key && process.env[key] === undefined) process.env[key] = value;
|
||||
// 开发/CLI:读本模块 .env;打包态额外读 resources/.env(electron-builder extraResources 带入,
|
||||
// 位于 asar 外的真实文件,可随包分发或按机器覆盖)
|
||||
const candidates = [path.join(SHELL_ROOT, ".env")];
|
||||
if (IS_FROZEN) candidates.push(path.join(process.resourcesPath, ".env"));
|
||||
for (const envPath of candidates) {
|
||||
if (!fs.existsSync(envPath)) continue;
|
||||
try {
|
||||
const text = fs.readFileSync(envPath, "utf-8");
|
||||
for (const rawLine of text.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith("#") || !line.includes("=")) continue;
|
||||
const idx = line.indexOf("=");
|
||||
const key = line.slice(0, idx).trim();
|
||||
const value = line.slice(idx + 1).trim();
|
||||
if (key && process.env[key] === undefined) process.env[key] = value;
|
||||
}
|
||||
} catch (e) {
|
||||
// 读取失败静默(与 Python 实现一致)
|
||||
}
|
||||
} catch (e) {
|
||||
// 读取失败静默(与 Python 实现一致)
|
||||
}
|
||||
}
|
||||
loadDotEnv();
|
||||
@@ -93,10 +98,12 @@ const RUN_MAX_MEM_MB = parseInt(process.env.RUN_MAX_MEM_MB || "2048", 10);
|
||||
|
||||
// ==================== 便携 Python 环境包(python-env) ====================
|
||||
// 版本化目录(python-env/<version>/)+ current.json 指向当前版本,保留上一版供回滚。
|
||||
// 目录位置:打包态 = exe 同级 python-env/;开发态 = electron-shell/python-env/(可本地构建联调)。
|
||||
// 目录位置:打包态 = %LOCALAPPDATA%\37duAutomation\python-env——NSIS 重装/升级会清空安装目录,
|
||||
// 放 exe 同级会导致环境包每次陪葬重新下载解压(其余持久化数据本就都在 APP_DATA);
|
||||
// 开发态 = electron-shell/python-env/(可本地构建联调)。
|
||||
function envRootDir() {
|
||||
if (process.env.SHELL_PYTHON_ENV_ROOT) return path.resolve(process.env.SHELL_PYTHON_ENV_ROOT);
|
||||
if (IS_FROZEN) return path.join(path.dirname(process.execPath), "python-env");
|
||||
if (IS_FROZEN) return path.join(APP_DATA, "python-env");
|
||||
return path.join(SHELL_ROOT, "python-env");
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,13 @@ const logger = makeLogger("db");
|
||||
|
||||
const DB_PATH = path.join(config.APP_DATA, "shell.db");
|
||||
|
||||
// 首次运行数据目录可能不存在,better-sqlite3 会直接报"目录不存在",先建目录
|
||||
try {
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
} catch (e) {
|
||||
/* 忽略:只读环境等极端情况由后续建库报错兜底 */
|
||||
}
|
||||
|
||||
// 打开即建库建表(幂等);WAL 提升并发读性能,写仍同步
|
||||
const db = new Database(DB_PATH);
|
||||
db.pragma("journal_mode = WAL");
|
||||
|
||||
@@ -56,6 +56,7 @@ function saveWindowState(win) {
|
||||
let mainWindow = null;
|
||||
let tray = null;
|
||||
let server = null;
|
||||
let isQuitting = false; // 托盘「退出」/系统退出时置真,放行真正关闭;否则关闭窗口 = 收托盘
|
||||
|
||||
// 单实例锁:重复启动聚焦已有窗口
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
@@ -79,7 +80,8 @@ if (!app.requestSingleInstanceLock()) {
|
||||
y: st.y,
|
||||
minWidth: 1000,
|
||||
minHeight: 660,
|
||||
backgroundColor: "#eef2f9",
|
||||
// 与启动页默认皮肤底色一致(style.css --bg #F9F7F2),避免冷启动色跳
|
||||
backgroundColor: "#F9F7F2",
|
||||
title: "37du 自动化工作台",
|
||||
icon: trayIconImage(),
|
||||
webPreferences: {
|
||||
@@ -101,8 +103,14 @@ if (!app.requestSingleInstanceLock()) {
|
||||
};
|
||||
mainWindow.on("resize", save);
|
||||
mainWindow.on("move", save);
|
||||
mainWindow.on("close", () => {
|
||||
if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow);
|
||||
mainWindow.on("close", (e) => {
|
||||
if (isQuitting) {
|
||||
if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow);
|
||||
return; // 真正退出:放行关闭
|
||||
}
|
||||
// 关闭按钮 → 收托盘(隐藏窗口,服务/插件继续运行),从托盘菜单「退出」才真正退出
|
||||
e.preventDefault();
|
||||
mainWindow.hide();
|
||||
});
|
||||
mainWindow.on("closed", () => {
|
||||
mainWindow = null;
|
||||
@@ -110,6 +118,15 @@ if (!app.requestSingleInstanceLock()) {
|
||||
}
|
||||
|
||||
function trayIconImage() {
|
||||
// 优先用官方图标(Windows 托盘/窗口均正常渲染);缺失时 SVG 兜底。
|
||||
// 打包态:resources/assets/icon.ico(extraResources 真实文件);开发态:本模块 assets/
|
||||
const ico = config.IS_FROZEN
|
||||
? path.join(process.resourcesPath, "assets", "icon.ico")
|
||||
: path.join(__dirname, "..", "assets", "icon.ico");
|
||||
if (fs.existsSync(ico)) {
|
||||
const img = nativeImage.createFromPath(ico);
|
||||
if (!img.isEmpty()) return img;
|
||||
}
|
||||
// 16x16 蓝色圆点占位图标(正式打包时替换为 tools/icon.ico 生成的 png)
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" rx="4" fill="#3b6cf6"/><text x="8" y="12" font-size="10" text-anchor="middle" fill="#fff" font-family="sans-serif">37</text></svg>`;
|
||||
return nativeImage.createFromDataURL(`data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`);
|
||||
@@ -118,7 +135,14 @@ if (!app.requestSingleInstanceLock()) {
|
||||
function createTray() {
|
||||
tray = new Tray(trayIconImage());
|
||||
const ctx = Menu.buildFromTemplate([
|
||||
{ label: "打开工作台", click: () => createWindow() },
|
||||
{
|
||||
label: "打开工作台",
|
||||
click: () => {
|
||||
// 关闭窗口只是收托盘(窗口仍存在),此处复用已有窗口而非重复新建
|
||||
if (!mainWindow) createWindow();
|
||||
else { mainWindow.show(); mainWindow.focus(); }
|
||||
},
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "开机自启",
|
||||
@@ -143,12 +167,15 @@ if (!app.requestSingleInstanceLock()) {
|
||||
try {
|
||||
const { init } = require("./app");
|
||||
const { listen } = require("./server");
|
||||
await init();
|
||||
// 先起本地服务并【立即创建窗口】(登录页/首屏立刻可见),网络初始化放后台执行。
|
||||
// 否则 `await init()` 里 resolveAllowed/凭证/授权等串行网络调用在中心机不可达时会逐个
|
||||
// 超时,窗口迟迟不出 —— 表现为"后台静默加载、毫无提示、像卡死"。
|
||||
server = listen(() => {
|
||||
createWindow();
|
||||
createTray();
|
||||
logger.info("Electron 壳就绪");
|
||||
});
|
||||
void init().catch((e) => logger.error(`后台初始化异常:${e.stack || e}`));
|
||||
} catch (e) {
|
||||
logger.error(`启动失败:${e.stack || e}`);
|
||||
dialog.showErrorBox("37du 自动化工作台", `启动失败:${e.message}`);
|
||||
@@ -157,10 +184,12 @@ if (!app.requestSingleInstanceLock()) {
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
app.quit(); // Windows:关闭窗口即退出(服务随主进程结束)
|
||||
// 关闭窗口默认收托盘(close 已拦截),只有真正退出路径才会走到这里
|
||||
app.quit();
|
||||
});
|
||||
|
||||
app.on("before-quit", () => {
|
||||
isQuitting = true; // 放行主窗口真正关闭
|
||||
try {
|
||||
if (server) server.close();
|
||||
} catch (e) {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// 环境包解压工作子进程(utilityProcess.fork 启动)。
|
||||
// AdmZip.extractAllTo 是同步 API,294MB 环境包若在主进程解压会阻塞事件循环几十秒,
|
||||
// 期间窗口点击必现"未响应"。故将【解压+校验+原子切换】整体下沉到子进程,主进程保持响应。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const AdmZip = require("adm-zip");
|
||||
|
||||
const { parentPort } = process;
|
||||
|
||||
function rm(p) {
|
||||
try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* 忽略 */ }
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
const end = Date.now() + ms;
|
||||
while (Date.now() < end) { /* 忙等(子进程内允许,避免阻塞主进程) */ }
|
||||
}
|
||||
|
||||
// 入参:process.argv = [modulePath, zip, tmp, target]
|
||||
async function main() {
|
||||
const zip = process.argv[2];
|
||||
const tmp = process.argv[3];
|
||||
const target = process.argv[4];
|
||||
try {
|
||||
rm(tmp);
|
||||
rm(target);
|
||||
fs.mkdirSync(tmp, { recursive: true });
|
||||
|
||||
// 防路径穿越
|
||||
const az = new AdmZip(zip);
|
||||
for (const en of az.getEntries()) {
|
||||
const name = en.entryName.replace(/\\/g, "/");
|
||||
if (name.startsWith("/") || name.split("/").includes("..")) {
|
||||
throw new Error(`环境包含非法路径: ${name}`);
|
||||
}
|
||||
}
|
||||
// 同步解压(本进程阻塞无所谓)
|
||||
az.extractAllTo(tmp, true);
|
||||
|
||||
// 冒烟校验:必须含 python.exe + plugin_runner.py
|
||||
if (!fs.existsSync(path.join(tmp, "python.exe"))) throw new Error("环境包缺少 python.exe");
|
||||
if (!fs.existsSync(path.join(tmp, "webhost", "backend", "core", "plugin_runner.py"))) {
|
||||
throw new Error("环境包缺少 plugin_runner.py");
|
||||
}
|
||||
|
||||
// 原子切换(带重试:杀软可能短暂占用新解压文件导致 rename EPERM)
|
||||
let lastErr = null;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
try {
|
||||
fs.renameSync(tmp, target);
|
||||
parentPort.postMessage({ ok: true, target });
|
||||
return;
|
||||
} catch (e) {
|
||||
lastErr = e;
|
||||
sleep(500 * (i + 1));
|
||||
}
|
||||
}
|
||||
throw lastErr || new Error("环境包切换失败");
|
||||
} catch (e) {
|
||||
parentPort.postMessage({ ok: false, error: (e && e.message) || String(e) });
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -21,7 +21,7 @@ const _STATE = {
|
||||
dir: "",
|
||||
cloud_available: false,
|
||||
cloud_version: "",
|
||||
dl_status: "idle", // idle | downloading | downloaded | failed
|
||||
dl_status: "idle", // idle | downloading | downloaded | extracting | failed
|
||||
dl_received: 0,
|
||||
dl_total: 0,
|
||||
dl_pct: 0,
|
||||
@@ -146,34 +146,56 @@ async function downloadZip(info) {
|
||||
return zip;
|
||||
}
|
||||
|
||||
// 解压 zip → python-env/<version>/,防路径穿越;返回版本目录
|
||||
async function extractZip(zip, version) {
|
||||
const target = path.join(envDir(), version);
|
||||
const tmp = path.join(envDir(), `.${version}.tmp`);
|
||||
// 解压 zip → python-env/<version>/,防路径穿越;返回版本目录。
|
||||
// ★ 解压是同步重活(294MB → ~600MB),Electron 主进程内直接跑会阻塞事件循环几十秒
|
||||
// (表现为"启动时点窗口就未响应"),故下沉到子进程(utilityProcess)执行;
|
||||
// CLI 纯 Node 模式无窗口,保留同步兜底。
|
||||
function extractViaChildProcess(zip, tmp, target) {
|
||||
const electron = require("electron");
|
||||
const child = electron.utilityProcess.fork(
|
||||
path.join(__dirname, "env-extract-worker.js"),
|
||||
[zip, tmp, target],
|
||||
{ serviceName: "env-extract" }
|
||||
);
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
try { child.kill(); } catch (e) { /* 忽略 */ }
|
||||
reject(new Error("环境包解压超时"));
|
||||
}, 600 * 1000);
|
||||
child.once("message", (m) => {
|
||||
clearTimeout(timer);
|
||||
try { child.kill(); } catch (e) { /* 忽略 */ }
|
||||
if (m && m.ok) resolve(m.target);
|
||||
else reject(new Error((m && m.error) || "环境包解压失败"));
|
||||
});
|
||||
child.once("error", (e) => { clearTimeout(timer); reject(e); });
|
||||
child.once("exit", (code) => {
|
||||
clearTimeout(timer);
|
||||
if (code !== 0) reject(new Error(`环境包解压子进程退出 code=${code}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function extractInline(zip, tmp, target) {
|
||||
// CLI 纯 Node 兜底:同步解压(无窗口,阻塞无感);逻辑与子进程内一致
|
||||
const rm = (p) => {
|
||||
try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* 忽略 */ }
|
||||
};
|
||||
// 清理可能的残留临时目录
|
||||
rm(tmp);
|
||||
rm(target);
|
||||
fs.mkdirSync(tmp, { recursive: true });
|
||||
|
||||
const az = new AdmZip(zip);
|
||||
const entries = az.getEntries();
|
||||
for (const en of entries) {
|
||||
for (const en of az.getEntries()) {
|
||||
const name = en.entryName.replace(/\\/g, "/");
|
||||
if (name.startsWith("/") || name.split("/").includes("..")) {
|
||||
throw new Error(`环境包含非法路径: ${name}`);
|
||||
}
|
||||
}
|
||||
az.extractAllTo(tmp, true);
|
||||
|
||||
// 冒烟校验:必须含 python.exe + webhost/backend/core/plugin_runner.py
|
||||
if (!fs.existsSync(path.join(tmp, "python.exe"))) throw new Error("环境包缺少 python.exe");
|
||||
if (!fs.existsSync(path.join(tmp, "webhost", "backend", "core", "plugin_runner.py"))) {
|
||||
throw new Error("环境包缺少 plugin_runner.py");
|
||||
}
|
||||
// 原子切换(带重试:杀软可能短暂占用新解压文件导致 rename EPERM)
|
||||
let lastErr = null;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
try {
|
||||
@@ -181,12 +203,23 @@ async function extractZip(zip, version) {
|
||||
return target;
|
||||
} catch (e) {
|
||||
lastErr = e;
|
||||
await new Promise((r) => setTimeout(r, 500 * (i + 1)));
|
||||
// 用同步忙等替代 await(保持函数同步语义;仅 CLI 路径用到)
|
||||
const end = Date.now() + 500 * (i + 1);
|
||||
while (Date.now() < end) { /* 忙等 */ }
|
||||
}
|
||||
}
|
||||
throw lastErr || new Error("环境包切换失败");
|
||||
}
|
||||
|
||||
async function extractZip(zip, version) {
|
||||
const target = path.join(envDir(), version);
|
||||
const tmp = path.join(envDir(), `.${version}.tmp`);
|
||||
if (process.versions && process.versions.electron) {
|
||||
return extractViaChildProcess(zip, tmp, target);
|
||||
}
|
||||
return extractInline(zip, tmp, target);
|
||||
}
|
||||
|
||||
// 切换当前版本 + 清理旧版本(保留上一版供回滚)
|
||||
function switchCurrent(version) {
|
||||
const cur = readCurrent();
|
||||
@@ -196,14 +229,15 @@ function switchCurrent(version) {
|
||||
JSON.stringify({ version, updated_at: new Date().toISOString() }, null, 2),
|
||||
"utf-8"
|
||||
);
|
||||
// 清理:保留当前 + 上一版;其余删除(异常残留目录也清)
|
||||
// 清理:保留当前 + 上一版;其余删除(异常残留目录也清)。
|
||||
// 旧版本可能数百 MB,rmSync 会阻塞主进程 → 改异步后台删除
|
||||
const keep = new Set([version, cur].filter(Boolean));
|
||||
try {
|
||||
for (const name of fs.readdirSync(envDir())) {
|
||||
if (name === "current.json" || name === "_cache") continue;
|
||||
if (keep.has(name)) continue;
|
||||
const p = path.join(envDir(), name);
|
||||
try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* 忽略 */ }
|
||||
void fs.promises.rm(p, { recursive: true, force: true }).catch(() => {});
|
||||
}
|
||||
} catch (e) { /* 忽略 */ }
|
||||
}
|
||||
@@ -229,6 +263,9 @@ async function checkAndSync(force = false) {
|
||||
const zip = await downloadZip(info);
|
||||
_STATE.dl_status = "downloaded";
|
||||
_STATE.dl_pct = 100;
|
||||
// 显式进入解压阶段(294MB 需几十秒):期间 installed 仍为 false,
|
||||
// 若不标记,前端会把"正在解压"误显示为"环境待装"
|
||||
_STATE.dl_status = "extracting";
|
||||
const dir = await extractZip(zip, info.version);
|
||||
switchCurrent(info.version);
|
||||
_STATE.dl_status = "idle";
|
||||
@@ -265,10 +302,29 @@ function rollback() {
|
||||
return { ok: true, version: target };
|
||||
}
|
||||
|
||||
// 旧版兼容(一次性):v1.0.x 环境包放在安装目录(exe 同级 python-env/),NSIS 重装会清空导致
|
||||
// 每次重装都重新下载解压 294MB;现迁移到 APP_DATA。同盘 rename 瞬时完成,连 _cache(zip 缓存)
|
||||
// 一起带走——同版本重装后 checkAndSync 直接命中 current,零下载零解压。
|
||||
function migrateLegacyEnvRoot() {
|
||||
if (!config.IS_FROZEN) return;
|
||||
const target = envDir();
|
||||
const legacy = path.join(path.dirname(process.execPath), "python-env");
|
||||
if (fs.existsSync(path.join(target, "current.json"))) return; // 新位置已有数据
|
||||
if (!fs.existsSync(path.join(legacy, "current.json"))) return; // 旧位置无数据
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.renameSync(legacy, target);
|
||||
logger.info(`环境包目录已从安装目录迁移到 ${target}`);
|
||||
} catch (e) {
|
||||
logger.warning(`环境包旧目录迁移失败(将重新下载):${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
status,
|
||||
refreshStatus,
|
||||
checkAndSync,
|
||||
migrateLegacyEnvRoot,
|
||||
rollback,
|
||||
readCurrent,
|
||||
envDir,
|
||||
|
||||
@@ -36,6 +36,14 @@ function listConfigs(account, pluginId) {
|
||||
return rows.map(rowToCfg);
|
||||
}
|
||||
|
||||
// 按 id 取单个方案(定时任务到点解析参数用;方案已删除返回 null)
|
||||
function getConfig(account, pluginId, cfgId) {
|
||||
const row = db.prepare(
|
||||
"SELECT id, name, fields, at FROM plugin_configs WHERE account = ? AND plugin_id = ? AND id = ?"
|
||||
).get(account, pluginId, String(cfgId || ""));
|
||||
return rowToCfg(row);
|
||||
}
|
||||
|
||||
// 保存/覆盖:同名方案更新字段,否则新增;返回新/更新后的配置
|
||||
function saveConfig(account, pluginId, name, fields, schema) {
|
||||
const trimmed = String(name || "").trim().slice(0, 20);
|
||||
@@ -70,4 +78,4 @@ function deleteConfig(account, pluginId, cfgId) {
|
||||
return r.changes > 0;
|
||||
}
|
||||
|
||||
module.exports = { MAX_CONFIGS_PER_PLUGIN, listConfigs, saveConfig, deleteConfig };
|
||||
module.exports = { MAX_CONFIGS_PER_PLUGIN, listConfigs, getConfig, saveConfig, deleteConfig };
|
||||
|
||||
@@ -215,7 +215,7 @@ function installPkg(pluginId, content) {
|
||||
fs.mkdirSync(pluginRoot(), { recursive: true });
|
||||
backupForRollback(pluginId); // 升级前保留上一版(首次安装自动跳过)
|
||||
if (fs.existsSync(target)) fs.rmSync(target, { recursive: true, force: true });
|
||||
fs.renameSync(tmp, target);
|
||||
moveDir(tmp, target); // 跨盘兼容:同卷 rename / 跨卷复制+删除
|
||||
} catch (e) {
|
||||
logger.error(`安装插件 ${pluginId} 失败:${e.message}`);
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
@@ -224,6 +224,21 @@ function installPkg(pluginId, content) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 目录移动:同卷用 rename(原子);跨卷(如 %TEMP% 在 C:、插件目录在 D:)Windows 的 rename
|
||||
// 会报 EXDEV,回退为"复制+删除",避免插件安装失败。
|
||||
function moveDir(src, dest) {
|
||||
try {
|
||||
fs.renameSync(src, dest);
|
||||
} catch (e) {
|
||||
if (e.code === "EXDEV") {
|
||||
fs.cpSync(src, dest, { recursive: true });
|
||||
fs.rmSync(src, { recursive: true, force: true });
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function localPluginEntries() {
|
||||
const root = pluginRoot();
|
||||
const out = [];
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
const { spawn } = require("child_process");
|
||||
const readline = require("readline");
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("./config");
|
||||
const state = require("./state");
|
||||
const scheduler = require("./scheduler");
|
||||
@@ -121,9 +123,49 @@ function finishRun(runId, plugin, status, error, summary) {
|
||||
|
||||
// 提交一次插件运行(手动 POST /api/runs 与定时任务共用入口);立即返回 run_id。
|
||||
// opts: { trigger: "manual" | "schedule", schedule_id } —— 用于区分"谁触发的",落进运行历史
|
||||
//
|
||||
// 参数收口到插件侧:插件界面保存的配置(plugin_configs/<id>.json,单配置 blob)是参数权威来源。
|
||||
// 插件界面手动执行会显式传全量 fields,原样使用;壳子侧入口(定时任务未选方案等)传空 fields 时
|
||||
// 回退到该配置,避免"界面配置了一套、定时任务用 plugin.fields 默认值跑"的参数漂移。
|
||||
function loadUiSavedFields(pluginId) {
|
||||
try {
|
||||
const raw = fs.readFileSync(path.join(config.PLUGIN_CONFIG_DIR, `${pluginId}.json`), "utf-8");
|
||||
const v = JSON.parse(raw);
|
||||
return v && typeof v === "object" && !Array.isArray(v) ? v : null;
|
||||
} catch (_) {
|
||||
return null; // 无保存配置/损坏:维持空 fields(插件走自身默认值)
|
||||
}
|
||||
}
|
||||
|
||||
// 环境包未就绪时的拒绝提示:环境包正在下载/解压时提示等待,云端有包但未装时引导状态栏安装
|
||||
function throwEnvNotReady() {
|
||||
let msg = "插件执行环境未就绪,暂时无法执行";
|
||||
try {
|
||||
const es = require("./env-sync").status();
|
||||
if (es.dl && (es.dl.status === "downloading" || es.dl.status === "extracting")) {
|
||||
msg = "环境包正在安装中(下载/解压),完成后即可执行,请稍候";
|
||||
} else if (es.cloud_available) {
|
||||
msg = "环境包未安装,请点击状态栏「环境」完成安装后再执行";
|
||||
}
|
||||
} catch (_) { /* env-sync 不可用时忽略 */ }
|
||||
throw new Error(msg);
|
||||
}
|
||||
|
||||
function submitRun(account, plugin, fields, opts) {
|
||||
const o = opts && typeof opts === "object" ? opts : {};
|
||||
const trigger = o.trigger === "schedule" ? "schedule" : "manual";
|
||||
// 环境未就绪预防:提交前校验执行链路(入口脚本/解释器),缺失时直接拒绝并给可读提示,
|
||||
// 避免子进程 spawn ENOENT 后用户只看到"执行进程异常退出(exit=-4058)且未返回结果"。
|
||||
// 打包态无环境包且未显式配置解释器时也拒绝(系统 python 不可依赖)。
|
||||
if (!fs.existsSync(config.runnerScript()) ||
|
||||
(!process.env.PYTHON_EXE && !config.pythonEnvRoot() && config.IS_FROZEN)) {
|
||||
throwEnvNotReady();
|
||||
}
|
||||
let effFields = fields && typeof fields === "object" && !Array.isArray(fields) ? fields : {};
|
||||
if (Object.keys(effFields).length === 0) {
|
||||
const saved = loadUiSavedFields(plugin.id);
|
||||
if (saved) effFields = saved;
|
||||
}
|
||||
const runId = crypto.randomBytes(16).toString("hex");
|
||||
state.registerRun(runId, {
|
||||
status: "running",
|
||||
@@ -148,7 +190,7 @@ function submitRun(account, plugin, fields, opts) {
|
||||
});
|
||||
licensing.report(account, "", plugin.id, plugin.version || "0", "start");
|
||||
|
||||
void runQueued(plugin, fields, runId, account);
|
||||
void runQueued(plugin, effFields, runId, account);
|
||||
return runId;
|
||||
}
|
||||
|
||||
|
||||
@@ -379,6 +379,11 @@ async function route(req, res, url) {
|
||||
}
|
||||
|
||||
// ---------- 元数据 / 插件同步 ----------
|
||||
// 启动状态(启动页展示"当前在干嘛",无需登录)
|
||||
if (p === "/api/boot/status" && method === "GET") {
|
||||
return sendJson(res, 200, state.bootStatus());
|
||||
}
|
||||
|
||||
if (p === "/api/meta" && method === "GET") {
|
||||
const account = session.sessAccount(cookies);
|
||||
const data = await meta.buildMeta(account);
|
||||
@@ -398,6 +403,10 @@ async function route(req, res, url) {
|
||||
} catch (e) {
|
||||
logger.warning(`同步后刷新授权票据失败:${e.message}`);
|
||||
}
|
||||
// 同步完成 → 推事件,前端据此刷新插件清单(避免用户看到"空场景/请授权"旧值)
|
||||
try {
|
||||
HUB.publish({ t: "plugins_synced", failed: result.failed || [] });
|
||||
} catch (e) { /* 忽略:推送失败不影响返回 */ }
|
||||
return sendJson(res, 200, result);
|
||||
}
|
||||
|
||||
@@ -465,8 +474,8 @@ async function route(req, res, url) {
|
||||
}
|
||||
if (p === "/api/env/sync" && method === "POST") {
|
||||
session.requireLogin(cookies);
|
||||
const r = await envSync.checkAndSync(true);
|
||||
return sendJson(res, 200, { ok: r.ok, reason: r.reason || "", version: r.version || "" });
|
||||
void envSync.checkAndSync(true); // 后台下载+切换,进度经 /api/env/status 轮询展示
|
||||
return sendJson(res, 200, { ok: true });
|
||||
}
|
||||
if (p === "/api/env/rollback" && method === "POST") {
|
||||
session.requireLogin(cookies);
|
||||
@@ -768,6 +777,12 @@ function servePluginUi(res, pluginId, rel) {
|
||||
res.end(body);
|
||||
}
|
||||
|
||||
// 静态资源内存缓存:首屏 index.html/js/css 每次 readFileSync 是同步 IO,会阻塞事件循环,
|
||||
// 与 boot status 轮询、WS 握手抢时间(空机器 + 杀软扫描场景被放大)→ 命中缓存零 IO。
|
||||
// 仅打包态启用:开发态 dist 随时重建,内存缓存会吐旧文件,必须每次读盘。
|
||||
const _STATIC_CACHE = new Map();
|
||||
const STATIC_CACHE_MAX = 200;
|
||||
|
||||
function serveStatic(res, url) {
|
||||
const dist = config.frontendDist();
|
||||
let rel = url.pathname === "/" ? "index.html" : url.pathname.slice(1);
|
||||
@@ -782,7 +797,19 @@ function serveStatic(res, url) {
|
||||
if (!fs.existsSync(target)) return sendJson(res, 404, { detail: "Not Found" });
|
||||
}
|
||||
const mediaType = MIME[path.extname(target).toLowerCase()] || "application/octet-stream";
|
||||
if (config.IS_FROZEN) {
|
||||
const cached = _STATIC_CACHE.get(target);
|
||||
if (cached) {
|
||||
res.writeHead(200, { "Content-Type": mediaType, "Content-Length": cached.length });
|
||||
res.end(cached);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const body = fs.readFileSync(target);
|
||||
if (config.IS_FROZEN) {
|
||||
if (_STATIC_CACHE.size >= STATIC_CACHE_MAX) _STATIC_CACHE.clear(); // 简单防无限增长
|
||||
_STATIC_CACHE.set(target, body);
|
||||
}
|
||||
res.writeHead(200, { "Content-Type": mediaType, "Content-Length": body.length });
|
||||
res.end(body);
|
||||
}
|
||||
@@ -915,6 +942,14 @@ function listen(cb) {
|
||||
} else {
|
||||
logger.error(`本地服务启动失败:${e.message}`);
|
||||
}
|
||||
// 端口占用时窗口还没建,直接 exit 用户只看到"闪一下就没了" → 弹窗说明后再退出
|
||||
try {
|
||||
const { dialog } = require("electron");
|
||||
dialog.showErrorBox(
|
||||
"37du 自动化工作台",
|
||||
`本地服务端口 ${config.PORT} 被占用,无法启动。\n请先关闭旧客户端/底座进程后重试。\n(${e.code || e.message})`
|
||||
);
|
||||
} catch (_e) { /* 非 Electron 环境忽略 */ }
|
||||
process.exit(1);
|
||||
});
|
||||
return server;
|
||||
|
||||
@@ -17,7 +17,9 @@ const _SESS = new Map(); // token -> { account, ts }
|
||||
// account -> 最近云端会话 token(7 天,供 /api/plugins 等用 Bearer)
|
||||
const _ACCT_CLOUD_TOKEN = new Map();
|
||||
|
||||
const SESS_FILE = path.join(config.SHELL_ROOT, "_cp_sessions.json");
|
||||
// 会话落盘放数据根(%LOCALAPPDATA%\37duAutomation)——打包态 SHELL_ROOT 在 app.asar 内只读,
|
||||
// 写到那里会 ENOENT(表现为登录态存不住、反复提示未登录)
|
||||
const SESS_FILE = path.join(config.APP_DATA, "_cp_sessions.json");
|
||||
|
||||
function persist() {
|
||||
const payload = {};
|
||||
@@ -25,6 +27,7 @@ function persist() {
|
||||
payload[token] = [item.account, Math.floor(item.ts / 1000), _ACCT_CLOUD_TOKEN.get(item.account) || ""];
|
||||
}
|
||||
try {
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
fs.writeFileSync(SESS_FILE, JSON.stringify(payload), "utf-8");
|
||||
} catch (e) {
|
||||
logger.warning(`本机会话持久化失败: ${e.message}`);
|
||||
|
||||
@@ -19,6 +19,7 @@ let _checking = false;
|
||||
let _downloading = false;
|
||||
let _pendingVersion = "";
|
||||
let _pendingNotes = "";
|
||||
let _pendingPkg = ""; // 已通过 sha256 校验的缓存安装包绝对路径
|
||||
|
||||
const _STATE = {
|
||||
checking: false,
|
||||
@@ -68,20 +69,54 @@ async function fetchCloudVersion() {
|
||||
}
|
||||
}
|
||||
|
||||
function cachedPkg(version) {
|
||||
// 缓存包校验:sha256 与云端登记不一致(同版本号重新发版/下载中断残留)→ 删除旧包返回 null,
|
||||
// 触发重新下载,避免"缓存命中秒显示下载完成、实际是旧坏包"
|
||||
function validateCache(version, expectSha) {
|
||||
const p = path.join(SHELL_CACHE, `setup-37du-host-${version}.exe`);
|
||||
return fs.existsSync(p) ? p : null;
|
||||
if (!fs.existsSync(p)) return null;
|
||||
if (expectSha) {
|
||||
try {
|
||||
if (sha256Hex(fs.readFileSync(p)) !== String(expectSha).toLowerCase()) {
|
||||
logger.warning(`缓存安装包与云端 sha256 不符(旧坏包),删除后重新下载:${p}`);
|
||||
try { fs.unlinkSync(p); } catch (_) { /* 文件占用时下次再清 */ }
|
||||
return null;
|
||||
}
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
function restorePending(cloud, notes) {
|
||||
function restorePending(cloud, notes, pkgPath) {
|
||||
_pendingVersion = cloud;
|
||||
_pendingNotes = notes;
|
||||
_pendingPkg = pkgPath || "";
|
||||
_STATE.dl_version = cloud;
|
||||
_STATE.dl_status = "downloaded";
|
||||
_STATE.dl_pct = 100;
|
||||
logger.info(`壳子新版本 ${cloud} 已在缓存中,等待用户重启更新`);
|
||||
}
|
||||
|
||||
// 启动清扫:删除缓存中"已安装/过期"的安装包(~80MB/个)与升级批处理。
|
||||
// 版本 <= 本机版本 → 已装或更旧,删除;版本 > 本机 → 可能是已下载待更新的包,保留。
|
||||
// 仅打包态执行(dev 不动缓存),应用启动时调用一次。
|
||||
function cleanupStalePackages() {
|
||||
if (!config.IS_FROZEN) return;
|
||||
const cur = localShellVersion();
|
||||
let files = [];
|
||||
try { files = fs.readdirSync(SHELL_CACHE); } catch (_) { return; }
|
||||
for (const f of files) {
|
||||
const pkg = f.match(/^setup-37du-host-(.+)\.exe$/);
|
||||
const stale = (pkg && (!cur || !versionLt(cur, pkg[1]))) || /^apply-update-.+\.cmd$/.test(f);
|
||||
if (!stale) continue;
|
||||
try {
|
||||
fs.unlinkSync(path.join(SHELL_CACHE, f));
|
||||
logger.info(`清理升级遗留文件:${f}`);
|
||||
} catch (_) { /* 占用中下次启动再清 */ }
|
||||
}
|
||||
}
|
||||
|
||||
async function checkUpdate() {
|
||||
if (_checking) return;
|
||||
_checking = true;
|
||||
@@ -110,7 +145,20 @@ async function checkUpdate() {
|
||||
return;
|
||||
}
|
||||
_STATE.available = true;
|
||||
if (cachedPkg(cloud)) restorePending(cloud, notes);
|
||||
// 多版本跳更:已下载待更新的版本落后于云端 → 作废旧下载(删安装包),重走下载流程。
|
||||
// 否则 pendingStatus 持续报旧版本"已下载",且 startDownload 被 downloaded 态卡死。
|
||||
if (_pendingVersion && versionLt(_pendingVersion, cloud)) {
|
||||
logger.info(`已下载的 ${_pendingVersion} 落后于云端 ${cloud},作废旧安装包`);
|
||||
try { if (_pendingPkg && fs.existsSync(_pendingPkg)) fs.unlinkSync(_pendingPkg); } catch (_) {}
|
||||
_pendingVersion = "";
|
||||
_pendingNotes = "";
|
||||
_pendingPkg = "";
|
||||
_STATE.dl_version = "";
|
||||
_STATE.dl_status = "idle";
|
||||
_STATE.dl_pct = 0;
|
||||
}
|
||||
const cached = validateCache(cloud, info.sha256);
|
||||
if (cached) restorePending(cloud, notes, cached);
|
||||
} finally {
|
||||
_STATE.checking = false;
|
||||
_checking = false;
|
||||
@@ -136,22 +184,35 @@ async function startDownload() {
|
||||
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;
|
||||
// 先置"下载中"态(版本号暂用最近一次检查结果):拉版本信息有网络往返,
|
||||
// 若等它结束才改状态,前端点击后的抢拉会读到 idle,误判成"已下载完成"
|
||||
_STATE.dl_version = _STATE.latest || "";
|
||||
_STATE.dl_status = "downloading";
|
||||
_STATE.dl_received = 0;
|
||||
_STATE.dl_total = 0;
|
||||
_STATE.dl_pct = 0;
|
||||
_STATE.dl_error = "";
|
||||
const info = await fetchCloudVersion();
|
||||
if (!info) {
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = "获取云端版本信息失败";
|
||||
return;
|
||||
}
|
||||
const cloud = String(info.version || "");
|
||||
if (!cloud || !versionLt(cur, cloud)) {
|
||||
_STATE.dl_status = "idle";
|
||||
_STATE.dl_version = "";
|
||||
return;
|
||||
}
|
||||
_STATE.dl_version = cloud;
|
||||
const cached = validateCache(cloud, info.sha256);
|
||||
if (cached) {
|
||||
restorePending(cloud, String(info.notes || ""), cached);
|
||||
return;
|
||||
}
|
||||
if (_downloading) return;
|
||||
_downloading = true;
|
||||
logger.info(`开始下载壳子新版本 ${cloud}`);
|
||||
try {
|
||||
await download(cloud, info);
|
||||
} catch (e) {
|
||||
@@ -162,7 +223,6 @@ async function startDownload() {
|
||||
} finally {
|
||||
_downloading = false;
|
||||
}
|
||||
logger.info(`开始下载壳子新版本 ${cloud}`);
|
||||
}
|
||||
|
||||
async function download(cloud, info) {
|
||||
@@ -224,7 +284,7 @@ async function download(cloud, info) {
|
||||
_STATE.dl_pct = 100;
|
||||
_STATE.dl_received = received;
|
||||
_STATE.dl_total = total;
|
||||
restorePending(cloud, String(info.notes || ""));
|
||||
restorePending(cloud, String(info.notes || ""), pkg);
|
||||
}
|
||||
|
||||
async function downloadFromUrl(url, headers, out, sha, onProgress) {
|
||||
@@ -256,10 +316,12 @@ function cleanupPart(cloud) {
|
||||
|
||||
function pendingStatus() {
|
||||
let cur = localShellVersion();
|
||||
let downloaded = !!_pendingVersion && cachedPkg(_pendingVersion) !== null;
|
||||
// 用已校验的 _pendingPkg 判断(不做全量 sha 重算——状态接口被前端高频轮询)
|
||||
const downloaded = !!_pendingVersion && !!_pendingPkg && fs.existsSync(_pendingPkg);
|
||||
if (!downloaded) {
|
||||
_pendingVersion = "";
|
||||
_pendingNotes = "";
|
||||
_pendingPkg = "";
|
||||
}
|
||||
return {
|
||||
current: cur,
|
||||
@@ -285,17 +347,28 @@ function pendingStatus() {
|
||||
|
||||
function applyUpdate() {
|
||||
const version = _pendingVersion;
|
||||
const pkg = cachedPkg(version);
|
||||
if (!pkg) throw new Error(`未找到已下载的安装包:setup-37du-host-${version}.exe`);
|
||||
const pkg = _pendingPkg || validateCache(version, "");
|
||||
if (!pkg || !fs.existsSync(pkg)) {
|
||||
throw new Error(`未找到已下载的安装包:${pkg || `setup-37du-host-${version}.exe`}`);
|
||||
}
|
||||
_STATE.applying = true;
|
||||
logger.info(`开始静默升级到 ${version}:${pkg}`);
|
||||
const child = spawn(pkg, ["/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"], {
|
||||
cwd: path.dirname(pkg),
|
||||
// electron-builder NSIS 静默安装完成后不会自动拉起新版本(旧壳 Inno [Run] 的行为不可用),
|
||||
// 用批处理串联"等待安装器完成 → 启动新版本";本进程 1s 后退出,让安装器接管收尾。
|
||||
const newExe = path.join(path.dirname(process.execPath), path.basename(process.execPath));
|
||||
const bat = path.join(SHELL_CACHE, `apply-update-${version}.cmd`);
|
||||
fs.writeFileSync(bat, [
|
||||
"@echo off",
|
||||
`start "" /wait "${pkg}" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART`,
|
||||
`start "" "${newExe}"`,
|
||||
"",
|
||||
].join("\r\n"), "utf-8");
|
||||
spawn("cmd.exe", ["/c", bat], {
|
||||
cwd: SHELL_CACHE,
|
||||
windowsHide: true,
|
||||
stdio: "ignore",
|
||||
detached: true,
|
||||
});
|
||||
child.unref();
|
||||
}).unref();
|
||||
// 给安装器接管进程,随后退出
|
||||
setTimeout(() => {
|
||||
if (typeof process.exit === "function") process.exit(0);
|
||||
@@ -308,6 +381,6 @@ module.exports = {
|
||||
startDownload,
|
||||
pendingStatus,
|
||||
applyUpdate,
|
||||
cachedPkg,
|
||||
cleanupStalePackages,
|
||||
localShellVersion,
|
||||
};
|
||||
|
||||
@@ -20,6 +20,18 @@ function setAllowed(v) {
|
||||
ALLOWED = v === undefined ? null : v;
|
||||
}
|
||||
|
||||
// 启动步骤状态(启动页/登录页展示"当前在干嘛";后台初始化失败/超时只记日志,不阻塞 UI)
|
||||
let BOOT = { step: "初始化中", detail: "", done: false, at: "" };
|
||||
function setBootStep(step, detail = "") {
|
||||
BOOT = { step, detail, done: false, at: new Date().toISOString() };
|
||||
}
|
||||
function setBootDone() {
|
||||
BOOT = { ...BOOT, done: true, at: new Date().toISOString() };
|
||||
}
|
||||
function bootStatus() {
|
||||
return { ...BOOT };
|
||||
}
|
||||
|
||||
function setRun(runId, fields) {
|
||||
const run = RUNS.get(runId);
|
||||
if (run) Object.assign(run, fields);
|
||||
@@ -52,4 +64,7 @@ module.exports = {
|
||||
setRun,
|
||||
registerRun,
|
||||
appendRunLog,
|
||||
setBootStep,
|
||||
setBootDone,
|
||||
bootStatus,
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ const path = require("path");
|
||||
const config = require("./config");
|
||||
const cp = require("./cpclient");
|
||||
const session = require("./session");
|
||||
const pluginConfigs = require("./plugin-configs");
|
||||
const { newId, nowStr, versionLt: _unused } = require("./crypto");
|
||||
const { HUB } = require("./hub");
|
||||
const { makeLogger } = require("./logger");
|
||||
@@ -201,7 +202,8 @@ function createSchedule(account, payload) {
|
||||
name: (payload.name || "").trim() || "定时任务",
|
||||
account,
|
||||
plugin_id: payload.plugin_id || "",
|
||||
fields: payload.fields || {},
|
||||
config_id: payload.config_id || "", // 引用插件界面维护的多配置方案;空 = 用插件保存的当前配置/默认值
|
||||
fields: payload.fields || {}, // 兼容旧数据(创建收口后统一走 config_id)
|
||||
cron,
|
||||
enabled: !!payload.enabled,
|
||||
last_run_at: "",
|
||||
@@ -222,6 +224,7 @@ function updateSchedule(sid, payload) {
|
||||
if (s.id !== sid) continue;
|
||||
if ("name" in payload) s.name = (payload.name || "").trim() || "定时任务";
|
||||
if ("plugin_id" in payload) s.plugin_id = payload.plugin_id;
|
||||
if ("config_id" in payload) s.config_id = payload.config_id || "";
|
||||
if ("fields" in payload) s.fields = payload.fields || {};
|
||||
if (payload.cron) s.cron = payload.cron.trim();
|
||||
if ("enabled" in payload) s.enabled = !!payload.enabled;
|
||||
@@ -372,7 +375,18 @@ async function fire(s) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const runId = runner.submitRun(account, plugin, s.fields || {}, {
|
||||
// 参数解析:引用了配置方案 → 到点取该方案最新 fields(方案在插件界面维护,更新自动跟随);
|
||||
// 未引用 → 空 fields 交给 runner 回退到插件保存的当前配置/插件默认值
|
||||
let fields = s.fields || {};
|
||||
if (s.config_id) {
|
||||
const cfg = pluginConfigs.getConfig(account, plugin.id, s.config_id);
|
||||
if (!cfg) {
|
||||
logger.warning(`定时任务「${s.name}」引用的配置方案已被删除,跳过本次触发(请在计划页重选配置)`);
|
||||
return false;
|
||||
}
|
||||
fields = cfg.fields;
|
||||
}
|
||||
const runId = runner.submitRun(account, plugin, fields, {
|
||||
trigger: "schedule",
|
||||
schedule_id: s.id,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user