feat: 新增多插件 UI 支持及运行日志集中回传功能
本次提交包含多项功能更新: 1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持 2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储 3. 新增插件分类字段支持,用于场景库分组管理 4. 优化 xq0034/0037/0048 等插件的功能及描述 5. 修复控制面响应兼容问题,支持新旧版本数据格式 6. 新增 xq0033 插件的状态存储模块,用于历史记录管理 7. 优化 CRM 登录窗口模式,支持全屏置顶
This commit is contained in:
@@ -163,6 +163,13 @@ async function init(options = {}) {
|
||||
} catch (e) {
|
||||
logger.warning(`通知推送启动失败:${e.message}`);
|
||||
}
|
||||
|
||||
// 日志集中回传:运行日志 + 壳日志上送中心机(启动即回传一次 + 15 分钟周期)
|
||||
try {
|
||||
require("./log-upload").start();
|
||||
} catch (e) {
|
||||
logger.warning(`日志集中回传启动失败:${e.message}`);
|
||||
}
|
||||
} else {
|
||||
logger.info("未配置中心机地址(CONTROLPLANE_URL),进入离线本地模式");
|
||||
state.setAllowed(new Set());
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
const { spawn, execFile } = require("child_process");
|
||||
const cp = require("./cpclient");
|
||||
const config = require("./config");
|
||||
@@ -14,8 +15,17 @@ const logger = makeLogger("chrome-manager");
|
||||
const CHROME_CACHE = path.join(config.APP_DATA, "chrome");
|
||||
let _pendingPkg = null;
|
||||
|
||||
// 启动清扫:上次异常退出遗留的 .part 半包(可能上百 MB);启动时无下载在跑,直接清
|
||||
try {
|
||||
for (const f of fs.readdirSync(CHROME_CACHE)) {
|
||||
if (f.endsWith(".part")) {
|
||||
try { fs.unlinkSync(path.join(CHROME_CACHE, f)); } catch (_) { /* 占用中忽略 */ }
|
||||
}
|
||||
}
|
||||
} catch (_) { /* 目录不存在等忽略 */ }
|
||||
|
||||
const _STATE = {
|
||||
installed: true,
|
||||
installed: false, // 未知态:首次 status() 会真实检测后覆盖
|
||||
version: "",
|
||||
checking: false,
|
||||
check_error: "",
|
||||
@@ -30,6 +40,42 @@ const _STATE = {
|
||||
|
||||
const VERSION_RE = /^\d+\.\d+\.\d+\.\d+$/;
|
||||
|
||||
// 异步流式算 sha256:安装包约 100MB,不能用 readFileSync 卡住主进程事件循环
|
||||
function sha256File(p) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const h = crypto.createHash("sha256");
|
||||
const s = fs.createReadStream(p);
|
||||
s.on("data", (c) => h.update(c));
|
||||
s.on("error", reject);
|
||||
s.on("end", () => resolve(h.digest("hex")));
|
||||
});
|
||||
}
|
||||
|
||||
// 复用磁盘上已下载完成的安装包(rename 只发生在 sha 校验通过后,因此 .exe 可信),
|
||||
// 避免壳子重启后 _pendingPkg 内存态丢失、用户被迫重新下载 ~100MB。
|
||||
function findCachedPkg() {
|
||||
try {
|
||||
const files = fs
|
||||
.readdirSync(CHROME_CACHE)
|
||||
.filter((f) => /\.exe$/i.test(f))
|
||||
.map((f) => {
|
||||
const p = path.join(CHROME_CACHE, f);
|
||||
try {
|
||||
const st = fs.statSync(p);
|
||||
return { p, mtime: st.mtimeMs, size: st.size };
|
||||
} catch (_) {
|
||||
return { p, mtime: 0, size: 0 };
|
||||
}
|
||||
})
|
||||
// 过小的文件视为下载残留,不参与复用
|
||||
.filter((x) => x.size > 10 * 1024 * 1024)
|
||||
.sort((a, b) => b.mtime - a.mtime);
|
||||
return files.length ? files[0].p : null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 系统位数:Chrome 安装包按位数分发(登记分类 chrome-x64 / chrome-x86)
|
||||
function detectArch() {
|
||||
const pa = (process.env.PROCESSOR_ARCHITECTURE || "").toLowerCase();
|
||||
@@ -134,6 +180,8 @@ async function status() {
|
||||
} else {
|
||||
_STATE.installed = false;
|
||||
_STATE.version = "";
|
||||
// 壳子重启后 _pendingPkg 内存态丢失:从磁盘找回已下载完成的安装包,避免重复下载
|
||||
if (!_pendingPkg || !fs.existsSync(_pendingPkg)) _pendingPkg = findCachedPkg();
|
||||
}
|
||||
const pkgOk = !!_pendingPkg && fs.existsSync(_pendingPkg);
|
||||
return {
|
||||
@@ -157,6 +205,7 @@ async function status() {
|
||||
|
||||
async function refresh() {
|
||||
_STATE.checking = true;
|
||||
_STATE.check_error = ""; // 手动「重新检测」清掉上一次的安装超时/失败提示
|
||||
try {
|
||||
await detectLocal();
|
||||
await cloudInfo();
|
||||
@@ -173,7 +222,12 @@ async function startDownload() {
|
||||
if (_STATE.dl_status === "downloading") return;
|
||||
if (_STATE.dl_status === "downloaded" && _pendingPkg && fs.existsSync(_pendingPkg)) return;
|
||||
const info = await cloudInfo();
|
||||
if (!info || !info.url) return;
|
||||
if (!info || !info.url) {
|
||||
// 前端点击时已乐观进入"下载中",这里必须落到失败态,否则弹窗停在 0% 无任何提示
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = "中心机未登记浏览器安装包(chrome-x64 / chrome-x86 / chrome)";
|
||||
return;
|
||||
}
|
||||
const url = String(info.url).trim();
|
||||
const expect = String(info.sha256 || "").toLowerCase();
|
||||
const filename = String(info.filename || (ARCH === "x86" ? "ChromeStandaloneSetup.exe" : "ChromeStandaloneSetup64.exe")).trim();
|
||||
@@ -185,45 +239,66 @@ async function startDownload() {
|
||||
_STATE.dl_pct = 0;
|
||||
_STATE.dl_error = "";
|
||||
try {
|
||||
logger.info(`开始下载 Chrome 安装包:${url}`);
|
||||
await download(url, expect, filename);
|
||||
} catch (e) {
|
||||
logger.warning(`下载 Chrome 安装包失败:${e.message}`);
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = `安装包下载失败(${e.constructor.name})`;
|
||||
_STATE.dl_error = `安装包下载失败:${(e && e.message) || e.constructor.name}`;
|
||||
cleanupPart();
|
||||
} finally {
|
||||
_downloading = false;
|
||||
}
|
||||
logger.info(`开始下载 Chrome 安装包:${url}`);
|
||||
}
|
||||
|
||||
async function download(url, expect, filename) {
|
||||
const crypto = require("crypto");
|
||||
const sha = crypto.createHash("sha256");
|
||||
const tmp = path.join(CHROME_CACHE, `${filename}.part`);
|
||||
const pkg = path.join(CHROME_CACHE, filename);
|
||||
fs.mkdirSync(CHROME_CACHE, { recursive: true });
|
||||
// 同名安装包已在磁盘:sha 一致直接复用,省掉一次 ~100MB 下载(重启/重试场景)
|
||||
if (fs.existsSync(pkg)) {
|
||||
let reusable = !expect;
|
||||
if (expect) {
|
||||
try { reusable = (await sha256File(pkg)) === expect; } catch (_) { reusable = false; }
|
||||
}
|
||||
if (reusable) {
|
||||
_pendingPkg = pkg;
|
||||
_STATE.dl_status = "downloaded";
|
||||
_STATE.dl_pct = 100;
|
||||
try { _STATE.dl_received = _STATE.dl_total = fs.statSync(pkg).size; } catch (_) {}
|
||||
logger.info(`复用已下载的 Chrome 安装包:${pkg}`);
|
||||
return;
|
||||
}
|
||||
try { fs.unlinkSync(pkg); } catch (_) { /* 占用中则继续覆盖写 */ }
|
||||
}
|
||||
const out = fs.createWriteStream(tmp);
|
||||
let received = 0;
|
||||
let total = 0;
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 600 * 1000);
|
||||
const res = await fetch(url, { signal: ctrl.signal, redirect: "follow" });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
total = parseInt(res.headers.get("content-length") || "0", 10);
|
||||
const reader = res.body.getReader();
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
out.write(value);
|
||||
sha.update(value);
|
||||
received += value.length;
|
||||
_STATE.dl_received = received;
|
||||
_STATE.dl_total = total;
|
||||
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
|
||||
try {
|
||||
const res = await fetch(url, { signal: ctrl.signal, redirect: "follow" });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
total = parseInt(res.headers.get("content-length") || "0", 10);
|
||||
const reader = res.body.getReader();
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
out.write(value);
|
||||
sha.update(value);
|
||||
received += value.length;
|
||||
_STATE.dl_received = received;
|
||||
_STATE.dl_total = total;
|
||||
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
|
||||
}
|
||||
await new Promise((res2, rej2) => out.end((e) => (e ? rej2(e) : res2())));
|
||||
} catch (e) {
|
||||
out.destroy(); // 释放文件句柄,否则 Windows 上 cleanupPart 删不掉 .part
|
||||
throw e;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
clearTimeout(timer);
|
||||
await new Promise((res2, rej2) => out.end((e) => (e ? rej2(e) : res2())));
|
||||
const digest = sha.digest("hex");
|
||||
if (expect && digest !== expect) {
|
||||
logger.error("Chrome 安装包 sha256 校验失败");
|
||||
@@ -263,6 +338,7 @@ function install() {
|
||||
throw Object.assign(new Error("未找到已下载的 Chrome 安装包"), { status: 404 });
|
||||
}
|
||||
_STATE.installing = true;
|
||||
_STATE.check_error = ""; // 重新打开安装器,清掉上一次的失败/超时提示
|
||||
logger.info(`启动 Chrome 安装器(弹出窗口由用户完成安装):${_pendingPkg}`);
|
||||
// 直接弹出官方安装器窗口、由用户点击完成安装(不下发静默参数):
|
||||
// 新版 Chrome 安装器会静默忽略未知参数(旧版 /silent /install 组合),
|
||||
@@ -275,6 +351,7 @@ function install() {
|
||||
});
|
||||
child.on("error", (e) => {
|
||||
_STATE.installing = false;
|
||||
_STATE.check_error = `启动 Chrome 安装器失败:${e.message}`;
|
||||
logger.warning(`启动 Chrome 安装器失败:${e.message}`);
|
||||
});
|
||||
child.unref();
|
||||
@@ -285,18 +362,24 @@ function install() {
|
||||
async function pollInstall() {
|
||||
for (let i = 0; i < 120; i++) { // 交互式安装由用户人工操作,时限放宽到 10 分钟
|
||||
await new Promise((r) => setTimeout(r, 5000));
|
||||
const local = await detectLocal();
|
||||
// force:本地检测有 30s 缓存,这里必须绕开,否则用户装完后界面最多晚 30s 才变"已安装"
|
||||
const local = await detectLocal(true);
|
||||
if (local.installed) {
|
||||
_STATE.installing = false;
|
||||
_STATE.installed = true;
|
||||
_STATE.version = local.version;
|
||||
_STATE.check_error = "";
|
||||
_STATE.dl_status = "idle"; // 已安装,安装包不再参与状态,避免重复安装
|
||||
// 装完即清理本地安装包(~100MB):安装器可能仍占用文件,失败则下次启动/下载时再清
|
||||
if (_pendingPkg) { try { fs.unlinkSync(_pendingPkg); } catch (_) { /* 占用中忽略 */ } }
|
||||
_pendingPkg = null; // 释放安装包句柄,后续点击走「重新检测」而非再装
|
||||
logger.info(`Chrome 安装完成:${_STATE.version}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
_STATE.installing = false;
|
||||
// 超时不是静默失败:把原因透出到状态里,前端提示用户重新打开安装器或手动检测
|
||||
_STATE.check_error = "等待 Chrome 安装完成超时(未检测到安装结果),请完成安装器操作后点击重新检测";
|
||||
logger.warning("等待 Chrome 安装完成超时(可能用户未完成安装器窗口操作)");
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const { app, BrowserWindow, Tray, Menu, nativeImage, dialog, screen } = require("electron");
|
||||
const { app, BrowserWindow, Tray, Menu, nativeImage, dialog, screen, ipcMain } = require("electron");
|
||||
const path = require("path");
|
||||
const config = require("./config");
|
||||
const { makeLogger } = require("./logger");
|
||||
const trayMenu = require("./tray-menu");
|
||||
|
||||
const logger = makeLogger("electron-main");
|
||||
|
||||
@@ -82,8 +83,10 @@ if (!app.requestSingleInstanceLock()) {
|
||||
y: st.y,
|
||||
minWidth: 1000,
|
||||
minHeight: 660,
|
||||
// 与启动页默认皮肤底色一致(style.css --bg #F9F7F2),避免冷启动色跳
|
||||
backgroundColor: "#F9F7F2",
|
||||
// 无边框窗口:顶栏由渲染层自绘(含窗口控制钮 / 面包屑 / 服务状态)
|
||||
frame: false,
|
||||
// 与启动页画布底色一致(style.css --canvas #F2F4F8),避免冷启动色跳
|
||||
backgroundColor: "#F2F4F8",
|
||||
title: "37du 自动化工作台",
|
||||
icon: trayIconImage(),
|
||||
webPreferences: {
|
||||
@@ -94,6 +97,14 @@ if (!app.requestSingleInstanceLock()) {
|
||||
},
|
||||
});
|
||||
mainWindow.loadURL(URL);
|
||||
// 推送最大化状态变化:渲染层顶栏切换最大化/还原图标
|
||||
const sendMaxState = () => {
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.webContents.send("win:maximized", mainWindow.isMaximized());
|
||||
}
|
||||
};
|
||||
mainWindow.on("maximize", sendMaxState);
|
||||
mainWindow.on("unmaximize", sendMaxState);
|
||||
// 关闭时保存窗口状态;resize/move 防抖保存(异常退出也不丢太多)
|
||||
let stateTimer = null;
|
||||
const save = () => {
|
||||
@@ -119,6 +130,16 @@ if (!app.requestSingleInstanceLock()) {
|
||||
});
|
||||
}
|
||||
|
||||
// 无边框窗口控制 IPC:渲染层自绘顶栏的窗口控制钮走这里(fire-and-forget)
|
||||
ipcMain.on("win:min", () => { if (mainWindow && !mainWindow.isDestroyed()) mainWindow.minimize(); });
|
||||
ipcMain.on("win:max", () => {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) return;
|
||||
if (mainWindow.isMaximized()) mainWindow.unmaximize();
|
||||
else mainWindow.maximize();
|
||||
});
|
||||
// 关闭 = 走 close 拦截逻辑(默认收托盘,托盘「退出」才真正退出)
|
||||
ipcMain.on("win:close", () => { if (mainWindow && !mainWindow.isDestroyed()) mainWindow.close(); });
|
||||
|
||||
function trayIconImage() {
|
||||
// 优先用官方图标(Windows 托盘/窗口均正常渲染);缺失时 SVG 兜底。
|
||||
// 打包态:resources/assets/icon.ico(extraResources 真实文件);开发态:本模块 assets/
|
||||
@@ -134,35 +155,21 @@ if (!app.requestSingleInstanceLock()) {
|
||||
return nativeImage.createFromDataURL(`data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`);
|
||||
}
|
||||
|
||||
function openWorkbench() {
|
||||
// 关闭窗口只是收托盘(窗口仍存在),此处复用已有窗口而非重复新建
|
||||
if (!mainWindow) createWindow();
|
||||
else { mainWindow.show(); mainWindow.focus(); }
|
||||
}
|
||||
|
||||
function createTray() {
|
||||
tray = new Tray(trayIconImage());
|
||||
const ctx = Menu.buildFromTemplate([
|
||||
{
|
||||
label: "打开工作台",
|
||||
click: () => {
|
||||
// 关闭窗口只是收托盘(窗口仍存在),此处复用已有窗口而非重复新建
|
||||
if (!mainWindow) createWindow();
|
||||
else { mainWindow.show(); mainWindow.focus(); }
|
||||
},
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "开机自启",
|
||||
type: "checkbox",
|
||||
checked: app.getLoginItemSettings().openAtLogin,
|
||||
click: (item) => {
|
||||
app.setLoginItemSettings({ openAtLogin: item.checked });
|
||||
},
|
||||
},
|
||||
{ type: "separator" },
|
||||
{ label: "退出", click: () => app.quit() },
|
||||
]);
|
||||
tray.setToolTip("37du 自动化工作台");
|
||||
tray.setContextMenu(ctx);
|
||||
tray.on("click", () => {
|
||||
if (!mainWindow) createWindow();
|
||||
else mainWindow.show();
|
||||
// 右键菜单用自绘卡片弹窗(系统原生菜单样式跟随系统、无法统一视觉)
|
||||
trayMenu.attach(tray, {
|
||||
onOpen: openWorkbench,
|
||||
onQuit: () => app.quit(),
|
||||
});
|
||||
tray.on("click", openWorkbench);
|
||||
}
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
// 日志集中回传:运行日志(整次,幂等 upsert)+ 壳日志(shell.log 增量字节)+ 离线暂存补报。
|
||||
// 目的:执行机运行/壳日志自动上送中心机,管理端「运行日志」页集中排查,无需再去各电脑翻日志。
|
||||
// 与 licensing.offline_reports 互补:本模块只管"日志正文",状态/结论仍走 runtime/report。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const os = require("os");
|
||||
const path = require("path");
|
||||
const config = require("./config");
|
||||
const cp = require("./cpclient");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("log-upload");
|
||||
|
||||
const LOGS_DIR = path.join(config.APP_DATA, "logs");
|
||||
const SHELL_LOG_FILE = path.join(LOGS_DIR, "shell.log");
|
||||
const PENDING_FILE = path.join(config.APP_DATA, "pending_log_uploads.jsonl");
|
||||
const UPLOAD_STATE_FILE = path.join(LOGS_DIR, "upload_state.json");
|
||||
|
||||
const UPLOAD_INTERVAL_MS = 15 * 60 * 1000; // 周期回传:15 分钟
|
||||
const BACKFILL_MAX = 50; // 启动补报最近 N 次运行(服务端按 run_id 幂等)
|
||||
const BACKFILL_DAYS = 7; // 只补报最近 7 天内的运行(更早的线上早已回传过)
|
||||
const MAX_PENDING = 500; // 离线暂存条数上限(超出丢弃最旧)
|
||||
|
||||
let _started = false;
|
||||
|
||||
// ==================== 本地状态文件(读/写/行) ====================
|
||||
function readLines(file) {
|
||||
if (!file || !fs.existsSync(file)) return [];
|
||||
let text;
|
||||
try {
|
||||
text = fs.readFileSync(file, "utf-8");
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
const out = [];
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const s = line.trim();
|
||||
if (!s) continue;
|
||||
try {
|
||||
out.push(JSON.parse(s));
|
||||
} catch (e) {
|
||||
/* 跳过损坏行 */
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function writeLines(file, records) {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const tmp = file + ".tmp";
|
||||
const body = records.length ? records.map((r) => JSON.stringify(r)).join("\n") + "\n" : "";
|
||||
fs.writeFileSync(tmp, body, "utf-8");
|
||||
fs.renameSync(tmp, file);
|
||||
} catch (e) {
|
||||
/* 写入失败忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
function readUploadState() {
|
||||
try {
|
||||
const v = JSON.parse(fs.readFileSync(UPLOAD_STATE_FILE, "utf-8"));
|
||||
return v && typeof v === "object" ? v : {};
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeUploadState(state) {
|
||||
try {
|
||||
fs.mkdirSync(LOGS_DIR, { recursive: true });
|
||||
fs.writeFileSync(UPLOAD_STATE_FILE, JSON.stringify(state), "utf-8");
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
// 设备 ID:与 app.deviceId() 同源(持久化 %LOCALAPPDATA%\37duAutomation\device_id)。
|
||||
// 不直接 require("./app")(避免拖入整个应用依赖树),本模块内自包含。
|
||||
function deviceId() {
|
||||
const f = path.join(config.APP_DATA, "device_id");
|
||||
try {
|
||||
if (fs.existsSync(f)) {
|
||||
const v = fs.readFileSync(f, "utf-8").trim();
|
||||
if (v) return v;
|
||||
}
|
||||
const crypto = require("crypto");
|
||||
const id = crypto.randomUUID();
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
fs.writeFileSync(f, id, "utf-8");
|
||||
return id;
|
||||
} catch (e) {
|
||||
return "dev-" + require("crypto").randomBytes(8).toString("hex");
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 运行日志(整次回传,幂等 upsert) ====================
|
||||
// rec: 见 runner.finishRun 的 runHistory 记录(含 logs 数组)
|
||||
async function uploadRun(rec) {
|
||||
if (!config.CONTROLPLANE_URL) return false;
|
||||
if (!rec || !rec.run_id) return false;
|
||||
const payload = { ...rec, device_id: deviceId() };
|
||||
try {
|
||||
await cp.request("POST", "/api/runtime/logs", {
|
||||
headers: cp.machineHeaders(), json: payload, timeout: 15,
|
||||
});
|
||||
return true;
|
||||
} catch (e) {
|
||||
queuePending(payload);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 离线暂存:写入 JSONL(上限 MAX_PENDING,超出丢最旧)
|
||||
function queuePending(payload) {
|
||||
try {
|
||||
const pending = readLines(PENDING_FILE);
|
||||
pending.push(payload);
|
||||
writeLines(PENDING_FILE, pending.slice(-MAX_PENDING));
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
// 重连后补报此前暂存的运行日志;返回成功条数
|
||||
async function flushPending() {
|
||||
if (!config.CONTROLPLANE_URL) return 0;
|
||||
if (!fs.existsSync(PENDING_FILE)) return 0;
|
||||
const pending = readLines(PENDING_FILE);
|
||||
if (!pending.length) return 0;
|
||||
const kept = [];
|
||||
let sent = 0;
|
||||
for (const rec of pending) {
|
||||
try {
|
||||
await cp.request("POST", "/api/runtime/logs", {
|
||||
headers: cp.machineHeaders(), json: { ...rec, device_id: rec.device_id || deviceId() },
|
||||
timeout: 15,
|
||||
});
|
||||
sent++;
|
||||
} catch (e) {
|
||||
kept.push(rec); // 仍失败:保留待下轮
|
||||
}
|
||||
}
|
||||
writeLines(PENDING_FILE, kept);
|
||||
if (sent) logger.info(`运行日志离线补报完成:${sent} 条`);
|
||||
return sent;
|
||||
}
|
||||
|
||||
// ==================== 壳日志(shell.log 增量字节上传) ====================
|
||||
// 以字节偏移为游标:只传上次之后的增量;日志轮转(size < offset)时 reset=1 让服务端截断重传。
|
||||
async function uploadShellLog() {
|
||||
if (!config.CONTROLPLANE_URL) return;
|
||||
if (!fs.existsSync(SHELL_LOG_FILE)) return;
|
||||
let size;
|
||||
try {
|
||||
size = fs.statSync(SHELL_LOG_FILE).size;
|
||||
} catch (e) {
|
||||
return;
|
||||
}
|
||||
const state = readUploadState();
|
||||
const shell = (state.shell && typeof state.shell === "object") ? state.shell : {};
|
||||
let offset = typeof shell.offset === "number" && shell.offset > 0 ? shell.offset : 0;
|
||||
if (size < offset) offset = 0; // 文件已轮转/截断:重置,整文件重传(服务端先截断)
|
||||
if (size <= offset) return; // 无新增字节
|
||||
let buf;
|
||||
try {
|
||||
const fd = fs.openSync(SHELL_LOG_FILE, "r");
|
||||
buf = Buffer.alloc(size - offset);
|
||||
fs.readSync(fd, buf, 0, buf.length, offset);
|
||||
fs.closeSync(fd);
|
||||
} catch (e) {
|
||||
return;
|
||||
}
|
||||
if (!buf || !buf.length) return;
|
||||
try {
|
||||
await cp.request("POST", "/api/runtime/shell-log", {
|
||||
// 显式声明 octet-stream:避免中间件把原始字节按 form-urlencoded 消费(新旧服务端均接受)
|
||||
headers: { ...cp.machineHeaders(), "Content-Type": "application/octet-stream" },
|
||||
params: {
|
||||
device_id: deviceId(),
|
||||
account: config.CONTROLPLANE_ACCOUNT || "",
|
||||
hostname: os.hostname() || "",
|
||||
client_version: (config.runtimeVersion && config.runtimeVersion()) || "",
|
||||
reset: offset === 0 ? 1 : 0,
|
||||
},
|
||||
body: buf,
|
||||
timeout: 60,
|
||||
});
|
||||
state.shell = { offset: size, at: Date.now() };
|
||||
writeUploadState(state);
|
||||
} catch (e) {
|
||||
logger.warning(`壳日志回传失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 启动补报:最近运行历史里尚未回传的整次日志 ====================
|
||||
const SAFE_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
||||
|
||||
function readRunLogs(runId) {
|
||||
const id = String(runId || "");
|
||||
if (!SAFE_ID.test(id)) return [];
|
||||
try {
|
||||
const runHistory = require("./run-history");
|
||||
return readLines(path.join(runHistory.RUNS_DIR, `${id}.jsonl`));
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function recentRuns(max) {
|
||||
try {
|
||||
const runHistory = require("./run-history");
|
||||
return readLines(runHistory.HISTORY_PATH)
|
||||
.filter((r) => r && typeof r === "object" && r.run_id)
|
||||
.slice(-Math.max(1, Math.min(max, 200)))
|
||||
.reverse(); // 新的在前
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// 补报最近 BACKFILL_DAYS 天内的运行日志(服务端 run_id 幂等,重复回传安全)
|
||||
async function backfillRecentRuns() {
|
||||
if (!config.CONTROLPLANE_URL) return;
|
||||
let ok = 0;
|
||||
for (const rec of recentRuns(BACKFILL_MAX)) {
|
||||
const finished = Number(rec.finished || 0);
|
||||
if (finished && Date.now() / 1000 - finished > BACKFILL_DAYS * 86400) continue;
|
||||
const payload = {
|
||||
run_id: rec.run_id,
|
||||
account: rec.account || "",
|
||||
plugin_id: rec.plugin_id || "",
|
||||
name: rec.name || "",
|
||||
version: rec.version || "",
|
||||
trigger: rec.trigger || "manual",
|
||||
schedule_id: rec.schedule_id || "",
|
||||
status: rec.status || "",
|
||||
ok: !!rec.ok,
|
||||
error: rec.error || "",
|
||||
summary: rec.summary || "",
|
||||
started: rec.started || 0,
|
||||
finished: rec.finished || 0,
|
||||
duration_sec: rec.duration_sec || 0,
|
||||
logs: readRunLogs(rec.run_id),
|
||||
};
|
||||
if (!(await uploadRun(payload))) break; // 不可达:本批中断,待下轮周期重试
|
||||
ok++;
|
||||
}
|
||||
if (ok) logger.info(`运行日志启动补报完成:${ok} 次`);
|
||||
}
|
||||
|
||||
// ==================== 启动 ====================
|
||||
function start() {
|
||||
if (_started || !config.CONTROLPLANE_URL) return;
|
||||
_started = true;
|
||||
const cycle = async () => {
|
||||
try { await flushPending(); } catch (e) { /* 忽略 */ }
|
||||
try { await uploadShellLog(); } catch (e) { /* 忽略 */ }
|
||||
try { await backfillRecentRuns(); } catch (e) { /* 忽略 */ }
|
||||
};
|
||||
void cycle(); // 启动即回传一次
|
||||
setInterval(() => { void cycle(); }, UPLOAD_INTERVAL_MS);
|
||||
logger.info(`日志集中回传已启动(运行日志 + 壳日志,每 ${UPLOAD_INTERVAL_MS / 60000} 分钟一次)`);
|
||||
}
|
||||
|
||||
module.exports = { start, uploadRun, flushPending, uploadShellLog, backfillRecentRuns };
|
||||
@@ -28,6 +28,26 @@ async function accountAllowedPlatforms(account) {
|
||||
}
|
||||
}
|
||||
|
||||
// 调中心机获取后台维护的场景分类;控制面不可达返回 null(调用方回退本地 plugin.json)
|
||||
async function accountPluginCategories(account) {
|
||||
if (!config.CONTROLPLANE_URL) return null;
|
||||
try {
|
||||
const r = await cp.request("GET", "/api/plugins", {
|
||||
headers: cp.machineHeaders(),
|
||||
params: { account },
|
||||
timeout: 5,
|
||||
});
|
||||
const map = new Map();
|
||||
for (const p of r.plugins || []) {
|
||||
const cat = String(p.category || "").trim();
|
||||
if (cat) map.set(p.id, cat);
|
||||
}
|
||||
return map;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// /api/meta 聚合响应
|
||||
async function buildMeta(account) {
|
||||
let authExpired = false;
|
||||
@@ -43,16 +63,29 @@ async function buildMeta(account) {
|
||||
authExpired = true;
|
||||
}
|
||||
}
|
||||
const allowedPlats = account ? await accountAllowedPlatforms(account) : null;
|
||||
const platforms = [];
|
||||
for (const [pid, m] of Object.entries(state.PLATFORMS)) {
|
||||
platforms.push({
|
||||
id: pid,
|
||||
label: m.label,
|
||||
online: await platformAuth.isOnline(pid, account), // 按当前账号的会话校验
|
||||
allowed: allowedPlats === null ? true : allowedPlats.has(pid),
|
||||
const [cloudCats, allowedPlats] = account
|
||||
? await Promise.all([
|
||||
plugins.length ? accountPluginCategories(account) : Promise.resolve(null),
|
||||
accountAllowedPlatforms(account),
|
||||
])
|
||||
: [null, null];
|
||||
// 后台分类优先,未配置则保留插件包内 plugin.json 的分类
|
||||
if (cloudCats) {
|
||||
plugins = plugins.map((p) => {
|
||||
const cat = cloudCats.get(p.id);
|
||||
return cat ? { ...p, category: cat } : p;
|
||||
});
|
||||
}
|
||||
// 平台在线态:并行 + 单平台 2.5s 兜底,避免外网校验慢时整屏元数据被拖住
|
||||
// (超时先按未登录展示,后台校验完成后会回填缓存,平台账号页再读即为最新)
|
||||
const platforms = await Promise.all(
|
||||
Object.entries(state.PLATFORMS).map(async ([pid, m]) => ({
|
||||
id: pid,
|
||||
label: m.label,
|
||||
online: await platformAuth.isOnlineQuick(pid, account), // 按当前账号的会话校验
|
||||
allowed: allowedPlats === null ? true : allowedPlats.has(pid),
|
||||
}))
|
||||
);
|
||||
return {
|
||||
appName: "37du 自动化工作台",
|
||||
dingtalkScan: !!config.CONTROLPLANE_URL,
|
||||
|
||||
@@ -31,7 +31,9 @@ function platforms() {
|
||||
|
||||
// 账号隔离的会话目录;无账号时回退共享目录(兼容旧数据)
|
||||
function sessionDir(account) {
|
||||
const base = account ? path.join(BASE_SESSIONS_DIR, String(account)) : BASE_SESSIONS_DIR;
|
||||
// 与 Python 侧(hr_login_api 对 PLATFORM_ACCOUNT 做 strip)对齐,避免首尾空白导致目录错位
|
||||
const acc = String(account || "").trim();
|
||||
const base = acc ? path.join(BASE_SESSIONS_DIR, acc) : BASE_SESSIONS_DIR;
|
||||
try {
|
||||
fs.mkdirSync(base, { recursive: true });
|
||||
} catch (e) {
|
||||
@@ -158,7 +160,8 @@ async function isOnline(pid, account) {
|
||||
}
|
||||
}
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 8000);
|
||||
// 与 Python 侧校验超时(15s)对齐:登录刚完成时平台响应可能偏慢,过短易误判失效
|
||||
const timer = setTimeout(() => ctrl.abort(), 15000);
|
||||
const resp = await fetch(def.url, {
|
||||
method: def.method,
|
||||
headers: {
|
||||
@@ -168,11 +171,12 @@ async function isOnline(pid, account) {
|
||||
},
|
||||
body: def.method === "POST" ? "" : undefined,
|
||||
signal: ctrl.signal,
|
||||
redirect: "manual",
|
||||
// 与 Python requests 默认一致:跟随重定向后再判定;manual 会把 302 直接误判为失效
|
||||
redirect: "follow",
|
||||
});
|
||||
clearTimeout(timer);
|
||||
const text = await resp.text();
|
||||
value = resp.status === 200 && text.trim().startsWith("{") || text.trim().startsWith("[");
|
||||
const text = (await resp.text()).trim();
|
||||
value = resp.status === 200 && (text.startsWith("{") || text.startsWith("["));
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warning(`平台 ${pid} 在线校验失败:${e.message}`);
|
||||
@@ -204,7 +208,20 @@ async function login(pid, account) {
|
||||
const out = await runPython(snippet, 5 * 60 * 1000, extraEnv);
|
||||
const result = extractJson(out) || {};
|
||||
const ok = !!result.success;
|
||||
const online = ok ? await isOnline(pid, account) : false;
|
||||
let online = ok ? await isOnline(pid, account) : false;
|
||||
if (ok && !online) {
|
||||
// Python 侧返回成功前已用落盘 cookies 完成真实会话校验;Node 复核偶发失败
|
||||
// (网络抖动/响应慢)时清缓存重试一次,避免误杀已成功的登录。
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
_onlineCache.delete(cacheKey);
|
||||
online = await isOnline(pid, account);
|
||||
}
|
||||
if (ok && !online) {
|
||||
// 仍复核失败:以 Python 侧真实登录 + 会话校验结果为准放行(其校验口径与插件一致),
|
||||
// Node 手拼 Cookie 头的复核口径存在差异,不作为最终裁决。
|
||||
logger.warning(`平台 ${pid} Node 复核未通过,但 Python 侧已登录并校验成功,按登录成功处理(账号 ${account})`);
|
||||
online = true;
|
||||
}
|
||||
return {
|
||||
id: pid,
|
||||
label: LABELS[pid],
|
||||
@@ -230,21 +247,38 @@ function logout(pid, account) {
|
||||
return { id: pid, label: LABELS[pid], online: false };
|
||||
}
|
||||
|
||||
// 当前账号的平台状态(个人中心展示):在线态 + 是否已配置个人账号密码 + 已存用户名
|
||||
async function status(account) {
|
||||
const creds = platformCreds.get(account) || {};
|
||||
const out = [];
|
||||
for (const pid of Object.keys(LABELS)) {
|
||||
const c = creds[pid] || {};
|
||||
out.push({
|
||||
id: pid,
|
||||
label: LABELS[pid],
|
||||
online: await isOnline(pid, account),
|
||||
has_creds: !!(c.user && c.pass),
|
||||
user: c.user || "",
|
||||
});
|
||||
}
|
||||
return out;
|
||||
// 带超时的在线校验:超时先按未登录返回,校验仍在后台继续跑并回填缓存,
|
||||
// 用于 meta 这类"不能为一次外网校验卡住整屏"的场景。
|
||||
function isOnlineQuick(pid, account, timeoutMs = 2500) {
|
||||
const task = isOnline(pid, account).catch(() => false);
|
||||
return Promise.race([task, new Promise((r) => setTimeout(() => r(false), timeoutMs))]);
|
||||
}
|
||||
|
||||
module.exports = { platforms, sessionDir, isOnline, login, logout, status, BASE_SESSIONS_DIR };
|
||||
// 当前账号的平台状态(个人中心展示):在线态 + 是否已配置个人账号密码 + 已存用户名
|
||||
// 两平台并行校验:串行时最坏 15s×2,并行后总耗时 ≈ 单平台最坏值。
|
||||
async function status(account) {
|
||||
const creds = platformCreds.get(account) || {};
|
||||
return Promise.all(
|
||||
Object.keys(LABELS).map(async (pid) => {
|
||||
const c = creds[pid] || {};
|
||||
return {
|
||||
id: pid,
|
||||
label: LABELS[pid],
|
||||
online: await isOnline(pid, account),
|
||||
has_creds: !!(c.user && c.pass),
|
||||
user: c.user || "",
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
platforms,
|
||||
sessionDir,
|
||||
isOnline,
|
||||
isOnlineQuick,
|
||||
login,
|
||||
logout,
|
||||
status,
|
||||
BASE_SESSIONS_DIR,
|
||||
};
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// preload:contextBridge 白名单 IPC(渲染层主通道走 HTTP 兼容层,此处仅暴露只读环境信息)。
|
||||
// preload:contextBridge 白名单 IPC(渲染层主通道走 HTTP 兼容层)。
|
||||
// 暴露只读环境信息 + 无边框窗口控制(顶栏自绘窗口控制钮使用)。
|
||||
"use strict";
|
||||
|
||||
const { contextBridge } = require("electron");
|
||||
const { contextBridge, ipcRenderer } = require("electron");
|
||||
|
||||
contextBridge.exposeInMainWorld("dshShell", {
|
||||
platform: process.platform,
|
||||
@@ -10,5 +11,17 @@ contextBridge.exposeInMainWorld("dshShell", {
|
||||
node: process.versions.node,
|
||||
chrome: process.versions.chrome,
|
||||
},
|
||||
// ---- 无边框窗口控制(顶栏 min/max/close) ----
|
||||
winControl: {
|
||||
minimize: () => ipcRenderer.send("win:min"),
|
||||
toggleMaximize: () => ipcRenderer.send("win:max"),
|
||||
close: () => ipcRenderer.send("win:close"),
|
||||
// 订阅最大化状态变化(主进程 maximize/unmaximize 时推送 boolean)
|
||||
onMaximized: (cb) => {
|
||||
const handler = (_e, v) => cb(v);
|
||||
ipcRenderer.on("win:maximized", handler);
|
||||
return () => ipcRenderer.removeListener("win:maximized", handler);
|
||||
},
|
||||
},
|
||||
// 渲染层可通过 window.open 打开中心机控制面(外部 URL 需在渲染层显式触发)
|
||||
});
|
||||
|
||||
@@ -100,6 +100,7 @@ function pluginSchema(pluginId) {
|
||||
name: manifest.name || pluginId,
|
||||
version: manifest.version || "0",
|
||||
description: manifest.description || "",
|
||||
category: manifest.category || "", // 场景分类(左侧场景库按此分组折叠,空则归"其他")
|
||||
uses_month: !!manifest.uses_month,
|
||||
ui: !!manifest.ui,
|
||||
platform: manifest.platform || "", // hr / oa / ""(前端平台徽章 + 运行并发闸按(账号,平台)隔离)
|
||||
|
||||
@@ -139,6 +139,28 @@ function finishRun(runId, plugin, status, error, summary) {
|
||||
duration_sec: durationSec,
|
||||
logs: Array.isArray(run.logs) ? run.logs : [],
|
||||
});
|
||||
// 日志集中回传:整次运行日志上送中心机(离线自动暂存补报;失败不阻断运行收尾)
|
||||
try {
|
||||
require("./log-upload").uploadRun({
|
||||
run_id: runId,
|
||||
account: run.account || "",
|
||||
plugin_id: plugin.id,
|
||||
name: run.name || plugin.name || plugin.id,
|
||||
version: run.version || plugin.version || "0",
|
||||
trigger: run.trigger || "manual",
|
||||
schedule_id: run.schedule_id || "",
|
||||
status,
|
||||
ok,
|
||||
error: ok ? "" : error || "",
|
||||
summary: summary || "",
|
||||
started: run.started || 0,
|
||||
finished,
|
||||
duration_sec: durationSec,
|
||||
logs: Array.isArray(run.logs) ? run.logs : [],
|
||||
});
|
||||
} catch (e) {
|
||||
logger.warning(`运行日志回传失败:${e.message}`);
|
||||
}
|
||||
HUB.publish({
|
||||
t: "run_done",
|
||||
run_id: runId,
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
const { spawn } = require("child_process");
|
||||
const cp = require("./cpclient");
|
||||
const config = require("./config");
|
||||
const { versionLt, sha256Hex } = require("./crypto");
|
||||
const { versionLt } = require("./crypto");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("shell-updater");
|
||||
@@ -15,6 +16,150 @@ const logger = makeLogger("shell-updater");
|
||||
const SHELL_CACHE = path.join(config.APP_DATA, "shell");
|
||||
const PERIODIC_INTERVAL = 30 * 60 * 1000;
|
||||
|
||||
// 升级等待窗口:独立 HTA(mshta.exe)进程。
|
||||
// 壳子自身进程必须退出才能被 NSIS 替换文件,所以这段时间 Electron 窗口必然消失;
|
||||
// 由该窗口接管界面:跑马灯进度 + 状态文案 + 「打开客户端」按钮,
|
||||
// 检测到旧进程退出后新进程出现即自动关闭。
|
||||
// 用 HTA 而不是 PowerShell WinForms:Electron 以 windowsHide(CREATE_NO_WINDOW + SW_HIDE
|
||||
// 启动信息)拉起 powershell.exe 时,WinForms 首窗口会被连带设成隐藏(Form.Visible 仍是 True,
|
||||
// 但屏幕上看不到);mshta.exe 是 GUI 子系统,既不会有黑控制台,窗口也能正常显示。
|
||||
const WAIT_WINDOW_HTA = `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="x-ua-compatible" content="ie=edge">
|
||||
<meta charset="utf-8">
|
||||
<title>37du 自动化工作台 - 升级</title>
|
||||
<hta:application
|
||||
border="thin"
|
||||
caption="yes"
|
||||
sysmenu="yes"
|
||||
maximizebutton="no"
|
||||
minimizebutton="no"
|
||||
scroll="no"
|
||||
contextmenu="no"
|
||||
selection="no"
|
||||
innerborder="no" />
|
||||
<style>
|
||||
html, body { margin: 0; padding: 0; overflow: hidden; }
|
||||
body {
|
||||
font-family: "Microsoft YaHei UI", "Microsoft YaHei", sans-serif;
|
||||
background: #ffffff; color: #20242c; padding: 22px 26px;
|
||||
}
|
||||
.title { font-size: 15px; font-weight: 700; }
|
||||
.bar { margin-top: 16px; height: 6px; background: #eef1f6; border-radius: 3px; overflow: hidden; position: relative; }
|
||||
.bar i { position: absolute; top: 0; left: -40%; width: 38%; height: 100%; border-radius: 3px;
|
||||
background: #4d8cff; animation: mv 1.15s linear infinite; }
|
||||
@keyframes mv { from { left: -40%; } to { left: 102%; } }
|
||||
.sub { margin-top: 14px; font-size: 12px; line-height: 1.7; color: #6e7480; min-height: 42px; }
|
||||
.foot { text-align: right; }
|
||||
button { font-family: inherit; font-size: 12px; padding: 7px 18px; border: 1px solid #d8dde6;
|
||||
border-radius: 4px; background: #f7f9fc; color: #20242c; cursor: pointer; }
|
||||
button:disabled { color: #a9b0bc; cursor: default; }
|
||||
</style>
|
||||
<script language="JScript">
|
||||
var exe = '__EXE__';
|
||||
var markerFile = '__MARKER__';
|
||||
var version = '__VERSION__';
|
||||
var finished = false;
|
||||
var closed = false;
|
||||
var startAt = (new Date()).getTime();
|
||||
var pollTimer = null;
|
||||
var fso = null;
|
||||
|
||||
function el(id) { return document.getElementById(id); }
|
||||
function setTitle(t) { el('ttl').innerHTML = t; }
|
||||
function setSub(t) { el('msg').innerHTML = t; }
|
||||
|
||||
function fsObject() {
|
||||
if (!fso) fso = new ActiveXObject('Scripting.FileSystemObject');
|
||||
return fso;
|
||||
}
|
||||
|
||||
// 靠安装脚本装完后写下的标记文件(ok / failed)判断结束,而不是 WMI 轮询进程名。
|
||||
// 进程名方案对中文/带空格的 exe 名不可靠(查询失败被静默吞掉→窗口永远关不掉),
|
||||
// 且"安装器自拉起"与"脚本补启动"两种路径都要照顾;标记文件由脚本自己在装完后落盘,最稳。
|
||||
function readMarker() {
|
||||
try {
|
||||
var f = fsObject();
|
||||
if (!f.FileExists(markerFile)) return '';
|
||||
var ts = f.OpenTextFile(markerFile, 1, false);
|
||||
var txt = ts.ReadAll();
|
||||
ts.Close();
|
||||
return String(txt);
|
||||
} catch (err) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function enableBtn() { el('btn').disabled = false; }
|
||||
|
||||
function closeWindow(ms) {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
|
||||
setTimeout(function () { window.close(); }, ms);
|
||||
}
|
||||
|
||||
function tick() {
|
||||
if (closed) return;
|
||||
var secs = ((new Date()).getTime() - startAt) / 1000;
|
||||
var m = readMarker();
|
||||
if (m && !finished) {
|
||||
finished = true;
|
||||
if (m.indexOf('failed') >= 0) {
|
||||
setTitle('升级未完成');
|
||||
setSub('安装失败,已为你重新打开旧版本。若未自动打开,请点击下方「打开客户端」。');
|
||||
enableBtn();
|
||||
setTimeout(function () { closeWindow(0); }, 8000);
|
||||
} else {
|
||||
setTitle('升级完成');
|
||||
setSub('正在重新打开客户端…');
|
||||
closeWindow(900);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!finished && secs >= 5) setSub('正在写入新版本,完成后会自动重新打开客户端…');
|
||||
if (el('btn').disabled && secs >= 20) enableBtn();
|
||||
if (secs >= 300 && !closed) {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
|
||||
setTitle('升级耗时较长');
|
||||
setSub('请点击「打开客户端」手动启动;若仍无法打开,请联系管理员。');
|
||||
enableBtn();
|
||||
}
|
||||
}
|
||||
|
||||
function openApp() {
|
||||
try {
|
||||
new ActiveXObject('WScript.Shell').Run('"' + exe + '"', 1, false);
|
||||
setSub('正在打开客户端…');
|
||||
closeWindow(900);
|
||||
} catch (err) {
|
||||
setSub('打开客户端失败:' + err.message + ',请稍后重试。');
|
||||
}
|
||||
}
|
||||
|
||||
function init() {
|
||||
try {
|
||||
window.resizeTo(470, 260);
|
||||
window.moveTo(Math.max(0, (screen.availWidth - 470) / 2), Math.max(0, (screen.availHeight - 260) / 2));
|
||||
} catch (e) { }
|
||||
window.focus();
|
||||
setTimeout(function () { window.focus(); }, 400);
|
||||
setTitle('正在安装新版本 v' + version);
|
||||
pollTimer = setInterval(tick, 500);
|
||||
tick();
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body onload="init()">
|
||||
<div class="title" id="ttl">正在准备升级…</div>
|
||||
<div class="bar"><i></i></div>
|
||||
<div class="sub" id="msg">正在重启客户端,安装完成后会自动重新打开,请稍候…</div>
|
||||
<div class="foot"><button id="btn" disabled="disabled" onclick="openApp()">打开客户端</button></div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
let _checking = false;
|
||||
let _downloading = false;
|
||||
let _pendingVersion = "";
|
||||
@@ -69,14 +214,29 @@ async function fetchCloudVersion() {
|
||||
}
|
||||
}
|
||||
|
||||
function cachePath(version) {
|
||||
return path.join(SHELL_CACHE, `setup-37du-host-${version}.exe`);
|
||||
}
|
||||
|
||||
// 流式计算 sha256:避免 readFileSync 一次性把 ~80MB 安装包读进内存
|
||||
function sha256File(p) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const h = crypto.createHash("sha256");
|
||||
const s = fs.createReadStream(p);
|
||||
s.on("data", (c) => h.update(c));
|
||||
s.on("error", reject);
|
||||
s.on("end", () => resolve(h.digest("hex")));
|
||||
});
|
||||
}
|
||||
|
||||
// 缓存包校验:sha256 与云端登记不一致(同版本号重新发版/下载中断残留)→ 删除旧包返回 null,
|
||||
// 触发重新下载,避免"缓存命中秒显示下载完成、实际是旧坏包"
|
||||
function validateCache(version, expectSha) {
|
||||
const p = path.join(SHELL_CACHE, `setup-37du-host-${version}.exe`);
|
||||
async function validateCache(version, expectSha) {
|
||||
const p = cachePath(version);
|
||||
if (!fs.existsSync(p)) return null;
|
||||
if (expectSha) {
|
||||
try {
|
||||
if (sha256Hex(fs.readFileSync(p)) !== String(expectSha).toLowerCase()) {
|
||||
if ((await sha256File(p)) !== String(expectSha).toLowerCase()) {
|
||||
logger.warning(`缓存安装包与云端 sha256 不符(旧坏包),删除后重新下载:${p}`);
|
||||
try { fs.unlinkSync(p); } catch (_) { /* 文件占用时下次再清 */ }
|
||||
return null;
|
||||
@@ -108,7 +268,8 @@ function cleanupStalePackages() {
|
||||
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);
|
||||
// .part = 上次下载中断的残留(启动时不可能有下载在跑),直接清掉
|
||||
const stale = (pkg && (!cur || !versionLt(cur, pkg[1]))) || /^apply-update-.+\.(cmd|vbs)$/i.test(f) || /^update-wait-.+\.(ps1|hta)$/i.test(f) || /\.part$/i.test(f);
|
||||
if (!stale) continue;
|
||||
try {
|
||||
fs.unlinkSync(path.join(SHELL_CACHE, f));
|
||||
@@ -157,7 +318,7 @@ async function checkUpdate() {
|
||||
_STATE.dl_status = "idle";
|
||||
_STATE.dl_pct = 0;
|
||||
}
|
||||
const cached = validateCache(cloud, info.sha256);
|
||||
const cached = await validateCache(cloud, info.sha256);
|
||||
if (cached) restorePending(cloud, notes, cached);
|
||||
} finally {
|
||||
_STATE.checking = false;
|
||||
@@ -205,7 +366,7 @@ async function startDownload() {
|
||||
return;
|
||||
}
|
||||
_STATE.dl_version = cloud;
|
||||
const cached = validateCache(cloud, info.sha256);
|
||||
const cached = await validateCache(cloud, info.sha256);
|
||||
if (cached) {
|
||||
restorePending(cloud, String(info.notes || ""), cached);
|
||||
return;
|
||||
@@ -218,7 +379,7 @@ async function startDownload() {
|
||||
} catch (e) {
|
||||
logger.warning(`下载壳子安装包失败:${e.message}`);
|
||||
_STATE.dl_status = "failed";
|
||||
_STATE.dl_error = `安装包下载失败(${e.constructor.name})`;
|
||||
_STATE.dl_error = `安装包下载失败:${(e && e.message) || e.constructor.name}`;
|
||||
cleanupPart(cloud);
|
||||
} finally {
|
||||
_downloading = false;
|
||||
@@ -227,43 +388,47 @@ async function startDownload() {
|
||||
|
||||
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 tmp = `${cachePath(cloud)}.part`;
|
||||
const pkg = cachePath(cloud);
|
||||
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) => {
|
||||
try {
|
||||
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;
|
||||
},
|
||||
});
|
||||
received = r.received;
|
||||
total = r.contentLength;
|
||||
});
|
||||
} 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())));
|
||||
} catch (e) {
|
||||
out.destroy(); // 释放文件句柄,否则 Windows 上 cleanupPart 删不掉 .part
|
||||
throw e;
|
||||
}
|
||||
await new Promise((res, rej) => out.end((e) => (e ? rej(e) : res())));
|
||||
const digest = sha.digest("hex");
|
||||
if (expect && digest !== expect) {
|
||||
logger.error(`壳子安装包 sha256 校验失败,放弃更新`);
|
||||
@@ -290,20 +455,23 @@ async function download(cloud, info) {
|
||||
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);
|
||||
try {
|
||||
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);
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timer); // 失败分支也要清,否则定时器泄漏并可能在 10 分钟后误 abort
|
||||
}
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
function cleanupPart(cloud) {
|
||||
@@ -314,6 +482,29 @@ function cleanupPart(cloud) {
|
||||
}
|
||||
}
|
||||
|
||||
// 启动独立等待窗口:Electron 退出后接管界面,避免"点完升级窗口直接消失、全程无提示"。
|
||||
// mshta.exe 是 GUI 子系统:不产生黑控制台;detached 保证父进程退出后窗口存活;
|
||||
// 千万不要传 windowsHide —— 它会让窗口被创建即隐藏(这正是 PowerShell 方案失效的原因)。
|
||||
function spawnWaitWindow(version, exe, markerFile) {
|
||||
const hta = path.join(SHELL_CACHE, `update-wait-${version}.hta`);
|
||||
try {
|
||||
// 用 JSON.stringify 生成 JScript 字符串字面量:Windows 路径反斜杠、中文目录名都能正确转义
|
||||
// 用函数式 replace,避免路径里的 $& / $' 被当成替换模式
|
||||
const fill = (src, token, val) => src.replace(token, () => JSON.stringify(val));
|
||||
let html = WAIT_WINDOW_HTA;
|
||||
html = fill(html, "'__EXE__'", exe);
|
||||
html = fill(html, "'__MARKER__'", markerFile);
|
||||
html = fill(html, "'__VERSION__'", version);
|
||||
// 带 BOM 的 UTF-8,保证 mshta 正确识别中文
|
||||
fs.writeFileSync(hta, "\uFEFF" + html, "utf8");
|
||||
const child = spawn("mshta.exe", [hta], { cwd: SHELL_CACHE, detached: true, stdio: "ignore" });
|
||||
child.on("error", (e) => logger.warning(`启动升级等待窗口失败:${e.message}`));
|
||||
child.unref();
|
||||
} catch (e) {
|
||||
logger.warning(`启动升级等待窗口失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function pendingStatus() {
|
||||
let cur = localShellVersion();
|
||||
// 用已校验的 _pendingPkg 判断(不做全量 sha 重算——状态接口被前端高频轮询)
|
||||
@@ -346,33 +537,139 @@ function pendingStatus() {
|
||||
}
|
||||
|
||||
function applyUpdate() {
|
||||
// 防重入:前端重复点击 / 用户连点会让多个安装器同时启动,安装必失败
|
||||
if (_STATE.applying) {
|
||||
throw Object.assign(new Error("正在升级中,请稍候"), { status: 409 });
|
||||
}
|
||||
const version = _pendingVersion;
|
||||
const pkg = _pendingPkg || validateCache(version, "");
|
||||
if (!pkg || !fs.existsSync(pkg)) {
|
||||
throw new Error(`未找到已下载的安装包:${pkg || `setup-37du-host-${version}.exe`}`);
|
||||
const pkg = _pendingPkg && fs.existsSync(_pendingPkg) ? _pendingPkg : version ? cachePath(version) : "";
|
||||
if (!version || !pkg || !fs.existsSync(pkg)) {
|
||||
throw Object.assign(new Error(`未找到已下载的安装包:${pkg || `setup-37du-host-${version || "?"}.exe`}`), { status: 404 });
|
||||
}
|
||||
_STATE.applying = true;
|
||||
logger.info(`开始静默升级到 ${version}:${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,
|
||||
}).unref();
|
||||
// 给安装器接管进程,随后退出
|
||||
// electron-builder NSIS 静默参数是 /S(不认 Inno 的 /VERYSILENT)。
|
||||
// 静默安装结束后安装器可能已自行拉起新版本(electron-updater 语义,进程带 --updated),
|
||||
// 因此安装成功时先等 3s 检测进程,确实没起来才补启动,避免双实例;
|
||||
// 安装失败时落日志并把旧版本拉起来,避免用户"点完升级窗口直接消失"。
|
||||
// 用 wscript.exe 跑 VBS 而不是 cmd.exe 跑批处理:detached 启动时 cmd 会自建控制台,
|
||||
// windowsHide 对 DETACHED_PROCESS 不生效,用户会看到黑窗口连弹;wscript 是 GUI 子系统,无控制台。
|
||||
const newExe = process.execPath;
|
||||
const exeName = path.basename(newExe);
|
||||
const vbs = path.join(SHELL_CACHE, `apply-update-${version}.vbs`);
|
||||
const logFile = path.join(SHELL_CACHE, "update-apply.log");
|
||||
const markerFile = path.join(SHELL_CACHE, "update-apply.done");
|
||||
try {
|
||||
// VBS 默认按 ANSI 读取脚本,安装目录 / exe 名含中文会乱码;
|
||||
// 带 BOM 的 UTF-16LE 才能让 wscript 正确解析中文路径
|
||||
const script = "\uFEFF" + [
|
||||
"Option Explicit",
|
||||
"Dim pkg, exe, exeName, logFile, markerFile, sh, fso, rc",
|
||||
`pkg = "${pkg}"`,
|
||||
`exe = "${newExe}"`,
|
||||
`exeName = "${exeName}"`,
|
||||
`logFile = "${logFile}"`,
|
||||
`markerFile = "${markerFile}"`,
|
||||
'Set sh = CreateObject("WScript.Shell")',
|
||||
'Set fso = CreateObject("Scripting.FileSystemObject")',
|
||||
"",
|
||||
"Sub WriteLog(msg)",
|
||||
" On Error Resume Next",
|
||||
" Dim f",
|
||||
" Set f = fso.OpenTextFile(logFile, 8, True)",
|
||||
' f.WriteLine Now & " " & msg',
|
||||
" f.Close",
|
||||
"End Sub",
|
||||
"",
|
||||
// 等待窗口靠这个标记文件判断"可以关窗了"(ok / failed),
|
||||
// 不再依赖它在窗口里查进程名——那套对中文带空格的进程名不可靠。
|
||||
"Sub WriteMarker(txt)",
|
||||
" On Error Resume Next",
|
||||
" Dim f",
|
||||
" Set f = fso.CreateTextFile(markerFile, True)",
|
||||
" f.Write txt",
|
||||
" f.Close",
|
||||
"End Sub",
|
||||
"",
|
||||
// 查进程数:用 WMI 而不是 tasklist。sh.Exec("tasklist ...") 每次都会拉起一个可见的
|
||||
// cmd 控制台,轮询期间用户在屏幕上看到的就是连环闪黑窗(本次体验问题的根因)。
|
||||
"Function ProcCount(name)",
|
||||
" Dim svc, col",
|
||||
" ProcCount = -1",
|
||||
" On Error Resume Next",
|
||||
' Set svc = GetObject("winmgmts:\\\\.\\root\\cimv2")',
|
||||
' Set col = svc.ExecQuery("SELECT ProcessId FROM Win32_Process WHERE Name=\'" & name & "\'")',
|
||||
" If Err.Number = 0 Then ProcCount = col.Count",
|
||||
" Err.Clear",
|
||||
"End Function",
|
||||
"",
|
||||
// 清掉上一轮日志 / 标记,避免等待窗口一启动就读到旧状态
|
||||
"On Error Resume Next",
|
||||
"If fso.FileExists(logFile) Then fso.DeleteFile logFile, True",
|
||||
"If fso.FileExists(markerFile) Then fso.DeleteFile markerFile, True",
|
||||
"On Error GoTo 0",
|
||||
"",
|
||||
// 等本进程(旧壳)完全退出,否则 NSIS 检测到应用在运行会直接失败
|
||||
"WScript.Sleep 2500",
|
||||
// 0 = 隐藏安装器窗口,True = 等安装结束
|
||||
'rc = sh.Run("""" & pkg & """ /S", 0, True)',
|
||||
"If rc <> 0 Then",
|
||||
' WriteLog "install failed, rc=" & rc & ", pkg=" & pkg',
|
||||
" WriteMarker \"failed\"",
|
||||
' sh.Run """" & exe & """", 1, False',
|
||||
" WScript.Quit 0",
|
||||
"End If",
|
||||
// 安装成功后轮询最多 5s 等新进程起来(静默安装不一定自动拉起),没起来再补启动,
|
||||
// 避免与安装器自身拉起的实例并发双开(壳子有单实例锁,重复启动也只是多闪一下)。
|
||||
"Dim i, started",
|
||||
"started = False",
|
||||
"For i = 1 To 10",
|
||||
" WScript.Sleep 500",
|
||||
" If ProcCount(exeName) > 0 Then",
|
||||
" started = True",
|
||||
" Exit For",
|
||||
" End If",
|
||||
"Next",
|
||||
"If Not started Then",
|
||||
' WriteLog "安装完成但未检测到进程,补启动:" & exe',
|
||||
" On Error Resume Next",
|
||||
' sh.Run """" & exe & """", 1, False',
|
||||
" If Err.Number <> 0 Then",
|
||||
" WriteLog \"补启动失败:\" & Err.Description",
|
||||
" WriteMarker \"failed\"",
|
||||
" WScript.Quit 0",
|
||||
" End If",
|
||||
" On Error GoTo 0",
|
||||
"End If",
|
||||
'WriteMarker "ok"',
|
||||
"WScript.Quit 0",
|
||||
"",
|
||||
].join("\r\n");
|
||||
fs.writeFileSync(vbs, script, "utf16le");
|
||||
// 先清掉上一轮日志 / 标记:残留会让等待窗口一启动就误判"已完成"或"升级未完成"
|
||||
try { fs.unlinkSync(logFile); } catch (_) { /* 不存在或占用,忽略 */ }
|
||||
try { fs.unlinkSync(markerFile); } catch (_) { /* 不存在或占用,忽略 */ }
|
||||
// 先起等待窗口(Electron 随后退出,界面由它接管),再起安装脚本
|
||||
spawnWaitWindow(version, newExe, markerFile);
|
||||
const child = spawn("wscript.exe", ["//nologo", "//B", vbs], {
|
||||
cwd: SHELL_CACHE,
|
||||
windowsHide: true,
|
||||
stdio: "ignore",
|
||||
detached: true,
|
||||
});
|
||||
child.on("error", (e) => {
|
||||
_STATE.applying = false;
|
||||
logger.error(`启动升级脚本失败:${e.message}`);
|
||||
});
|
||||
child.unref();
|
||||
} catch (e) {
|
||||
_STATE.applying = false;
|
||||
throw e;
|
||||
}
|
||||
// 给等待窗口(mshta 启动约 1s)和前端遮罩层留出展示时间,随后退出让安装器替换文件
|
||||
setTimeout(() => {
|
||||
if (typeof process.exit === "function") process.exit(0);
|
||||
}, 1000);
|
||||
}, 1800);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
// 托盘菜单弹窗专用 preload:只暴露菜单动作白名单。
|
||||
"use strict";
|
||||
|
||||
const { contextBridge, ipcRenderer } = require("electron");
|
||||
|
||||
contextBridge.exposeInMainWorld("trayMenu", {
|
||||
action: (name) => ipcRenderer.send("tray-menu:action", String(name || "")),
|
||||
toggleAutostart: () => ipcRenderer.invoke("tray-menu:toggle-autostart"),
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
// 自定义托盘右键菜单:无边框卡片式弹窗,替代系统原生菜单(原生样式跟随系统、不可控)。
|
||||
// 用法:attach(tray, { onOpen, onQuit }),主进程负责窗口与菜单项动作。
|
||||
"use strict";
|
||||
|
||||
const path = require("path");
|
||||
const { app, BrowserWindow, ipcMain, screen } = require("electron");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("tray-menu");
|
||||
|
||||
const W = 236;
|
||||
const H = 178; // 与 buildHTML 里的内容高度一致(头部 44 + 三分隔 + 三菜单项)
|
||||
const MARGIN = 8; // 与托盘图标 / 屏幕边缘留白
|
||||
|
||||
let win = null;
|
||||
let trayRef = null;
|
||||
let handlers = { onOpen: null, onQuit: null };
|
||||
let wired = false;
|
||||
|
||||
function buildHTML() {
|
||||
const version = app.getVersion();
|
||||
const autoOn = app.getLoginItemSettings().openAtLogin ? "on" : "";
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><style>
|
||||
*{margin:0;padding:0;box-sizing:border-box;font-family:"Segoe UI","Microsoft YaHei",sans-serif;
|
||||
-webkit-user-select:none;user-select:none}
|
||||
html,body{background:transparent;overflow:hidden}
|
||||
.card{position:fixed;inset:0;background:#fff;border:1px solid #E8EAF1;border-radius:14px;
|
||||
box-shadow:0 16px 38px -16px rgba(18,20,31,.38),0 4px 12px -6px rgba(18,20,31,.12);
|
||||
padding:6px;display:flex;flex-direction:column;
|
||||
animation:pop .16s cubic-bezier(.2,.8,.3,1)}
|
||||
@keyframes pop{from{opacity:0;transform:translateY(6px) scale(.985)}to{opacity:1;transform:none}}
|
||||
.head{display:flex;align-items:center;gap:9px;padding:6px 8px 10px}
|
||||
.logo{width:26px;height:26px;border-radius:8px;background:linear-gradient(135deg,#4F5AE8,#0F9F9B);
|
||||
color:#fff;font-size:11px;font-weight:800;display:flex;align-items:center;justify-content:center;letter-spacing:.2px}
|
||||
.hi{min-width:0;flex:1}
|
||||
.hi b{display:block;font-size:12.5px;color:#12141B;font-weight:600;
|
||||
white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.hi span{display:flex;align-items:center;gap:5px;font-size:11px;color:#6E7686;margin-top:3px}
|
||||
.dot{width:5px;height:5px;border-radius:50%;background:#0E9F76;box-shadow:0 0 0 2px rgba(14,159,118,.14)}
|
||||
.sep{height:1px;background:#F0F2F7;margin:4px 6px}
|
||||
.item{display:flex;align-items:center;gap:9px;height:34px;padding:0 9px;border-radius:9px;
|
||||
font-size:12.5px;color:#3C4250;cursor:pointer;transition:background .12s,color .12s}
|
||||
.item:hover{background:#F5F6FA;color:#12141B}
|
||||
.item .ic{width:15px;height:15px;flex-shrink:0;color:#8A92A3}
|
||||
.item:hover .ic{color:#4F5AE8}
|
||||
.item.brand{color:#3D47D4;font-weight:600}
|
||||
.item.brand .ic{color:#4F5AE8}
|
||||
.item.danger:hover{background:#FDEDED;color:#CC3B40}
|
||||
.item.danger:hover .ic{color:#E5484D}
|
||||
.sw{margin-left:auto;width:26px;height:15px;border-radius:8px;background:#E3E6EF;position:relative;
|
||||
transition:background .16s;flex-shrink:0}
|
||||
.sw::after{content:"";position:absolute;top:2px;left:2px;width:11px;height:11px;border-radius:50%;
|
||||
background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.2);transition:transform .16s}
|
||||
.sw.on{background:#4F5AE8}
|
||||
.sw.on::after{transform:translateX(11px)}
|
||||
</style></head><body>
|
||||
<div class="card">
|
||||
<div class="head">
|
||||
<div class="logo">37</div>
|
||||
<div class="hi">
|
||||
<b>37du 自动化工作台</b>
|
||||
<span><i class="dot"></i>服务运行中 · v${version}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sep"></div>
|
||||
<div class="item brand" data-act="open">
|
||||
<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"
|
||||
stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="14" rx="2.5"/>
|
||||
<path d="M3 9h18"/><path d="M9 22h6"/></svg>
|
||||
<span>打开工作台</span>
|
||||
</div>
|
||||
<div class="item" data-act="autostart">
|
||||
<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"
|
||||
stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v9"/>
|
||||
<path d="M6.4 6.4a8 8 0 1 0 11.2 0"/></svg>
|
||||
<span>开机自启</span>
|
||||
<span class="sw ${autoOn}" id="sw"></span>
|
||||
</div>
|
||||
<div class="sep"></div>
|
||||
<div class="item danger" data-act="quit">
|
||||
<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"
|
||||
stroke-linecap="round" stroke-linejoin="round"><path d="M12 21a9 9 0 1 0-9-9"/>
|
||||
<path d="M3 16v5h5"/></svg>
|
||||
<span>退出</span>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
document.addEventListener("click", async (e) => {
|
||||
const el = e.target.closest(".item");
|
||||
if (!el) return;
|
||||
const act = el.dataset.act;
|
||||
if (act === "autostart") {
|
||||
const on = await window.trayMenu.toggleAutostart();
|
||||
document.getElementById("sw").classList.toggle("on", !!on);
|
||||
return;
|
||||
}
|
||||
window.trayMenu.action(act);
|
||||
});
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape") window.trayMenu.action("close");
|
||||
});
|
||||
document.addEventListener("contextmenu", (e) => e.preventDefault());
|
||||
</script>
|
||||
</body></html>`;
|
||||
}
|
||||
|
||||
function closeMenu() {
|
||||
if (win && !win.isDestroyed()) win.destroy();
|
||||
win = null;
|
||||
}
|
||||
|
||||
function openMenu() {
|
||||
if (win && !win.isDestroyed()) { closeMenu(); return; } // 再次右键 = 收起
|
||||
if (!trayRef) return;
|
||||
|
||||
try {
|
||||
// 托盘图标可能被折叠进"隐藏的图标"面板(bounds 无效),此时以鼠标位置为锚点
|
||||
let b = trayRef.getBounds();
|
||||
if (!b || !b.width) {
|
||||
const p = screen.getCursorScreenPoint();
|
||||
b = { x: p.x - 8, y: p.y - 8, width: 16, height: 16 };
|
||||
}
|
||||
const pt = { x: b.x + Math.round(b.width / 2), y: b.y + Math.round(b.height / 2) };
|
||||
const wa = screen.getDisplayNearestPoint(pt).workArea;
|
||||
|
||||
// 任务栏在屏幕下半部分时菜单向上弹出,否则向下
|
||||
let x = Math.round(b.x + b.width / 2 - W / 2);
|
||||
let y = b.y > wa.y + wa.height / 2 ? b.y - H - MARGIN : b.y + b.height + MARGIN;
|
||||
x = Math.max(wa.x + MARGIN, Math.min(x, wa.x + wa.width - W - MARGIN));
|
||||
y = Math.max(wa.y + MARGIN, Math.min(y, wa.y + wa.height - H - MARGIN));
|
||||
|
||||
win = new BrowserWindow({
|
||||
width: W, height: H, x, y,
|
||||
frame: false, transparent: true, resizable: false, movable: false,
|
||||
minimizable: false, maximizable: false, fullscreenable: false,
|
||||
skipTaskbar: true, alwaysOnTop: true, show: false, hasShadow: false,
|
||||
backgroundColor: "#00000000",
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, "tray-menu-preload.js"),
|
||||
contextIsolation: true, nodeIntegration: false, sandbox: true,
|
||||
},
|
||||
});
|
||||
win.setAlwaysOnTop(true, "pop-up-menu");
|
||||
win.loadURL("data:text/html;charset=utf-8," + encodeURIComponent(buildHTML()));
|
||||
win.once("ready-to-show", () => {
|
||||
if (win && !win.isDestroyed()) { win.show(); win.focus(); }
|
||||
});
|
||||
win.on("blur", () => closeMenu());
|
||||
win.on("closed", () => { win = null; });
|
||||
} catch (e) {
|
||||
logger.warning(`托盘菜单打开失败:${e.message}`);
|
||||
closeMenu();
|
||||
}
|
||||
}
|
||||
|
||||
function wire() {
|
||||
if (wired) return;
|
||||
wired = true;
|
||||
ipcMain.on("tray-menu:action", (_e, act) => {
|
||||
if (act === "open") {
|
||||
closeMenu();
|
||||
if (handlers.onOpen) handlers.onOpen();
|
||||
} else if (act === "quit") {
|
||||
closeMenu();
|
||||
if (handlers.onQuit) handlers.onQuit();
|
||||
} else {
|
||||
closeMenu();
|
||||
}
|
||||
});
|
||||
ipcMain.handle("tray-menu:toggle-autostart", () => {
|
||||
const next = !app.getLoginItemSettings().openAtLogin;
|
||||
app.setLoginItemSettings({ openAtLogin: next });
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function attach(tray, opts) {
|
||||
trayRef = tray;
|
||||
handlers = opts || { onOpen: null, onQuit: null };
|
||||
wire();
|
||||
tray.on("right-click", openMenu);
|
||||
}
|
||||
|
||||
module.exports = { attach, close: closeMenu };
|
||||
Reference in New Issue
Block a user