Files
37duAutomation/desktop/electron-shell/electron/electron-main.js
T
puddy eeb951f9f6 feat(fileserver): 新增内网文件服务器服务与管理页面
新增 FastAPI 文件服务器核心模块(配置、鉴权、存储、心跳上报),新增 HTTP 路由接口(健康检查、文件上传/下载/删除、管理登录/密码修改/统计),新增 Vue3 管理页面源码;新增 MySQL 元数据存储支持,新增 PyMySQL 依赖;新增 .gitignore 忽略 IDE 与备份文件;新增文件服务器工具脚本;删除旧的 build/ 脚本与 exe 构建产物,优化 Electron 平台登录逻辑为纯接口模式,新增平台账号环境变量注入,优化试用期异常检查逻辑,拆分服务岗转正流程为独立脚本。
2026-10-12 09:45:04 +08:00

202 lines
7.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Electron 壳:窗口 / 托盘 / 单实例 / 自启。渲染层加载本地 8799 兼容层(复用 webhost 前端)。
"use strict";
const fs = require("fs");
const { app, BrowserWindow, Tray, Menu, nativeImage, dialog, screen } = require("electron");
const path = require("path");
const config = require("./config");
const { makeLogger } = require("./logger");
const logger = makeLogger("electron-main");
// 移除 Electron 默认英文菜单栏(File Edit View Window Help):成品客户端菜单由页面自绘
Menu.setApplicationMenu(null);
const PORT = config.PORT;
const URL = `http://127.0.0.1:${PORT}`;
// 窗口状态持久化:记住位置/尺寸,重启还原(防显示器变更后窗口跑到屏幕外)
const WINDOW_STATE_FILE = path.join(config.APP_DATA, "window-state.json");
function loadWindowState() {
try {
if (!fs.existsSync(WINDOW_STATE_FILE)) return null;
const s = JSON.parse(fs.readFileSync(WINDOW_STATE_FILE, "utf-8"));
if (!s || typeof s !== "object") return null;
const w = Math.max(1000, Math.min(4000, Number(s.width) || 1200));
const h = Math.max(660, Math.min(4000, Number(s.height) || 780));
const x = Number(s.x);
const y = Number(s.y);
if (
!Number.isFinite(x) ||
!Number.isFinite(y) ||
!screen.getAllDisplays().some((d) => {
const a = d.workArea;
return x < a.x + a.width && x + w > a.x && y < a.y + a.height && y + h > a.y;
})
) {
return { width: w, height: h }; // 位置失效:只恢复尺寸
}
return { width: w, height: h, x, y };
} catch (e) {
return null;
}
}
function saveWindowState(win) {
try {
const b = win.getBounds();
fs.mkdirSync(config.APP_DATA, { recursive: true });
fs.writeFileSync(WINDOW_STATE_FILE, JSON.stringify(b), "utf-8");
} catch (e) {
/* 忽略:状态保存失败不影响运行 */
}
}
let mainWindow = null;
let tray = null;
let server = null;
let isQuitting = false; // 托盘「退出」/系统退出时置真,放行真正关闭;否则关闭窗口 = 收托盘
// 单实例锁:重复启动聚焦已有窗口
if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
app.on("second-instance", () => {
if (mainWindow && !mainWindow.isDestroyed()) {
if (mainWindow.isMinimized()) mainWindow.restore();
// 收托盘走的是 hide():隐藏窗口不是 minimized,focus() 也唤不回,必须先 show()
mainWindow.show();
mainWindow.focus();
}
});
app.setAppUserModelId("37du.Host");
function createWindow() {
const st = loadWindowState() || {};
mainWindow = new BrowserWindow({
width: st.width || 1200,
height: st.height || 780,
x: st.x,
y: st.y,
minWidth: 1000,
minHeight: 660,
// 与启动页默认皮肤底色一致(style.css --bg #F9F7F2),避免冷启动色跳
backgroundColor: "#F9F7F2",
title: "37du 自动化工作台",
icon: trayIconImage(),
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
preload: path.join(__dirname, "preload.js"),
},
});
mainWindow.loadURL(URL);
// 关闭时保存窗口状态;resize/move 防抖保存(异常退出也不丢太多)
let stateTimer = null;
const save = () => {
if (stateTimer) clearTimeout(stateTimer);
stateTimer = setTimeout(() => {
if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow);
}, 400);
if (stateTimer.unref) stateTimer.unref();
};
mainWindow.on("resize", save);
mainWindow.on("move", save);
mainWindow.on("close", (e) => {
if (isQuitting) {
if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow);
return; // 真正退出:放行关闭
}
// 关闭按钮 → 收托盘(隐藏窗口,服务/插件继续运行),从托盘菜单「退出」才真正退出
e.preventDefault();
mainWindow.hide();
});
mainWindow.on("closed", () => {
mainWindow = null;
});
}
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")}`);
}
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();
});
}
app.whenReady().then(async () => {
try {
const { init } = require("./app");
const { listen } = require("./server");
// 先起本地服务并【立即创建窗口】(登录页/首屏立刻可见),网络初始化放后台执行。
// 否则 `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}`);
app.quit();
}
});
app.on("window-all-closed", () => {
// 关闭窗口默认收托盘(close 已拦截),只有真正退出路径才会走到这里
app.quit();
});
app.on("before-quit", () => {
isQuitting = true; // 放行主窗口真正关闭
try {
if (server) server.close();
} catch (e) {
/* 忽略 */
}
});
}