调整C端展示
This commit is contained in:
@@ -1,52 +1,18 @@
|
|||||||
@echo off
|
@echo off
|
||||||
chcp 65001 >nul
|
chcp 65001 >nul
|
||||||
echo ========================================
|
echo ========================================
|
||||||
echo 清理并重新打包
|
echo 清理并重新打包`r
|
||||||
echo ========================================
|
echo ========================================
|
||||||
echo.
|
echo.
|
||||||
|
|
||||||
echo [1/5] 结束所有相关进程...
|
echo [1/5] 结束所有相关进<EFBFBD>?..
|
||||||
echo 正在停止 NPQS9100...
|
echo 正在停止 NPQS9100...
|
||||||
taskkill /F /IM NPQS9100.exe 2>nul
|
taskkill /F /IM NPQS9100.exe 2>nul
|
||||||
|
|
||||||
echo 正在停止 MySQL...
|
|
||||||
taskkill /F /IM mysqld.exe 2>nul
|
|
||||||
timeout /t 2 /nobreak >nul
|
|
||||||
|
|
||||||
REM 验证 MySQL 是否真的停止了
|
|
||||||
tasklist | find /I "mysqld.exe" >nul 2>&1
|
|
||||||
if %errorlevel% equ 0 (
|
|
||||||
echo ! MySQL 进程还在运行,再次尝试...
|
|
||||||
taskkill /F /IM mysqld.exe 2>nul
|
|
||||||
timeout /t 2 /nobreak >nul
|
|
||||||
|
|
||||||
REM 再次验证
|
|
||||||
tasklist | find /I "mysqld.exe" >nul 2>&1
|
|
||||||
if %errorlevel% equ 0 (
|
|
||||||
echo ! MySQL 进程仍在运行,使用强制方法...
|
|
||||||
REM 找出所有 mysqld.exe 的 PID 并逐个杀死
|
|
||||||
for /f "tokens=2" %%a in ('tasklist ^| find /I "mysqld.exe"') do (
|
|
||||||
echo 强制结束 PID: %%a
|
|
||||||
taskkill /F /PID %%a 2>nul
|
|
||||||
)
|
|
||||||
timeout /t 2 /nobreak >nul
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
REM 最终验证
|
|
||||||
tasklist | find /I "mysqld.exe" >nul 2>&1
|
|
||||||
if %errorlevel% equ 0 (
|
|
||||||
echo ✗ 警告:MySQL 进程可能仍在运行
|
|
||||||
echo 请手动运行 build\extraResources\mysql\kill-running-port.bat
|
|
||||||
pause
|
|
||||||
) else (
|
|
||||||
echo ✓ MySQL 已完全停止
|
|
||||||
)
|
|
||||||
|
|
||||||
echo 正在停止 Java...
|
echo 正在停止 Java...
|
||||||
taskkill /F /IM java.exe 2>nul
|
taskkill /F /IM java.exe 2>nul
|
||||||
taskkill /F /IM javaw.exe 2>nul
|
taskkill /F /IM javaw.exe 2>nul
|
||||||
echo ✓ 所有进程已结束
|
echo <EFBFBD>?所有进程已结束
|
||||||
timeout /t 2 /nobreak >nul
|
timeout /t 2 /nobreak >nul
|
||||||
echo.
|
echo.
|
||||||
|
|
||||||
@@ -55,50 +21,49 @@ cd /d "%~dp0.."
|
|||||||
if exist out (
|
if exist out (
|
||||||
rmdir /s /q out 2>nul
|
rmdir /s /q out 2>nul
|
||||||
if exist out (
|
if exist out (
|
||||||
echo ✗ 删除失败,请手动删除 out 目录
|
echo <EFBFBD>?删除失败,请手动删除 out 目录
|
||||||
pause
|
pause
|
||||||
exit /b 1
|
exit /b 1
|
||||||
) else (
|
) else (
|
||||||
echo ✓ out 目录已删除
|
echo <EFBFBD>?out 目录已删除`r
|
||||||
)
|
)
|
||||||
) else (
|
) else (
|
||||||
echo ✓ out 目录不存在
|
echo <EFBFBD>?out 目录不存在`r
|
||||||
)
|
)
|
||||||
echo.
|
echo.
|
||||||
|
|
||||||
echo [3/5] 构建前端代码...
|
echo [3/5] 构建前端代码...
|
||||||
call npm run build-frontend
|
call npm run build-frontend
|
||||||
if %errorlevel% neq 0 (
|
if %errorlevel% neq 0 (
|
||||||
echo ✗ 前端构建失败
|
echo <EFBFBD>?前端构建失败
|
||||||
pause
|
pause
|
||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
echo ✓ 前端代码构建完成
|
echo <EFBFBD>?前端代码构建完成
|
||||||
echo.
|
echo.
|
||||||
|
|
||||||
echo [4/5] 构建 electron 代码...
|
echo [4/5] 构建 electron 代码...
|
||||||
call npm run build-electron
|
call npm run build-electron
|
||||||
if %errorlevel% neq 0 (
|
if %errorlevel% neq 0 (
|
||||||
echo ✗ electron 构建失败
|
echo <EFBFBD>?electron 构建失败
|
||||||
pause
|
pause
|
||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
echo ✓ electron 代码构建完成
|
echo <EFBFBD>?electron 代码构建完成
|
||||||
echo.
|
echo.
|
||||||
|
|
||||||
echo [5/5] 打包 Windows 版本(包含代码加密)...
|
echo [5/5] 打包 Windows 版本(包含代码加密)...
|
||||||
call npm run build-w
|
call npm run build-w
|
||||||
if %errorlevel% neq 0 (
|
if %errorlevel% neq 0 (
|
||||||
echo ✗ 打包失败
|
echo <EFBFBD>?打包失败
|
||||||
pause
|
pause
|
||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
echo.
|
echo.
|
||||||
|
|
||||||
echo ========================================
|
echo ========================================
|
||||||
echo ✓ 打包完成!
|
echo <EFBFBD>?打包完成!`r
|
||||||
echo 输出目录: out\win-unpacked\
|
echo 输出目录: out\win-unpacked\
|
||||||
echo ========================================
|
echo ========================================
|
||||||
echo.
|
echo.
|
||||||
pause
|
pause
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
@@ -1,6 +0,0 @@
|
|||||||
ALTER USER IF EXISTS 'root'@'localhost' IDENTIFIED BY 'njcnpqs';
|
|
||||||
CREATE USER IF NOT EXISTS 'root'@'127.0.0.1' IDENTIFIED BY 'njcnpqs';
|
|
||||||
GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1' WITH GRANT OPTION;
|
|
||||||
CREATE USER IF NOT EXISTS 'root'@'%' IDENTIFIED BY 'njcnpqs';
|
|
||||||
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
|
|
||||||
FLUSH PRIVILEGES;
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 87 KiB After Width: | Height: | Size: 120 KiB |
@@ -35,6 +35,10 @@
|
|||||||
"from": "build/extraResources/read.txt",
|
"from": "build/extraResources/read.txt",
|
||||||
"to": "extraResources/read.txt"
|
"to": "extraResources/read.txt"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"from": "build/extraResources/使用说明.txt",
|
||||||
|
"to": "extraResources/使用说明.txt"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"from": "scripts/",
|
"from": "scripts/",
|
||||||
"to": "scripts",
|
"to": "scripts",
|
||||||
@@ -51,9 +55,30 @@
|
|||||||
"from": "build/extraResources/jre",
|
"from": "build/extraResources/jre",
|
||||||
"to": "jre",
|
"to": "jre",
|
||||||
"filter": ["**/*"]
|
"filter": ["**/*"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "build/NPQS9100-启动器.bat",
|
||||||
|
"to": "NPQS9100-启动器.bat"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "build/extraResources/使用说明.txt",
|
||||||
|
"to": "使用说明.txt"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "build/upgrade.bat",
|
||||||
|
"to": "upgrade.bat"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "build/rollback.bat",
|
||||||
|
"to": "rollback.bat"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "build/README-升级回滚.txt",
|
||||||
|
"to": "README-升级回滚.txt"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"win": {
|
"win": {
|
||||||
|
"icon": "public/images/icon.png",
|
||||||
"artifactName": "${productName}-${os}-${version}-${arch}.${ext}",
|
"artifactName": "${productName}-${os}-${version}-${arch}.${ext}",
|
||||||
"target": [
|
"target": [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,133 +0,0 @@
|
|||||||
## 便携式 JRE/JDK8 集成指南
|
|
||||||
|
|
||||||
本指南介绍如何将 JRE 8 以“便携式”(解压即用、无需安装)的方式随应用打包,并在 Electron 主进程中通过绝对路径调用,从而避免要求用户在系统中安装 JDK/JRE。
|
|
||||||
|
|
||||||
### 为什么选择便携式 JRE
|
|
||||||
- 无需管理员权限与系统环境变量配置,用户无感知。
|
|
||||||
- 不污染系统环境(不写入 JAVA_HOME/PATH)。
|
|
||||||
- 跨平台一致,可精简体积、可控版本。
|
|
||||||
|
|
||||||
### 适用场景
|
|
||||||
- 运行 Java 程序或 JAR 包(仅需运行时)。
|
|
||||||
- 不需要 javac/jcmd/jmap 等开发/诊断工具(若需要,请改为随包便携式 JDK)。
|
|
||||||
|
|
||||||
### 推荐的 JRE 8 发行版(可再分发)
|
|
||||||
- Azul Zulu 8 JRE(可选 ZuluFX 含 JavaFX):[下载页面](https://www.azul.com/downloads/?version=java-8-lts&package=jre)
|
|
||||||
- BellSoft Liberica 8 JRE(Standard/Full,Full 含 JavaFX):[下载页面](https://bell-sw.com/pages/downloads/#/java-8-lts)
|
|
||||||
- Eclipse Temurin 8 JRE(Adoptium):[下载页面](https://adoptium.net/temurin/releases/?version=8)
|
|
||||||
|
|
||||||
选择要点:
|
|
||||||
- 需要 AWT/Swing/字体/打印 → 选择非 headless 包。
|
|
||||||
- 需要 JavaFX → 选择 Liberica Full 或 ZuluFX。
|
|
||||||
- 仅命令行/服务端 → 任意 JRE 8(headless 也可)。
|
|
||||||
|
|
||||||
### 目录放置约定
|
|
||||||
将解压后的 JRE 放入项目的 `build/extraResources/jre`,保证内部存在 `bin/java(.exe)`:
|
|
||||||
|
|
||||||
```
|
|
||||||
build/
|
|
||||||
extraResources/
|
|
||||||
jre/
|
|
||||||
bin/
|
|
||||||
java(.exe)
|
|
||||||
lib/
|
|
||||||
...
|
|
||||||
```
|
|
||||||
|
|
||||||
构建后在生产环境可通过 `process.resourcesPath` 访问:
|
|
||||||
`<app>/resources/extraResources/jre/bin/java(.exe)`。
|
|
||||||
|
|
||||||
### 主进程调用示例
|
|
||||||
在 `electron/preload/lifecycle.js` 或你的业务模块中封装 Java 运行工具(开发/生产两种路径):
|
|
||||||
|
|
||||||
```js
|
|
||||||
const path = require('path');
|
|
||||||
const { spawn } = require('child_process');
|
|
||||||
|
|
||||||
function getExtraResourcesDir() {
|
|
||||||
// 开发态:使用项目目录;生产态:使用 asar/resources 目录
|
|
||||||
const isDev = !!process.env.EE_DEV || process.env.NODE_ENV === 'development';
|
|
||||||
return isDev
|
|
||||||
? path.join(process.cwd(), 'build', 'extraResources')
|
|
||||||
: path.join(process.resourcesPath, 'extraResources');
|
|
||||||
}
|
|
||||||
|
|
||||||
function getJavaBinPath() {
|
|
||||||
const extraDir = getExtraResourcesDir();
|
|
||||||
const javaBinName = process.platform === 'win32' ? 'java.exe' : 'java';
|
|
||||||
return path.join(extraDir, 'jre', 'bin', javaBinName);
|
|
||||||
}
|
|
||||||
|
|
||||||
function runJavaJar(jarAbsPath, args = [], options = {}) {
|
|
||||||
const javaPath = getJavaBinPath();
|
|
||||||
const child = spawn(javaPath, ['-jar', jarAbsPath, ...args], {
|
|
||||||
stdio: 'inherit',
|
|
||||||
...options,
|
|
||||||
});
|
|
||||||
return child;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function ensureJavaVersion(logger) {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
const child = spawn(getJavaBinPath(), ['-version']);
|
|
||||||
let out = '';
|
|
||||||
let err = '';
|
|
||||||
child.stdout && child.stdout.on('data', (d) => (out += d.toString()))
|
|
||||||
child.stderr && child.stderr.on('data', (d) => (err += d.toString()))
|
|
||||||
child.on('close', () => {
|
|
||||||
const text = (out + '\n' + err).trim();
|
|
||||||
logger && logger.info('[java] version check:', text);
|
|
||||||
resolve(text.includes('1.8.0'));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { getJavaBinPath, runJavaJar, ensureJavaVersion };
|
|
||||||
```
|
|
||||||
|
|
||||||
在生命周期中调用(示例):
|
|
||||||
|
|
||||||
```js
|
|
||||||
const { logger } = require('ee-core/log');
|
|
||||||
const path = require('path');
|
|
||||||
const { runJavaJar, ensureJavaVersion } = require('./java-runner');
|
|
||||||
|
|
||||||
class Lifecycle {
|
|
||||||
async ready() {
|
|
||||||
const ok = await ensureJavaVersion(logger);
|
|
||||||
if (!ok) {
|
|
||||||
logger.error('[java] 未检测到 JRE 8,请检查 extraResources/jre 是否存在');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async windowReady() {
|
|
||||||
const jarPath = path.join(process.resourcesPath || process.cwd(), 'extraResources', 'tools', 'your-app.jar');
|
|
||||||
// 示例:延后在某业务时机再启动 Java 进程
|
|
||||||
// const proc = runJavaJar(jarPath, ['--arg1', 'value']);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
注意:示例中的 `java-runner` 为上文工具函数文件,实际请按你的项目结构放置。
|
|
||||||
|
|
||||||
### 验证清单
|
|
||||||
- 运行 `jre/bin/java -version` 输出包含 `1.8.0_xxx`。
|
|
||||||
- 若涉及 GUI/字体/打印,验证 AWT/Swing 中文渲染与打印。
|
|
||||||
- 若需 JavaFX,验证 JavaFX Demo 启动。
|
|
||||||
- 若涉及 TLS/HTTPS,验证 SSL 通信正常。
|
|
||||||
|
|
||||||
### 许可与合规
|
|
||||||
- Azul Zulu、Eclipse Temurin(Adoptium)、BellSoft Liberica 的 JRE/JDK 8 发行包均可免费再分发(GPLv2+CE 或厂商许可证)。
|
|
||||||
- 建议在应用的“关于/许可证”中附上所选发行版的许可证链接与致谢。
|
|
||||||
|
|
||||||
### 常见问题
|
|
||||||
1) 是否“阉割”?
|
|
||||||
— 上述 JRE 8 发行版均为标准运行时,通过兼容性测试;JRE 不包含开发者工具属于正常区别,不是删减。
|
|
||||||
|
|
||||||
2) 何时需要 JDK 而不是 JRE?
|
|
||||||
— 需要 `javac` 编译或 `jcmd/jmap` 等诊断工具,或你的 Java 组件依赖 `tools.jar` 时。
|
|
||||||
|
|
||||||
3) 体积如何优化?
|
|
||||||
— 选择 headless(若无 GUI 需求)、去除无用语言/字体包;或改用 JDK 9+ 使用 jlink(不适用于 8)。
|
|
||||||
|
|
||||||
|
|
||||||
436
doc/打包方案对比.md
436
doc/打包方案对比.md
@@ -1,436 +0,0 @@
|
|||||||
# 应用打包方案对比与实现
|
|
||||||
|
|
||||||
本文档详细说明 ElectronEgg 应用的两种打包方案:纯绿色版方案 和 双版本方案。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 方案对比
|
|
||||||
|
|
||||||
| 特性 | 方案一:纯绿色版 | 方案二:双版本打包 |
|
|
||||||
|------|-----------------|-------------------|
|
|
||||||
| **打包产物** | 单个便携版 exe | 安装版 exe + 便携版 exe |
|
|
||||||
| **安装过程** | 无需安装 | 安装版需安装,便携版无需 |
|
|
||||||
| **桌面快捷方式** | 应用内自动创建 | 安装版自动创建,便携版手动或自动 |
|
|
||||||
| **开始菜单** | 无 | 安装版有 |
|
|
||||||
| **卸载程序** | 无(直接删除) | 安装版有 |
|
|
||||||
| **适用场景** | 临时使用、U盘携带 | 正式部署、企业分发 |
|
|
||||||
| **用户体验** | 灵活、轻量 | 专业、完整 |
|
|
||||||
| **打包时间** | 快 | 较慢(打包两次) |
|
|
||||||
| **分发复杂度** | 简单(单文件) | 中等(两个文件) |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 方案一:纯绿色版 + 自动创建快捷方式
|
|
||||||
|
|
||||||
### 特点
|
|
||||||
- ✅ 单个 exe 文件,双击即用
|
|
||||||
- ✅ 首次启动时询问是否创建桌面快捷方式
|
|
||||||
- ✅ 无需安装,无需卸载
|
|
||||||
- ✅ 适合快速分发和临时使用
|
|
||||||
|
|
||||||
### 实现步骤
|
|
||||||
|
|
||||||
#### 1. 修改打包配置
|
|
||||||
|
|
||||||
**文件**:[cmd/builder.json](../cmd/builder.json)
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"productName": "南京灿能工具",
|
|
||||||
"appId": "com.canneng.tool",
|
|
||||||
"copyright": "© 2025 hongawen",
|
|
||||||
"directories": {
|
|
||||||
"output": "out"
|
|
||||||
},
|
|
||||||
"asar": true,
|
|
||||||
"files": [
|
|
||||||
"**/*",
|
|
||||||
"!cmd/",
|
|
||||||
"!data/",
|
|
||||||
"!electron/",
|
|
||||||
"!frontend/",
|
|
||||||
"!logs/",
|
|
||||||
"!out/",
|
|
||||||
"!go/",
|
|
||||||
"!python/"
|
|
||||||
],
|
|
||||||
"extraResources": {
|
|
||||||
"from": "build/extraResources/",
|
|
||||||
"to": "extraResources"
|
|
||||||
},
|
|
||||||
"publish": [
|
|
||||||
{
|
|
||||||
"provider": "generic",
|
|
||||||
"url": "https://your-update-server.com"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"win": {
|
|
||||||
"icon": "build/icons/icon.ico",
|
|
||||||
"artifactName": "${productName}-${os}-${version}-${arch}.${ext}",
|
|
||||||
"target": [
|
|
||||||
{
|
|
||||||
"target": "portable"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 2. 添加自动创建快捷方式功能
|
|
||||||
|
|
||||||
**文件**:[electron/preload/lifecycle.js](../electron/preload/lifecycle.js)
|
|
||||||
|
|
||||||
在 `windowReady()` 钩子中添加以下代码:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const { logger } = require('ee-core/log');
|
|
||||||
const { getConfig } = require('ee-core/config');
|
|
||||||
const { getMainWindow } = require('ee-core/electron');
|
|
||||||
|
|
||||||
class Lifecycle {
|
|
||||||
|
|
||||||
async ready() {
|
|
||||||
logger.info('[lifecycle] ready');
|
|
||||||
}
|
|
||||||
|
|
||||||
async electronAppReady() {
|
|
||||||
logger.info('[lifecycle] electron-app-ready');
|
|
||||||
}
|
|
||||||
|
|
||||||
async windowReady() {
|
|
||||||
logger.info('[lifecycle] window-ready');
|
|
||||||
|
|
||||||
// 延迟加载,无白屏
|
|
||||||
const { windowsOption } = getConfig();
|
|
||||||
if (windowsOption.show == false) {
|
|
||||||
const win = getMainWindow();
|
|
||||||
win.once('ready-to-show', () => {
|
|
||||||
win.show();
|
|
||||||
win.focus();
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// 绿色版自动创建桌面快捷方式
|
|
||||||
await this.createDesktopShortcut();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 为绿色版创建桌面快捷方式
|
|
||||||
*/
|
|
||||||
async createDesktopShortcut() {
|
|
||||||
const { app, dialog, shell } = require('electron');
|
|
||||||
const path = require('path');
|
|
||||||
const fs = require('fs');
|
|
||||||
|
|
||||||
// 判断是否为便携版(绿色版)
|
|
||||||
// 安装版通常在 C:\Program Files 或 AppData\Local\Programs
|
|
||||||
const isPortable = process.platform === 'win32' &&
|
|
||||||
!process.execPath.includes('Program Files') &&
|
|
||||||
!process.execPath.includes('AppData\\Local\\Programs');
|
|
||||||
|
|
||||||
if (!isPortable) {
|
|
||||||
logger.info('[lifecycle] 非便携版,跳过快捷方式创建');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const desktopPath = app.getPath('desktop');
|
|
||||||
const shortcutPath = path.join(desktopPath, '南京灿能工具.lnk');
|
|
||||||
|
|
||||||
// 如果快捷方式已存在,跳过
|
|
||||||
if (fs.existsSync(shortcutPath)) {
|
|
||||||
logger.info('[lifecycle] 桌面快捷方式已存在');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 询问用户是否创建快捷方式
|
|
||||||
const result = await dialog.showMessageBox({
|
|
||||||
type: 'question',
|
|
||||||
buttons: ['创建', '跳过'],
|
|
||||||
defaultId: 0,
|
|
||||||
title: '创建桌面快捷方式',
|
|
||||||
message: '是否在桌面创建快捷方式?',
|
|
||||||
detail: '方便您下次快速启动应用'
|
|
||||||
});
|
|
||||||
|
|
||||||
if (result.response === 0) {
|
|
||||||
// Windows 下创建快捷方式
|
|
||||||
const success = shell.writeShortcutLink(shortcutPath, {
|
|
||||||
target: process.execPath,
|
|
||||||
cwd: path.dirname(process.execPath),
|
|
||||||
description: '南京灿能C端工具',
|
|
||||||
icon: process.execPath,
|
|
||||||
iconIndex: 0
|
|
||||||
});
|
|
||||||
|
|
||||||
if (success) {
|
|
||||||
logger.info('[lifecycle] 桌面快捷方式创建成功');
|
|
||||||
await dialog.showMessageBox({
|
|
||||||
type: 'info',
|
|
||||||
title: '成功',
|
|
||||||
message: '桌面快捷方式已创建',
|
|
||||||
buttons: ['确定']
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
logger.error('[lifecycle] 桌面快捷方式创建失败');
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
logger.info('[lifecycle] 用户跳过创建快捷方式');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('[lifecycle] 创建快捷方式时出错:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async beforeClose() {
|
|
||||||
logger.info('[lifecycle] before-close');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Lifecycle.toString = () => '[class Lifecycle]';
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
Lifecycle
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 3. 打包命令
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run build # 完整构建
|
|
||||||
npm run build-w # 打包 Windows 便携版
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 4. 产物说明
|
|
||||||
|
|
||||||
打包完成后,在 `out/` 目录下会生成:
|
|
||||||
```
|
|
||||||
out/
|
|
||||||
└── 南京灿能工具-win-4.0.0-x64.exe (便携版,约 150-200MB)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 方案二:双版本打包(安装版 + 便携版)
|
|
||||||
|
|
||||||
### 特点
|
|
||||||
- ✅ 提供两种版本供用户选择
|
|
||||||
- ✅ 安装版:专业、完整的安装体验
|
|
||||||
- ✅ 便携版:灵活、轻量,无需安装
|
|
||||||
- ✅ 适合正式产品发布
|
|
||||||
|
|
||||||
### 实现步骤
|
|
||||||
|
|
||||||
#### 1. 修改打包配置
|
|
||||||
|
|
||||||
**文件**:[cmd/builder.json](../cmd/builder.json)
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"productName": "南京灿能工具",
|
|
||||||
"appId": "com.canneng.tool",
|
|
||||||
"copyright": "© 2025 hongawen",
|
|
||||||
"directories": {
|
|
||||||
"output": "out"
|
|
||||||
},
|
|
||||||
"asar": true,
|
|
||||||
"files": [
|
|
||||||
"**/*",
|
|
||||||
"!cmd/",
|
|
||||||
"!data/",
|
|
||||||
"!electron/",
|
|
||||||
"!frontend/",
|
|
||||||
"!logs/",
|
|
||||||
"!out/",
|
|
||||||
"!go/",
|
|
||||||
"!python/"
|
|
||||||
],
|
|
||||||
"extraResources": {
|
|
||||||
"from": "build/extraResources/",
|
|
||||||
"to": "extraResources"
|
|
||||||
},
|
|
||||||
"nsis": {
|
|
||||||
"oneClick": false,
|
|
||||||
"allowElevation": true,
|
|
||||||
"allowToChangeInstallationDirectory": true,
|
|
||||||
"installerIcon": "build/icons/icon.ico",
|
|
||||||
"uninstallerIcon": "build/icons/icon.ico",
|
|
||||||
"installerHeaderIcon": "build/icons/icon.ico",
|
|
||||||
"createDesktopShortcut": true,
|
|
||||||
"createStartMenuShortcut": true,
|
|
||||||
"shortcutName": "南京灿能工具",
|
|
||||||
"artifactName": "${productName}-Setup-${version}.${ext}"
|
|
||||||
},
|
|
||||||
"portable": {
|
|
||||||
"artifactName": "${productName}-Portable-${version}.${ext}"
|
|
||||||
},
|
|
||||||
"publish": [
|
|
||||||
{
|
|
||||||
"provider": "generic",
|
|
||||||
"url": "https://your-update-server.com"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"win": {
|
|
||||||
"icon": "build/icons/icon.ico",
|
|
||||||
"target": [
|
|
||||||
{
|
|
||||||
"target": "nsis",
|
|
||||||
"arch": ["x64"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"target": "portable",
|
|
||||||
"arch": ["x64"]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 2. 便携版快捷方式功能(可选)
|
|
||||||
|
|
||||||
如果希望便携版也能自动创建快捷方式,使用**方案一**中的 `createDesktopShortcut()` 代码。
|
|
||||||
|
|
||||||
#### 3. 打包命令
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run build # 完整构建
|
|
||||||
npm run build-w # 打包两个版本
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 4. 产物说明
|
|
||||||
|
|
||||||
打包完成后,在 `out/` 目录下会生成:
|
|
||||||
```
|
|
||||||
out/
|
|
||||||
├── 南京灿能工具-Setup-4.0.0.exe (安装版,约 150MB)
|
|
||||||
└── 南京灿能工具-Portable-4.0.0.exe (便携版,约 150-200MB)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 5. 版本差异说明
|
|
||||||
|
|
||||||
**安装版 (NSIS)**:
|
|
||||||
- 需要安装到系统(默认 C:\Program Files)
|
|
||||||
- 自动创建桌面快捷方式
|
|
||||||
- 自动创建开始菜单项
|
|
||||||
- 提供卸载程序
|
|
||||||
- 支持自动更新
|
|
||||||
- 适合企业部署、长期使用
|
|
||||||
|
|
||||||
**便携版 (Portable)**:
|
|
||||||
- 单个 exe 文件
|
|
||||||
- 双击直接运行(首次会自解压)
|
|
||||||
- 无需安装,无需卸载
|
|
||||||
- 可放在 U 盘随身携带
|
|
||||||
- 适合临时使用、测试环境
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 快捷方式创建原理(技术细节)
|
|
||||||
|
|
||||||
### Windows 快捷方式 (.lnk)
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
shell.writeShortcutLink(shortcutPath, {
|
|
||||||
target: process.execPath, // 目标程序路径
|
|
||||||
cwd: path.dirname(process.execPath), // 工作目录
|
|
||||||
description: '应用描述', // 快捷方式描述
|
|
||||||
icon: process.execPath, // 图标路径
|
|
||||||
iconIndex: 0, // 图标索引
|
|
||||||
args: '', // 启动参数(可选)
|
|
||||||
appUserModelId: 'com.app.id' // Windows 应用 ID(可选)
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
### 判断是否为便携版
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const isPortable = process.platform === 'win32' &&
|
|
||||||
!process.execPath.includes('Program Files') &&
|
|
||||||
!process.execPath.includes('AppData\\Local\\Programs');
|
|
||||||
```
|
|
||||||
|
|
||||||
**原理**:
|
|
||||||
- 安装版通常安装在 `C:\Program Files\YourApp\`
|
|
||||||
- 或者 `C:\Users\用户名\AppData\Local\Programs\YourApp\`
|
|
||||||
- 便携版可以在任意位置运行
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 推荐配置
|
|
||||||
|
|
||||||
### 企业级应用(推荐方案二)
|
|
||||||
```
|
|
||||||
✅ 提供两个版本
|
|
||||||
✅ 主推安装版(专业形象)
|
|
||||||
✅ 提供便携版作为备选
|
|
||||||
```
|
|
||||||
|
|
||||||
### 轻量工具(推荐方案一)
|
|
||||||
```
|
|
||||||
✅ 只提供便携版
|
|
||||||
✅ 应用内自动创建快捷方式
|
|
||||||
✅ 简化分发流程
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 常见问题
|
|
||||||
|
|
||||||
### Q1: 便携版首次启动为什么慢?
|
|
||||||
**A**: 便携版是自解压程序,首次运行需要解压资源到临时目录(约 3-5 秒)。后续启动会快很多。
|
|
||||||
|
|
||||||
### Q2: 便携版数据存储在哪里?
|
|
||||||
**A**:
|
|
||||||
- 用户数据:`C:\Users\用户名\AppData\Roaming\你的appId\`
|
|
||||||
- 临时文件:`C:\Users\用户名\AppData\Local\Temp\`
|
|
||||||
|
|
||||||
### Q3: 如何让便携版也支持自动更新?
|
|
||||||
**A**: 需要配置 `electron-updater`,但便携版更新体验不如安装版。建议:
|
|
||||||
- 安装版:使用自动更新
|
|
||||||
- 便携版:提示用户下载新版本
|
|
||||||
|
|
||||||
### Q4: 可以同时运行两个版本吗?
|
|
||||||
**A**: 不建议。虽然技术上可行,但会导致数据冲突(共享同一个 userData 目录)。
|
|
||||||
|
|
||||||
### Q5: 如何自定义快捷方式图标?
|
|
||||||
**A**: 在 `build/icons/` 目录放置 `.ico` 文件,并在 `builder.json` 中配置:
|
|
||||||
```json
|
|
||||||
"win": {
|
|
||||||
"icon": "build/icons/custom-icon.ico"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 测试检查清单
|
|
||||||
|
|
||||||
打包完成后,请进行以下测试:
|
|
||||||
|
|
||||||
### 安装版测试
|
|
||||||
- [ ] 安装到默认路径成功
|
|
||||||
- [ ] 安装到自定义路径成功
|
|
||||||
- [ ] 桌面快捷方式正常
|
|
||||||
- [ ] 开始菜单项正常
|
|
||||||
- [ ] 应用启动正常
|
|
||||||
- [ ] 卸载程序正常
|
|
||||||
|
|
||||||
### 便携版测试
|
|
||||||
- [ ] 双击 exe 正常启动
|
|
||||||
- [ ] 首次启动自动创建快捷方式(如已实现)
|
|
||||||
- [ ] 桌面快捷方式可用
|
|
||||||
- [ ] 应用功能正常
|
|
||||||
- [ ] 关闭后再次启动正常
|
|
||||||
- [ ] 可移动到其他目录运行
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 参考资源
|
|
||||||
|
|
||||||
- electron-builder 官方文档: https://www.electron.build/
|
|
||||||
- NSIS 配置: https://www.electron.build/configuration/nsis
|
|
||||||
- Portable 配置: https://www.electron.build/configuration/portable
|
|
||||||
- Electron shell API: https://www.electronjs.org/docs/latest/api/shell
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
*文档创建时间: 2025-10-14*
|
|
||||||
*作者: hongawen*
|
|
||||||
@@ -25,7 +25,7 @@ module.exports = () => {
|
|||||||
},
|
},
|
||||||
frame: true,
|
frame: true,
|
||||||
show: false, // 初始不显示,等待服务启动完成后再显示
|
show: false, // 初始不显示,等待服务启动完成后再显示
|
||||||
icon: path.join(getBaseDir(), 'public', 'images', 'logo-32.png'),
|
icon: path.join(getBaseDir(), 'public', 'images', 'icon.png'),
|
||||||
},
|
},
|
||||||
logger: {
|
logger: {
|
||||||
level: 'INFO',
|
level: 'INFO',
|
||||||
|
|||||||
@@ -1,75 +0,0 @@
|
|||||||
const path = require('path');
|
|
||||||
|
|
||||||
// 动态获取 scripts 目录路径
|
|
||||||
function getScriptsPath(scriptName) {
|
|
||||||
// 开发环境
|
|
||||||
const devPath = path.join(__dirname, '../../scripts', scriptName);
|
|
||||||
// 生产环境(打包后)
|
|
||||||
const prodPath = path.join(process.resourcesPath, 'scripts', scriptName);
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 先尝试开发环境路径
|
|
||||||
require.resolve(devPath);
|
|
||||||
return devPath;
|
|
||||||
} catch (e) {
|
|
||||||
// 如果开发环境路径不存在,使用生产环境路径
|
|
||||||
return prodPath;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 延迟加载 MySQLManager
|
|
||||||
let MySQLManager = null;
|
|
||||||
function getMySQLManager() {
|
|
||||||
if (!MySQLManager) {
|
|
||||||
MySQLManager = require(getScriptsPath('start-mysql'));
|
|
||||||
}
|
|
||||||
return MySQLManager;
|
|
||||||
}
|
|
||||||
|
|
||||||
class MySQLController {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 启动MySQL服务
|
|
||||||
*/
|
|
||||||
async start() {
|
|
||||||
try {
|
|
||||||
const MySQLManagerClass = getMySQLManager();
|
|
||||||
const mysqlManager = new MySQLManagerClass();
|
|
||||||
await mysqlManager.start();
|
|
||||||
return { success: true, message: 'MySQL started successfully' };
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, message: error.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 停止MySQL服务
|
|
||||||
*/
|
|
||||||
async stop() {
|
|
||||||
try {
|
|
||||||
const MySQLManagerClass = getMySQLManager();
|
|
||||||
const mysqlManager = new MySQLManagerClass();
|
|
||||||
await mysqlManager.stop();
|
|
||||||
return { success: true, message: 'MySQL stopped successfully' };
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, message: error.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取MySQL连接配置
|
|
||||||
*/
|
|
||||||
async getConnectionConfig() {
|
|
||||||
try {
|
|
||||||
const MySQLManagerClass = getMySQLManager();
|
|
||||||
const mysqlManager = new MySQLManagerClass();
|
|
||||||
const config = mysqlManager.getConnectionConfig();
|
|
||||||
return { success: true, data: config };
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, message: error.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
MySQLController.toString = () => '[class MySQLController]';
|
|
||||||
module.exports = MySQLController;
|
|
||||||
197
electron/main.js
197
electron/main.js
@@ -1,27 +1,127 @@
|
|||||||
const { ElectronEgg } = require('ee-core');
|
const { ElectronEgg } = require('ee-core');
|
||||||
const { app, Menu, ipcMain } = require('electron');
|
const { app, Menu, ipcMain, Tray, dialog, BrowserWindow } = require('electron');
|
||||||
|
const path = require('path');
|
||||||
const lifecycle = require('./preload/lifecycle');
|
const lifecycle = require('./preload/lifecycle');
|
||||||
const { preload } = require('./preload');
|
const { preload } = require('./preload');
|
||||||
|
|
||||||
// new app
|
// new app
|
||||||
const electronApp = new ElectronEgg();
|
const electronApp = new ElectronEgg();
|
||||||
|
|
||||||
|
// 全局变量
|
||||||
|
let tray = null;
|
||||||
|
let isQuitting = false;
|
||||||
|
|
||||||
|
// 创建系统托盘
|
||||||
|
function createTray() {
|
||||||
|
try {
|
||||||
|
// 开发环境和生产环境的图标路径
|
||||||
|
const isDev = !process.resourcesPath;
|
||||||
|
const iconPath = isDev
|
||||||
|
? path.join(__dirname, '..', 'public', 'images', 'tray.png')
|
||||||
|
: path.join(process.resourcesPath, 'app.asar.unpacked', 'public', 'images', 'tray.png');
|
||||||
|
|
||||||
|
console.log('[Tray] Icon path:', iconPath);
|
||||||
|
|
||||||
|
// 检查图标文件是否存在
|
||||||
|
const fs = require('fs');
|
||||||
|
if (!fs.existsSync(iconPath)) {
|
||||||
|
console.error('[Tray] Icon file not found:', iconPath);
|
||||||
|
// 如果找不到,尝试使用备用路径(主图标)
|
||||||
|
const fallbackIcon = isDev
|
||||||
|
? path.join(__dirname, '..', 'public', 'images', 'icon.png')
|
||||||
|
: path.join(process.resourcesPath, 'app.asar.unpacked', 'public', 'images', 'icon.png');
|
||||||
|
|
||||||
|
if (fs.existsSync(fallbackIcon)) {
|
||||||
|
console.log('[Tray] Using fallback icon:', fallbackIcon);
|
||||||
|
tray = new Tray(fallbackIcon);
|
||||||
|
} else {
|
||||||
|
console.error('[Tray] No icon available, tray not created');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tray = new Tray(iconPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
tray.setToolTip('NPQS-9100自动检测平台');
|
||||||
|
console.log('[Tray] Tray created successfully');
|
||||||
|
|
||||||
|
// 创建托盘菜单
|
||||||
|
const contextMenu = Menu.buildFromTemplate([
|
||||||
|
{
|
||||||
|
label: '显示主窗口',
|
||||||
|
click: () => {
|
||||||
|
const mainWindow = BrowserWindow.getAllWindows()[0];
|
||||||
|
if (mainWindow) {
|
||||||
|
if (mainWindow.isMinimized()) {
|
||||||
|
mainWindow.restore();
|
||||||
|
}
|
||||||
|
mainWindow.show();
|
||||||
|
mainWindow.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: '退出',
|
||||||
|
click: async () => {
|
||||||
|
// 弹出确认对话框
|
||||||
|
const { response } = await dialog.showMessageBox({
|
||||||
|
type: 'question',
|
||||||
|
title: '退出确认',
|
||||||
|
message: '确定退出应用吗?',
|
||||||
|
buttons: ['取消', '确定退出'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 0
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response === 1) {
|
||||||
|
// 用户点击了"确定退出"
|
||||||
|
isQuitting = true;
|
||||||
|
|
||||||
|
// 获取主窗口
|
||||||
|
const mainWindow = BrowserWindow.getAllWindows()[0];
|
||||||
|
|
||||||
|
// 移除所有 close 监听器,避免阻止关闭
|
||||||
|
if (mainWindow) {
|
||||||
|
mainWindow.removeAllListeners('close');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行清理
|
||||||
|
await lifecycle.cleanup();
|
||||||
|
|
||||||
|
// 退出应用
|
||||||
|
app.quit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
|
||||||
|
tray.setContextMenu(contextMenu);
|
||||||
|
|
||||||
|
// 双击托盘图标显示窗口
|
||||||
|
tray.on('double-click', () => {
|
||||||
|
const mainWindow = BrowserWindow.getAllWindows()[0];
|
||||||
|
if (mainWindow) {
|
||||||
|
if (mainWindow.isMinimized()) {
|
||||||
|
mainWindow.restore();
|
||||||
|
}
|
||||||
|
mainWindow.show();
|
||||||
|
mainWindow.focus();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[Tray] Failed to create tray:', error);
|
||||||
|
tray = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 创建应用菜单
|
// 创建应用菜单
|
||||||
function createApplicationMenu() {
|
function createApplicationMenu() {
|
||||||
const template = [
|
const template = [
|
||||||
{
|
{
|
||||||
label: '查看',
|
label: '查看',
|
||||||
submenu: [
|
submenu: [
|
||||||
{
|
|
||||||
label: '显示/隐藏服务日志',
|
|
||||||
accelerator: 'F12',
|
|
||||||
click: () => {
|
|
||||||
if (lifecycle.logWindowManager) {
|
|
||||||
lifecycle.logWindowManager.toggle();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{ type: 'separator' },
|
|
||||||
{ role: 'reload', label: '刷新' },
|
{ role: 'reload', label: '刷新' },
|
||||||
{ role: 'forceReload', label: '强制刷新' },
|
{ role: 'forceReload', label: '强制刷新' },
|
||||||
{ type: 'separator' },
|
{ type: 'separator' },
|
||||||
@@ -71,14 +171,87 @@ ipcMain.handle('toggle-log-window', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 检查是否正在退出
|
||||||
|
ipcMain.handle('is-quitting', () => {
|
||||||
|
return isQuitting;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 处理单实例:当尝试启动第二个实例时,聚焦已有窗口
|
||||||
|
app.on('second-instance', (event, commandLine, workingDirectory) => {
|
||||||
|
console.log('[Main] Second instance detected, focusing main window...');
|
||||||
|
|
||||||
|
// 获取主窗口
|
||||||
|
const mainWindow = BrowserWindow.getAllWindows().find(win => {
|
||||||
|
return win.getTitle().includes('NPQS') || win.getTitle().includes('检测平台');
|
||||||
|
});
|
||||||
|
|
||||||
|
if (mainWindow) {
|
||||||
|
// 如果窗口最小化,恢复它
|
||||||
|
if (mainWindow.isMinimized()) {
|
||||||
|
mainWindow.restore();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果窗口隐藏,显示它
|
||||||
|
if (!mainWindow.isVisible()) {
|
||||||
|
mainWindow.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 聚焦窗口
|
||||||
|
mainWindow.focus();
|
||||||
|
|
||||||
|
console.log('[Main] Main window focused');
|
||||||
|
} else {
|
||||||
|
console.warn('[Main] Main window not found');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 监听应用退出前事件(确保清理托盘)
|
||||||
|
app.on('before-quit', () => {
|
||||||
|
console.log('[Main] App before-quit, destroying tray...');
|
||||||
|
|
||||||
|
// 销毁托盘图标
|
||||||
|
if (tray && !tray.isDestroyed()) {
|
||||||
|
tray.destroy();
|
||||||
|
tray = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 监听 will-quit 事件(强制退出时)
|
||||||
|
app.on('will-quit', () => {
|
||||||
|
console.log('[Main] App will-quit');
|
||||||
|
|
||||||
|
// 确保托盘被销毁
|
||||||
|
if (tray && !tray.isDestroyed()) {
|
||||||
|
tray.destroy();
|
||||||
|
tray = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// register lifecycle (绑定 this 上下文)
|
// register lifecycle (绑定 this 上下文)
|
||||||
electronApp.register("ready", lifecycle.ready.bind(lifecycle));
|
electronApp.register("ready", lifecycle.ready.bind(lifecycle));
|
||||||
electronApp.register("electron-app-ready", () => {
|
electronApp.register("electron-app-ready", () => {
|
||||||
lifecycle.electronAppReady.bind(lifecycle)();
|
lifecycle.electronAppReady.bind(lifecycle)();
|
||||||
createApplicationMenu();
|
createApplicationMenu();
|
||||||
|
createTray(); // 创建系统托盘
|
||||||
});
|
});
|
||||||
electronApp.register("window-ready", lifecycle.windowReady.bind(lifecycle));
|
electronApp.register("window-ready", lifecycle.windowReady.bind(lifecycle));
|
||||||
electronApp.register("before-close", lifecycle.beforeClose.bind(lifecycle));
|
electronApp.register("before-close", async () => {
|
||||||
|
// 如果不是真正退出,不执行清理
|
||||||
|
if (!isQuitting) {
|
||||||
|
console.log('[Main] Not quitting, skip cleanup');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('[Main] Quitting, execute cleanup');
|
||||||
|
|
||||||
|
// 销毁托盘图标
|
||||||
|
if (tray && !tray.isDestroyed()) {
|
||||||
|
tray.destroy();
|
||||||
|
tray = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
await lifecycle.beforeClose.bind(lifecycle)();
|
||||||
|
});
|
||||||
|
|
||||||
// register preload
|
// register preload
|
||||||
electronApp.register("preload", preload);
|
electronApp.register("preload", preload);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ const path = require('path');
|
|||||||
const { logger } = require('ee-core/log');
|
const { logger } = require('ee-core/log');
|
||||||
const { getConfig } = require('ee-core/config');
|
const { getConfig } = require('ee-core/config');
|
||||||
const { getMainWindow } = require('ee-core/electron');
|
const { getMainWindow } = require('ee-core/electron');
|
||||||
const ps = require('ee-core/ps');
|
const { getBaseDir } = require('ee-core/ps');
|
||||||
const { app } = require('electron');
|
const { app } = require('electron');
|
||||||
|
|
||||||
// 动态获取 scripts 目录路径
|
// 动态获取 scripts 目录路径
|
||||||
@@ -12,7 +12,8 @@ function getScriptsPath(scriptName) {
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
|
|
||||||
// 判断是否是打包后的环境
|
// 判断是否是打包后的环境
|
||||||
const isProd = process.resourcesPath && process.resourcesPath.includes('win-unpacked');
|
// 只要 process.resourcesPath 存在,就是打包后的环境(无论在哪个目录)
|
||||||
|
const isProd = !!process.resourcesPath;
|
||||||
|
|
||||||
if (isProd) {
|
if (isProd) {
|
||||||
// 生产环境(打包后):从 resources 目录
|
// 生产环境(打包后):从 resources 目录
|
||||||
@@ -44,11 +45,11 @@ function getScriptsPath(scriptName) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 延迟加载 scripts
|
// 延迟加载 scripts
|
||||||
let MySQLManager, JavaRunner, ConfigGenerator, PortChecker, StartupManager, LogWindowManager;
|
let MySQLServiceManager, JavaRunner, ConfigGenerator, PortChecker, StartupManager, LogWindowManager;
|
||||||
|
|
||||||
function loadScripts() {
|
function loadScripts() {
|
||||||
if (!MySQLManager) {
|
if (!MySQLServiceManager) {
|
||||||
MySQLManager = require(getScriptsPath('start-mysql'));
|
MySQLServiceManager = require(getScriptsPath('mysql-service-manager'));
|
||||||
JavaRunner = require(getScriptsPath('java-runner'));
|
JavaRunner = require(getScriptsPath('java-runner'));
|
||||||
ConfigGenerator = require(getScriptsPath('config-generator'));
|
ConfigGenerator = require(getScriptsPath('config-generator'));
|
||||||
PortChecker = require(getScriptsPath('port-checker'));
|
PortChecker = require(getScriptsPath('port-checker'));
|
||||||
@@ -59,13 +60,14 @@ function loadScripts() {
|
|||||||
|
|
||||||
class Lifecycle {
|
class Lifecycle {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.mysqlManager = null;
|
this.mysqlServiceManager = null;
|
||||||
this.javaRunner = null;
|
this.javaRunner = null;
|
||||||
this.startupManager = null;
|
this.startupManager = null;
|
||||||
this.logWindowManager = null;
|
this.logWindowManager = null;
|
||||||
this.mysqlPort = null;
|
this.mysqlPort = null;
|
||||||
this.javaPort = null;
|
this.javaPort = null;
|
||||||
this.autoRefreshTimer = null;
|
this.autoRefreshTimer = null;
|
||||||
|
this.isRestartingForAdmin = false; // 权限提升重启标记
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -74,76 +76,73 @@ class Lifecycle {
|
|||||||
async ready() {
|
async ready() {
|
||||||
logger.info('[lifecycle] ready');
|
logger.info('[lifecycle] ready');
|
||||||
// 延迟加载 scripts
|
// 延迟加载 scripts
|
||||||
if (ps.isProd()) {
|
|
||||||
loadScripts();
|
loadScripts();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 完整的应用启动流程
|
* 完整的应用启动流程
|
||||||
*/
|
*/
|
||||||
async startApplication() {
|
async startApplication() {
|
||||||
|
this.logWindowManager.addLog('system', '▶ 步骤1: 开始启动流程...');
|
||||||
|
logger.info('[lifecycle] Starting application...');
|
||||||
|
|
||||||
|
this.logWindowManager.addLog('system', '▶ 步骤2: 加载配置信息...');
|
||||||
const config = getConfig();
|
const config = getConfig();
|
||||||
|
logger.info('[lifecycle] Config loaded:', JSON.stringify(config));
|
||||||
|
|
||||||
// 步骤1: 初始化
|
// 步骤1: 初始化
|
||||||
|
this.logWindowManager.addLog('system', '▶ 步骤3: 初始化启动管理器...');
|
||||||
this.startupManager.updateProgress('init');
|
this.startupManager.updateProgress('init');
|
||||||
await this.sleep(500);
|
await this.sleep(500);
|
||||||
|
|
||||||
// 步骤2: 检测 MySQL 端口
|
// 步骤2-4: 确保 MySQL 服务运行
|
||||||
this.startupManager.updateProgress('check-mysql-port');
|
this.logWindowManager.addLog('system', '▶ 步骤4: 检查 MySQL 配置...');
|
||||||
this.logWindowManager.addLog('system', '正在检测可用的 MySQL 端口(从3306开始)...');
|
logger.info('[lifecycle] MySQL config check - enable:', config.mysql?.enable, 'autoStart:', config.mysql?.autoStart);
|
||||||
|
|
||||||
this.mysqlPort = await PortChecker.findAvailablePort(3306, 100);
|
|
||||||
|
|
||||||
if (this.mysqlPort === -1) {
|
|
||||||
this.logWindowManager.addLog('error', 'MySQL 端口检测失败:3306-3405 全部被占用');
|
|
||||||
throw new Error('无法找到可用的 MySQL 端口(3306-3405 全部被占用)');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.mysqlPort !== 3306) {
|
|
||||||
this.logWindowManager.addLog('warn', `MySQL 默认端口 3306 已被占用,自动切换到端口: ${this.mysqlPort}`);
|
|
||||||
} else {
|
|
||||||
this.logWindowManager.addLog('success', `MySQL 将使用默认端口: ${this.mysqlPort}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info(`[lifecycle] MySQL will use port: ${this.mysqlPort}`);
|
|
||||||
this.startupManager.updateProgress('check-mysql-port', { mysqlPort: this.mysqlPort });
|
|
||||||
await this.sleep(500);
|
|
||||||
|
|
||||||
// 步骤3: 启动 MySQL
|
|
||||||
if (config.mysql && config.mysql.enable && config.mysql.autoStart) {
|
if (config.mysql && config.mysql.enable && config.mysql.autoStart) {
|
||||||
this.startupManager.updateProgress('start-mysql', { mysqlPort: this.mysqlPort });
|
this.startupManager.updateProgress('check-mysql-port');
|
||||||
this.logWindowManager.addLog('mysql', `正在启动 MySQL,端口: ${this.mysqlPort}`);
|
this.logWindowManager.addLog('system', '▶ 步骤5: 启动 MySQL 服务管理器...');
|
||||||
|
|
||||||
this.mysqlManager = new MySQLManager();
|
this.mysqlServiceManager = new MySQLServiceManager(this.logWindowManager);
|
||||||
|
this.logWindowManager.addLog('system', '正在检查 MySQL 服务状态...');
|
||||||
|
|
||||||
// 监听 MySQL 输出
|
try {
|
||||||
const actualPort = await this.mysqlManager.start(this.mysqlPort);
|
// 使用服务管理器确保MySQL服务运行
|
||||||
this.setupMySQLLogging(this.mysqlManager.process);
|
this.logWindowManager.addLog('system', '▶ 步骤6: 确保 MySQL 服务运行中...');
|
||||||
|
this.mysqlPort = await this.mysqlServiceManager.ensureServiceRunning(
|
||||||
|
PortChecker.findAvailablePort.bind(PortChecker),
|
||||||
|
PortChecker.waitForPort.bind(PortChecker)
|
||||||
|
);
|
||||||
|
|
||||||
logger.info(`[lifecycle] MySQL started on port: ${actualPort}`);
|
logger.info(`[lifecycle] MySQL service running on port: ${this.mysqlPort}`);
|
||||||
this.logWindowManager.addLog('success', `MySQL 已启动,端口: ${actualPort}`);
|
this.logWindowManager.addLog('success', `✓ MySQL 服务已就绪,端口: ${this.mysqlPort}`);
|
||||||
|
this.startupManager.updateProgress('wait-mysql', { mysqlPort: this.mysqlPort });
|
||||||
// 步骤4: 等待 MySQL 就绪
|
|
||||||
this.startupManager.updateProgress('wait-mysql', { mysqlPort: actualPort });
|
|
||||||
this.logWindowManager.addLog('mysql', '等待 MySQL 就绪...');
|
|
||||||
|
|
||||||
const mysqlReady = await PortChecker.waitForPort(actualPort, 30000);
|
|
||||||
|
|
||||||
if (!mysqlReady) {
|
|
||||||
this.logWindowManager.addLog('error', `MySQL 启动超时(端口 ${actualPort} 未响应)`);
|
|
||||||
throw new Error(`MySQL 启动超时(端口 ${actualPort} 未响应)`);
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info('[lifecycle] MySQL is ready');
|
|
||||||
this.logWindowManager.addLog('success', 'MySQL 已就绪!');
|
|
||||||
await this.sleep(500);
|
await this.sleep(500);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('[lifecycle] MySQL service error:', error);
|
||||||
|
this.logWindowManager.addLog('error', `MySQL 服务错误: ${error.message}`);
|
||||||
|
// 检查是否是权限问题
|
||||||
|
if (error.message && (error.message.includes('administrator') || error.message.includes('Denied'))) {
|
||||||
|
logger.error('[lifecycle] Need administrator privileges');
|
||||||
|
this.logWindowManager.addLog('error', '检测到需要管理员权限来安装 MySQL 服务');
|
||||||
|
this.logWindowManager.addLog('system', '应用将自动请求管理员权限并重启...');
|
||||||
|
|
||||||
|
// 等待用户看清日志
|
||||||
|
await this.sleep(2000);
|
||||||
|
|
||||||
|
// 自动以管理员身份重启应用
|
||||||
|
await this.restartAsAdmin();
|
||||||
|
|
||||||
|
// 退出当前实例
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 步骤5: 检测 Java 端口
|
// 步骤5: 检测 Java 端口
|
||||||
|
this.logWindowManager.addLog('system', '▶ 步骤7: 检测可用的 Java 端口(从18092开始)...');
|
||||||
this.startupManager.updateProgress('check-java-port', { mysqlPort: this.mysqlPort });
|
this.startupManager.updateProgress('check-java-port', { mysqlPort: this.mysqlPort });
|
||||||
this.logWindowManager.addLog('system', '正在检测可用的 Java 端口(从18092开始)...');
|
|
||||||
|
|
||||||
this.javaPort = await PortChecker.findAvailablePort(18092, 100);
|
this.javaPort = await PortChecker.findAvailablePort(18092, 100);
|
||||||
|
|
||||||
@@ -152,13 +151,30 @@ class Lifecycle {
|
|||||||
throw new Error('无法找到可用的后端服务端口(18092-18191 全部被占用)');
|
throw new Error('无法找到可用的后端服务端口(18092-18191 全部被占用)');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 步骤5.5: 检测 WebSocket 端口
|
||||||
|
this.logWindowManager.addLog('system', '▶ 步骤8: 检测可用的 WebSocket 端口(从7777开始)...');
|
||||||
|
|
||||||
|
this.websocketPort = await PortChecker.findAvailablePort(7777, 100);
|
||||||
|
|
||||||
|
if (this.websocketPort === -1) {
|
||||||
|
this.logWindowManager.addLog('error', 'WebSocket 端口检测失败:7777-7876 全部被占用');
|
||||||
|
throw new Error('无法找到可用的 WebSocket 端口(7777-7876 全部被占用)');
|
||||||
|
}
|
||||||
|
|
||||||
if (this.javaPort !== 18092) {
|
if (this.javaPort !== 18092) {
|
||||||
this.logWindowManager.addLog('warn', `Java 默认端口 18092 已被占用,自动切换到端口: ${this.javaPort}`);
|
this.logWindowManager.addLog('warn', `⚠ Java 默认端口 18092 已被占用,自动切换到端口: ${this.javaPort}`);
|
||||||
} else {
|
} else {
|
||||||
this.logWindowManager.addLog('success', `Java 将使用默认端口: ${this.javaPort}`);
|
this.logWindowManager.addLog('success', `✓ Java 将使用默认端口: ${this.javaPort}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.websocketPort !== 7777) {
|
||||||
|
this.logWindowManager.addLog('warn', `⚠ WebSocket 默认端口 7777 已被占用,自动切换到端口: ${this.websocketPort}`);
|
||||||
|
} else {
|
||||||
|
this.logWindowManager.addLog('success', `✓ WebSocket 将使用默认端口: ${this.websocketPort}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info(`[lifecycle] Spring Boot will use port: ${this.javaPort}`);
|
logger.info(`[lifecycle] Spring Boot will use port: ${this.javaPort}`);
|
||||||
|
logger.info(`[lifecycle] WebSocket will use port: ${this.websocketPort}`);
|
||||||
this.startupManager.updateProgress('check-java-port', {
|
this.startupManager.updateProgress('check-java-port', {
|
||||||
mysqlPort: this.mysqlPort,
|
mysqlPort: this.mysqlPort,
|
||||||
javaPort: this.javaPort
|
javaPort: this.javaPort
|
||||||
@@ -166,28 +182,35 @@ class Lifecycle {
|
|||||||
await this.sleep(500);
|
await this.sleep(500);
|
||||||
|
|
||||||
// 步骤6: 生成配置文件
|
// 步骤6: 生成配置文件
|
||||||
|
this.logWindowManager.addLog('system', '▶ 步骤9: 生成 Spring Boot 配置文件...');
|
||||||
this.startupManager.updateProgress('generate-config', {
|
this.startupManager.updateProgress('generate-config', {
|
||||||
mysqlPort: this.mysqlPort,
|
mysqlPort: this.mysqlPort,
|
||||||
javaPort: this.javaPort
|
javaPort: this.javaPort,
|
||||||
|
websocketPort: this.websocketPort
|
||||||
});
|
});
|
||||||
|
|
||||||
const configGenerator = new ConfigGenerator();
|
const configGenerator = new ConfigGenerator();
|
||||||
const { configPath, dataPath } = await configGenerator.generateConfig({
|
const { configPath, dataPath } = await configGenerator.generateConfig({
|
||||||
mysqlPort: this.mysqlPort,
|
mysqlPort: this.mysqlPort,
|
||||||
javaPort: this.javaPort,
|
javaPort: this.javaPort,
|
||||||
|
websocketPort: this.websocketPort,
|
||||||
mysqlPassword: 'njcnpqs'
|
mysqlPassword: 'njcnpqs'
|
||||||
});
|
});
|
||||||
|
|
||||||
logger.info(`[lifecycle] Configuration generated at: ${configPath}`);
|
logger.info(`[lifecycle] Configuration generated at: ${configPath}`);
|
||||||
logger.info(`[lifecycle] Data directory: ${dataPath}`);
|
logger.info(`[lifecycle] Data directory: ${dataPath}`);
|
||||||
|
this.logWindowManager.addLog('success', `✓ 配置文件已生成: ${configPath}`);
|
||||||
|
this.logWindowManager.addLog('system', ` 数据目录: ${dataPath}`);
|
||||||
this.startupManager.updateProgress('generate-config', {
|
this.startupManager.updateProgress('generate-config', {
|
||||||
mysqlPort: this.mysqlPort,
|
mysqlPort: this.mysqlPort,
|
||||||
javaPort: this.javaPort,
|
javaPort: this.javaPort,
|
||||||
|
websocketPort: this.websocketPort,
|
||||||
dataPath: dataPath
|
dataPath: dataPath
|
||||||
});
|
});
|
||||||
await this.sleep(500);
|
await this.sleep(500);
|
||||||
|
|
||||||
// 步骤7: 启动 Spring Boot
|
// 步骤7: 启动 Spring Boot
|
||||||
|
this.logWindowManager.addLog('system', '▶ 步骤10: 启动 Spring Boot 应用...');
|
||||||
this.startupManager.updateProgress('start-java', {
|
this.startupManager.updateProgress('start-java', {
|
||||||
mysqlPort: this.mysqlPort,
|
mysqlPort: this.mysqlPort,
|
||||||
javaPort: this.javaPort,
|
javaPort: this.javaPort,
|
||||||
@@ -197,6 +220,7 @@ class Lifecycle {
|
|||||||
await this.startSpringBoot(configPath);
|
await this.startSpringBoot(configPath);
|
||||||
|
|
||||||
// 步骤8: 等待 Spring Boot 就绪
|
// 步骤8: 等待 Spring Boot 就绪
|
||||||
|
this.logWindowManager.addLog('system', '▶ 步骤11: 等待 Spring Boot 就绪(最多60秒)...');
|
||||||
this.startupManager.updateProgress('wait-java', {
|
this.startupManager.updateProgress('wait-java', {
|
||||||
mysqlPort: this.mysqlPort,
|
mysqlPort: this.mysqlPort,
|
||||||
javaPort: this.javaPort,
|
javaPort: this.javaPort,
|
||||||
@@ -207,13 +231,16 @@ class Lifecycle {
|
|||||||
|
|
||||||
if (!javaReady) {
|
if (!javaReady) {
|
||||||
logger.warn(`[lifecycle] Spring Boot 启动超时,但继续启动应用`);
|
logger.warn(`[lifecycle] Spring Boot 启动超时,但继续启动应用`);
|
||||||
|
this.logWindowManager.addLog('warn', '⚠ Spring Boot 启动超时(60秒),但应用将继续启动');
|
||||||
} else {
|
} else {
|
||||||
logger.info('[lifecycle] Spring Boot is ready');
|
logger.info('[lifecycle] Spring Boot is ready');
|
||||||
|
this.logWindowManager.addLog('success', '✓ Spring Boot 启动成功!');
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.sleep(1000);
|
await this.sleep(1000);
|
||||||
|
|
||||||
// 步骤9: 完成
|
// 步骤9: 完成
|
||||||
|
this.logWindowManager.addLog('system', '▶ 步骤12: 启动完成,准备显示主窗口...');
|
||||||
this.startupManager.updateProgress('done', {
|
this.startupManager.updateProgress('done', {
|
||||||
mysqlPort: this.mysqlPort,
|
mysqlPort: this.mysqlPort,
|
||||||
javaPort: this.javaPort,
|
javaPort: this.javaPort,
|
||||||
@@ -225,6 +252,7 @@ class Lifecycle {
|
|||||||
this.logWindowManager.addLog('success', '✓ NPQS9100 启动完成!所有服务正常运行');
|
this.logWindowManager.addLog('success', '✓ NPQS9100 启动完成!所有服务正常运行');
|
||||||
this.logWindowManager.addLog('system', `✓ MySQL 端口: ${this.mysqlPort}`);
|
this.logWindowManager.addLog('system', `✓ MySQL 端口: ${this.mysqlPort}`);
|
||||||
this.logWindowManager.addLog('system', `✓ Java 端口: ${this.javaPort}`);
|
this.logWindowManager.addLog('system', `✓ Java 端口: ${this.javaPort}`);
|
||||||
|
this.logWindowManager.addLog('system', `✓ WebSocket 端口: ${this.websocketPort}`);
|
||||||
this.logWindowManager.addLog('system', `✓ 数据目录: ${dataPath}`);
|
this.logWindowManager.addLog('system', `✓ 数据目录: ${dataPath}`);
|
||||||
this.logWindowManager.addLog('system', '='.repeat(60));
|
this.logWindowManager.addLog('system', '='.repeat(60));
|
||||||
this.logWindowManager.addLog('system', '应用即将启动...');
|
this.logWindowManager.addLog('system', '应用即将启动...');
|
||||||
@@ -241,9 +269,36 @@ class Lifecycle {
|
|||||||
win.focus();
|
win.focus();
|
||||||
|
|
||||||
// 添加主窗口关闭事件监听
|
// 添加主窗口关闭事件监听
|
||||||
win.on('close', async () => {
|
win.on('close', async (event) => {
|
||||||
logger.info('[lifecycle] Main window closing, cleaning up...');
|
// 总是弹出确认对话框
|
||||||
|
event.preventDefault();
|
||||||
|
|
||||||
|
const { dialog } = require('electron');
|
||||||
|
const { app } = require('electron');
|
||||||
|
|
||||||
|
const response = await dialog.showMessageBox(win, {
|
||||||
|
type: 'question',
|
||||||
|
title: '退出确认',
|
||||||
|
message: '确定要退出应用吗?',
|
||||||
|
buttons: ['取消', '退出'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 0
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.response === 1) {
|
||||||
|
// 用户确认退出
|
||||||
|
logger.info('[lifecycle] User confirmed exit');
|
||||||
|
|
||||||
|
// 移除所有监听器避免循环
|
||||||
|
win.removeAllListeners('close');
|
||||||
|
|
||||||
|
// 执行清理
|
||||||
await this.cleanup();
|
await this.cleanup();
|
||||||
|
|
||||||
|
// 退出应用
|
||||||
|
app.quit();
|
||||||
|
}
|
||||||
|
// 用户取消,什么都不做(已经 preventDefault)
|
||||||
});
|
});
|
||||||
|
|
||||||
// 立即刷新一次,确保显示最新内容
|
// 立即刷新一次,确保显示最新内容
|
||||||
@@ -294,6 +349,12 @@ class Lifecycle {
|
|||||||
async cleanup() {
|
async cleanup() {
|
||||||
logger.info('[lifecycle] Starting cleanup...');
|
logger.info('[lifecycle] Starting cleanup...');
|
||||||
|
|
||||||
|
// 如果是权限提升重启,跳过清理(服务需要继续运行)
|
||||||
|
if (this.isRestartingForAdmin) {
|
||||||
|
logger.info('[lifecycle] Restarting for admin, skip cleanup');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// 清除自动刷新定时器
|
// 清除自动刷新定时器
|
||||||
if (this.autoRefreshTimer) {
|
if (this.autoRefreshTimer) {
|
||||||
clearTimeout(this.autoRefreshTimer);
|
clearTimeout(this.autoRefreshTimer);
|
||||||
@@ -323,10 +384,8 @@ class Lifecycle {
|
|||||||
this.logWindowManager.addLog('system', '正在停止 Spring Boot...');
|
this.logWindowManager.addLog('system', '正在停止 Spring Boot...');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置超时,3秒后强制继续
|
// 停止 Java 进程(内部已有完整的等待和清理逻辑)
|
||||||
const stopPromise = this.javaRunner.stopSpringBoot();
|
await this.javaRunner.stopSpringBoot();
|
||||||
const timeoutPromise = new Promise(resolve => setTimeout(resolve, 3000));
|
|
||||||
await Promise.race([stopPromise, timeoutPromise]);
|
|
||||||
|
|
||||||
logger.info('[lifecycle] Spring Boot stopped');
|
logger.info('[lifecycle] Spring Boot stopped');
|
||||||
if (this.logWindowManager && this.logWindowManager.logWindow && !this.logWindowManager.logWindow.isDestroyed()) {
|
if (this.logWindowManager && this.logWindowManager.logWindow && !this.logWindowManager.logWindow.isDestroyed()) {
|
||||||
@@ -337,36 +396,13 @@ class Lifecycle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 停止 MySQL
|
// MySQL 作为Windows服务运行,应用关闭时保持运行
|
||||||
const config = getConfig();
|
logger.info('[lifecycle] MySQL service keeps running as Windows service');
|
||||||
if (config.mysql && config.mysql.enable && config.mysql.autoStart) {
|
|
||||||
try {
|
|
||||||
logger.info('[lifecycle] Stopping MySQL...');
|
|
||||||
if (this.logWindowManager && this.logWindowManager.logWindow && !this.logWindowManager.logWindow.isDestroyed()) {
|
if (this.logWindowManager && this.logWindowManager.logWindow && !this.logWindowManager.logWindow.isDestroyed()) {
|
||||||
this.logWindowManager.addLog('system', '正在停止 MySQL(最多等待10秒)...');
|
this.logWindowManager.addLog('system', 'MySQL 服务保持运行');
|
||||||
}
|
|
||||||
|
|
||||||
if (this.mysqlManager) {
|
|
||||||
// MySQL 的 stop() 方法内部使用 mysqladmin shutdown(最多10秒)
|
|
||||||
// 设置12秒超时作为保险
|
|
||||||
const stopPromise = this.mysqlManager.stop();
|
|
||||||
const timeoutPromise = new Promise(resolve => setTimeout(resolve, 12000));
|
|
||||||
await Promise.race([stopPromise, timeoutPromise]);
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info('[lifecycle] MySQL stopped');
|
|
||||||
if (this.logWindowManager && this.logWindowManager.logWindow && !this.logWindowManager.logWindow.isDestroyed()) {
|
|
||||||
this.logWindowManager.addLog('success', 'MySQL 已停止');
|
|
||||||
this.logWindowManager.addLog('system', '清理完成,应用即将退出');
|
this.logWindowManager.addLog('system', '清理完成,应用即将退出');
|
||||||
this.logWindowManager.addLog('system', '='.repeat(60));
|
this.logWindowManager.addLog('system', '='.repeat(60));
|
||||||
}
|
}
|
||||||
} catch (error) {
|
|
||||||
logger.error('[lifecycle] Failed to stop MySQL:', error);
|
|
||||||
if (this.logWindowManager && this.logWindowManager.logWindow && !this.logWindowManager.logWindow.isDestroyed()) {
|
|
||||||
this.logWindowManager.addLog('error', 'MySQL 停止失败: ' + error.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 等待500ms让用户看到清理日志
|
// 等待500ms让用户看到清理日志
|
||||||
await this.sleep(500);
|
await this.sleep(500);
|
||||||
@@ -384,35 +420,6 @@ class Lifecycle {
|
|||||||
logger.info('[lifecycle] Cleanup completed');
|
logger.info('[lifecycle] Cleanup completed');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 设置 MySQL 日志监听
|
|
||||||
*/
|
|
||||||
setupMySQLLogging(mysqlProcess) {
|
|
||||||
if (!mysqlProcess) return;
|
|
||||||
|
|
||||||
mysqlProcess.stdout.on('data', (data) => {
|
|
||||||
const output = data.toString().trim();
|
|
||||||
if (output) {
|
|
||||||
// 根据内容判断日志类型
|
|
||||||
if (output.includes('[ERROR]') || output.includes('ERROR')) {
|
|
||||||
this.logWindowManager.addLog('error', `[MySQL] ${output}`);
|
|
||||||
} else if (output.includes('[Warning]') || output.includes('WARNING')) {
|
|
||||||
this.logWindowManager.addLog('warn', `[MySQL] ${output}`);
|
|
||||||
} else if (output.includes('ready for connections')) {
|
|
||||||
this.logWindowManager.addLog('success', `[MySQL] ${output}`);
|
|
||||||
} else {
|
|
||||||
this.logWindowManager.addLog('mysql', `[MySQL] ${output}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
mysqlProcess.stderr.on('data', (data) => {
|
|
||||||
const output = data.toString().trim();
|
|
||||||
if (output) {
|
|
||||||
this.logWindowManager.addLog('warn', `[MySQL Error] ${output}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 启动 Spring Boot 应用
|
* 启动 Spring Boot 应用
|
||||||
@@ -477,6 +484,80 @@ class Lifecycle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 以管理员身份重启应用
|
||||||
|
*/
|
||||||
|
async restartAsAdmin() {
|
||||||
|
const { app, dialog } = require('electron');
|
||||||
|
const { spawn } = require('child_process');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
logger.info('[lifecycle] Requesting administrator privileges...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 显示提示对话框
|
||||||
|
const { response } = await dialog.showMessageBox({
|
||||||
|
type: 'warning',
|
||||||
|
title: '需要管理员权限',
|
||||||
|
message: '安装 MySQL 服务需要管理员权限',
|
||||||
|
detail: '应用将以管理员身份重新启动',
|
||||||
|
buttons: ['取消', '确定'],
|
||||||
|
defaultId: 1,
|
||||||
|
cancelId: 0
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response === 0) {
|
||||||
|
// 用户取消,关闭应用
|
||||||
|
logger.info('[lifecycle] User cancelled admin elevation');
|
||||||
|
app.quit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取应用可执行文件路径
|
||||||
|
const exePath = app.getPath('exe');
|
||||||
|
logger.info('[lifecycle] Restarting with admin privileges:', exePath);
|
||||||
|
|
||||||
|
// 使用 PowerShell 以管理员身份启动
|
||||||
|
const psCommand = `Start-Process -FilePath "${exePath}" -Verb RunAs`;
|
||||||
|
|
||||||
|
const child = spawn('powershell.exe', ['-Command', psCommand], {
|
||||||
|
detached: true,
|
||||||
|
stdio: 'ignore',
|
||||||
|
windowsHide: true
|
||||||
|
});
|
||||||
|
|
||||||
|
// 分离子进程,父进程退出不影响子进程
|
||||||
|
child.unref();
|
||||||
|
|
||||||
|
// 立即退出当前实例,释放单实例锁
|
||||||
|
// 必须立即退出,否则新实例会因为单实例锁无法启动
|
||||||
|
logger.info('[lifecycle] Quitting current instance to release lock...');
|
||||||
|
|
||||||
|
// 设置标记,跳过清理流程(这只是重启,不是真正退出)
|
||||||
|
this.isRestartingForAdmin = true;
|
||||||
|
|
||||||
|
// 关闭所有窗口
|
||||||
|
const BrowserWindow = require('electron').BrowserWindow;
|
||||||
|
BrowserWindow.getAllWindows().forEach(win => {
|
||||||
|
try {
|
||||||
|
win.destroy();
|
||||||
|
} catch (e) {
|
||||||
|
// 忽略错误
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 立即强制退出,释放锁
|
||||||
|
process.exit(0);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('[lifecycle] Failed to restart as admin:', error);
|
||||||
|
this.logWindowManager.addLog('error', '自动提升权限失败,请手动以管理员身份运行');
|
||||||
|
|
||||||
|
// 等待5秒后关闭
|
||||||
|
await this.sleep(5000);
|
||||||
|
app.quit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 睡眠函数
|
* 睡眠函数
|
||||||
*/
|
*/
|
||||||
@@ -495,20 +576,26 @@ class Lifecycle {
|
|||||||
* main window have been loaded
|
* main window have been loaded
|
||||||
*/
|
*/
|
||||||
async windowReady() {
|
async windowReady() {
|
||||||
logger.info('[lifecycle] window-ready');
|
logger.info('[lifecycle] window-ready hook triggered');
|
||||||
if (ps.isProd()) {
|
|
||||||
// 创建日志窗口
|
// 创建日志管理器(但不显示窗口,仅用于写日志文件)
|
||||||
|
logger.info('[lifecycle] Creating log window manager...');
|
||||||
this.logWindowManager = new LogWindowManager();
|
this.logWindowManager = new LogWindowManager();
|
||||||
this.logWindowManager.createLogWindow();
|
// this.logWindowManager.createLogWindow(); // ← 注释掉,不创建窗口
|
||||||
|
this.logWindowManager.addLog('system', '='.repeat(80));
|
||||||
|
this.logWindowManager.addLog('system', 'NPQS9100 应用启动');
|
||||||
|
this.logWindowManager.addLog('system', '='.repeat(80));
|
||||||
|
|
||||||
|
// 创建 Loading 窗口
|
||||||
|
logger.info('[lifecycle] Creating startup manager and loading window...');
|
||||||
|
this.startupManager = new StartupManager();
|
||||||
|
this.startupManager.createLoadingWindow();
|
||||||
this.logWindowManager.addLog('system', '='.repeat(60));
|
this.logWindowManager.addLog('system', '='.repeat(60));
|
||||||
this.logWindowManager.addLog('system', 'NPQS9100 启动中...');
|
this.logWindowManager.addLog('system', 'NPQS9100 启动中...');
|
||||||
this.logWindowManager.addLog('system', '='.repeat(60));
|
this.logWindowManager.addLog('system', '='.repeat(60));
|
||||||
|
|
||||||
// 创建 Loading 窗口
|
|
||||||
this.startupManager = new StartupManager();
|
|
||||||
this.startupManager.createLoadingWindow();
|
|
||||||
|
|
||||||
// 开始启动流程
|
// 开始启动流程
|
||||||
|
logger.info('[lifecycle] Starting application flow...');
|
||||||
try {
|
try {
|
||||||
await this.startApplication();
|
await this.startApplication();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -526,26 +613,18 @@ class Lifecycle {
|
|||||||
win.show();
|
win.show();
|
||||||
win.focus();
|
win.focus();
|
||||||
|
|
||||||
// 添加主窗口关闭事件监听
|
// 启动失败时,允许用户正常关闭窗口(不强制托盘)
|
||||||
win.on('close', async () => {
|
// 因为可能托盘未创建,或用户想直接退出
|
||||||
logger.info('[lifecycle] Main window closing (after error), cleaning up...');
|
win.on('close', async (event) => {
|
||||||
|
logger.info('[lifecycle] Window closing (after error), cleaning up...');
|
||||||
|
// 不阻止关闭,执行清理
|
||||||
await this.cleanup();
|
await this.cleanup();
|
||||||
});
|
});
|
||||||
|
|
||||||
this.logWindowManager.addLog('warn', '应用已启动,但部分服务可能未正常运行');
|
this.logWindowManager.addLog('warn', '应用已启动,但部分服务可能未正常运行');
|
||||||
|
this.logWindowManager.addLog('system', '您可以点击 X 关闭应用');
|
||||||
}, 5000);
|
}, 5000);
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
const win = getMainWindow();
|
|
||||||
const {windowsOption} = getConfig();
|
|
||||||
if (windowsOption.show == false) {
|
|
||||||
win.once('ready-to-show', () => {
|
|
||||||
win.show();
|
|
||||||
win.focus();
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// 主窗口初始化但不显示,等待启动流程完成后再显示
|
// 主窗口初始化但不显示,等待启动流程完成后再显示
|
||||||
// 在 startApplication() 中会调用 win.show()
|
// 在 startApplication() 中会调用 win.show()
|
||||||
@@ -556,11 +635,8 @@ class Lifecycle {
|
|||||||
*/
|
*/
|
||||||
async beforeClose() {
|
async beforeClose() {
|
||||||
logger.info('[lifecycle] before-close hook triggered');
|
logger.info('[lifecycle] before-close hook triggered');
|
||||||
if (ps.isProd()) {
|
|
||||||
await this.cleanup();
|
await this.cleanup();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Lifecycle.toString = () => '[class Lifecycle]';
|
Lifecycle.toString = () => '[class Lifecycle]';
|
||||||
|
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ VITE_API_URL=/api
|
|||||||
# 开发环境跨域代理,支持配置多个
|
# 开发环境跨域代理,支持配置多个
|
||||||
|
|
||||||
#VITE_PROXY=[["/api","http://127.0.0.1:18092/"]]
|
#VITE_PROXY=[["/api","http://127.0.0.1:18092/"]]
|
||||||
VITE_PROXY=[["/api","http://192.168.1.124:18092/"]]
|
#VITE_PROXY=[["/api","http://192.168.1.124:18092/"]]
|
||||||
#VITE_PROXY=[["/api","http://192.168.1.125:18092/"]]
|
VITE_PROXY=[["/api","http://192.168.1.125:18092/"]]
|
||||||
# VITE_PROXY=[["/api","http://192.168.1.138:8080/"]]张文
|
# VITE_PROXY=[["/api","http://192.168.1.138:8080/"]]张文
|
||||||
# 开启激活验证
|
# 开启激活验证
|
||||||
VITE_ACTIVATE_OPEN=false
|
VITE_ACTIVATE_OPEN=true
|
||||||
@@ -25,4 +25,4 @@ VITE_PWA=true
|
|||||||
#VITE_API_URL="/api" # 打包时用
|
#VITE_API_URL="/api" # 打包时用
|
||||||
VITE_API_URL="http://127.0.0.1:18092/"
|
VITE_API_URL="http://127.0.0.1:18092/"
|
||||||
# 开启激活验证
|
# 开启激活验证
|
||||||
VITE_ACTIVATE_OPEN=false
|
VITE_ACTIVATE_OPEN=true
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
<template>
|
<template>
|
||||||
<!--element-plus语言国际化,全局修改为中文-->
|
<!--element-plus语言国际化,全局修改为中文-->
|
||||||
|
<!-- 测试升级功能 - 2025-10-24 -->
|
||||||
<el-config-provider :locale="locale" :size="assemblySize" :button="buttonConfig">
|
<el-config-provider :locale="locale" :size="assemblySize" :button="buttonConfig">
|
||||||
<router-view />
|
<router-view />
|
||||||
</el-config-provider>
|
</el-config-provider>
|
||||||
|
|||||||
@@ -21,10 +21,10 @@ export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
// 默认地址请求地址,可在 .env.** 文件中修改
|
// 默认地址请求地址,可在 .env 开头文件中修改
|
||||||
baseURL: import.meta.env.VITE_API_URL as string,
|
baseURL: import.meta.env.VITE_API_URL as string,
|
||||||
// 设置超时时间
|
// 设置超时时间(60s)
|
||||||
timeout: ResultEnum.TIMEOUT as number,
|
timeout: 60000,
|
||||||
// 跨域时候允许携带凭证
|
// 跨域时候允许携带凭证
|
||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
// post请求指定数据类型以及编码
|
// post请求指定数据类型以及编码
|
||||||
|
|||||||
@@ -18,13 +18,15 @@
|
|||||||
<img :src="item.img" />
|
<img :src="item.img" />
|
||||||
</div>
|
</div>
|
||||||
<div class="test_button">
|
<div class="test_button">
|
||||||
<el-button size="large" type="primary" @click="handelOpen(item)" :disabled="!item.activated">
|
<el-button size="large" type="primary" @click="handelOpen(item)">
|
||||||
进入检测
|
{{ item.activated ? '进入检测' : '待激活' }}
|
||||||
</el-button>
|
</el-button>
|
||||||
</div>
|
</div>
|
||||||
</el-carousel-item>
|
</el-carousel-item>
|
||||||
</el-carousel>
|
</el-carousel>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- versionRegisterDialog -->
|
||||||
|
<VersionDialog ref="versionRegisterRef"></VersionDialog>
|
||||||
</template>
|
</template>
|
||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { useAuthStore } from '@/stores/modules/auth'
|
import { useAuthStore } from '@/stores/modules/auth'
|
||||||
@@ -32,6 +34,8 @@ import { useAppSceneStore, useModeStore } from '@/stores/modules/mode' // 引入
|
|||||||
import { getCurrentScene } from '@/api/user/login'
|
import { getCurrentScene } from '@/api/user/login'
|
||||||
import { initDynamicRouter } from '@/routers/modules/dynamicRouter'
|
import { initDynamicRouter } from '@/routers/modules/dynamicRouter'
|
||||||
import { useTabsStore } from '@/stores/modules/tabs'
|
import { useTabsStore } from '@/stores/modules/tabs'
|
||||||
|
import VersionDialog from '@/views/system/versionRegister/index.vue'
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
|
||||||
const authStore = useAuthStore()
|
const authStore = useAuthStore()
|
||||||
const modeStore = useModeStore() // 使用模式 store
|
const modeStore = useModeStore() // 使用模式 store
|
||||||
@@ -39,6 +43,7 @@ const AppSceneStore = useAppSceneStore()
|
|||||||
const activateInfo = authStore.activateInfo
|
const activateInfo = authStore.activateInfo
|
||||||
const isActivateOpen = import.meta.env.VITE_ACTIVATE_OPEN
|
const isActivateOpen = import.meta.env.VITE_ACTIVATE_OPEN
|
||||||
const tabsStore = useTabsStore()
|
const tabsStore = useTabsStore()
|
||||||
|
const versionRegisterRef = ref<InstanceType<typeof VersionDialog> | null>(null)
|
||||||
const modeList = [
|
const modeList = [
|
||||||
{
|
{
|
||||||
name: '模拟式模块',
|
name: '模拟式模块',
|
||||||
@@ -64,7 +69,8 @@ const modeList = [
|
|||||||
]
|
]
|
||||||
const handelOpen = async (item: any) => {
|
const handelOpen = async (item: any) => {
|
||||||
if (!item.activated) {
|
if (!item.activated) {
|
||||||
ElMessage.warning(`${item.name}未激活`)
|
// 打开版本激活弹窗
|
||||||
|
versionRegisterRef.value?.openDialog()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
modeStore.setCurrentMode(item.code) // 将模式code存入 store
|
modeStore.setCurrentMode(item.code) // 将模式code存入 store
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
</template>
|
</template>
|
||||||
</el-input>
|
</el-input>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item prop="checked">
|
<el-form-item prop="checked" v-show="false">
|
||||||
<el-checkbox v-model="loginForm.checked">记住我</el-checkbox>
|
<el-checkbox v-model="loginForm.checked">记住我</el-checkbox>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
</el-form>
|
</el-form>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>NPQS9100 正在启动...</title>
|
<title>NPQS-9100自动检测平台 正在启动...</title>
|
||||||
<style>
|
<style>
|
||||||
* {
|
* {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
@@ -145,8 +145,8 @@
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="loading-container">
|
<div class="loading-container">
|
||||||
<div class="logo">NPQS9100</div>
|
<div class="logo">NPQS-9100自动检测平台</div>
|
||||||
<div class="subtitle">南京灿能电气自动化 · 自动检测平台</div>
|
<div class="subtitle">南京灿能电力自动化股份有限公司</div>
|
||||||
|
|
||||||
<div class="status-text" id="statusText">正在初始化应用...</div>
|
<div class="status-text" id="statusText">正在初始化应用...</div>
|
||||||
|
|
||||||
|
|||||||
@@ -32,10 +32,8 @@ class ConfigGenerator {
|
|||||||
* @returns {string} 数据目录路径
|
* @returns {string} 数据目录路径
|
||||||
*/
|
*/
|
||||||
getDataPath(baseDir) {
|
getDataPath(baseDir) {
|
||||||
// 获取应用所在盘符(例如:C:, D:, E:)
|
// 数据目录设置在应用目录内的 NPQS9100_Data 文件夹
|
||||||
const driveLetter = path.parse(baseDir).root;
|
return path.join(baseDir, 'NPQS9100_Data');
|
||||||
// 数据目录设置在盘符根目录下的 NPQS9100_Data 文件夹
|
|
||||||
return path.join(driveLetter, 'NPQS9100_Data');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -43,6 +41,7 @@ class ConfigGenerator {
|
|||||||
* @param {object} options - 配置选项
|
* @param {object} options - 配置选项
|
||||||
* @param {number} options.mysqlPort - MySQL 端口
|
* @param {number} options.mysqlPort - MySQL 端口
|
||||||
* @param {number} options.javaPort - Java 应用端口
|
* @param {number} options.javaPort - Java 应用端口
|
||||||
|
* @param {number} options.websocketPort - WebSocket 端口
|
||||||
* @param {string} options.mysqlPassword - MySQL 密码
|
* @param {string} options.mysqlPassword - MySQL 密码
|
||||||
*/
|
*/
|
||||||
generateConfig(options = {}) {
|
generateConfig(options = {}) {
|
||||||
@@ -74,6 +73,11 @@ class ConfigGenerator {
|
|||||||
template = template.replace(/port:\s*18092/g, `port: ${options.javaPort}`);
|
template = template.replace(/port:\s*18092/g, `port: ${options.javaPort}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 替换 WebSocket 端口
|
||||||
|
if (options.websocketPort) {
|
||||||
|
template = template.replace(/port:\s*7777/g, `port: ${options.websocketPort}`);
|
||||||
|
}
|
||||||
|
|
||||||
// 写入配置文件
|
// 写入配置文件
|
||||||
fs.writeFileSync(this.configPath, template, 'utf-8');
|
fs.writeFileSync(this.configPath, template, 'utf-8');
|
||||||
|
|
||||||
@@ -85,12 +89,14 @@ class ConfigGenerator {
|
|||||||
console.log('[ConfigGenerator] MySQL port:', options.mysqlPort || 3306);
|
console.log('[ConfigGenerator] MySQL port:', options.mysqlPort || 3306);
|
||||||
console.log('[ConfigGenerator] MySQL password:', options.mysqlPassword || 'njcnpqs');
|
console.log('[ConfigGenerator] MySQL password:', options.mysqlPassword || 'njcnpqs');
|
||||||
console.log('[ConfigGenerator] Java port:', options.javaPort || 18092);
|
console.log('[ConfigGenerator] Java port:', options.javaPort || 18092);
|
||||||
|
console.log('[ConfigGenerator] WebSocket port:', options.websocketPort || 7777);
|
||||||
|
|
||||||
resolve({
|
resolve({
|
||||||
configPath: this.configPath,
|
configPath: this.configPath,
|
||||||
dataPath: this.dataPath,
|
dataPath: this.dataPath,
|
||||||
mysqlPort: options.mysqlPort || 3306,
|
mysqlPort: options.mysqlPort || 3306,
|
||||||
javaPort: options.javaPort || 18092
|
javaPort: options.javaPort || 18092,
|
||||||
|
websocketPort: options.websocketPort || 7777
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[ConfigGenerator] Failed to generate config:', error);
|
console.error('[ConfigGenerator] Failed to generate config:', error);
|
||||||
|
|||||||
@@ -206,39 +206,109 @@ class JavaRunner {
|
|||||||
* 停止 Spring Boot 应用
|
* 停止 Spring Boot 应用
|
||||||
*/
|
*/
|
||||||
stopSpringBoot() {
|
stopSpringBoot() {
|
||||||
return new Promise((resolve) => {
|
return new Promise(async (resolve) => {
|
||||||
|
const { exec } = require('child_process');
|
||||||
|
const killedPids = new Set();
|
||||||
|
let killAttempts = 0;
|
||||||
|
|
||||||
|
// 方法1: 如果有进程引用,通过PID杀死
|
||||||
if (this.springBootProcess && !this.springBootProcess.killed) {
|
if (this.springBootProcess && !this.springBootProcess.killed) {
|
||||||
// 设置3秒超时,如果进程没有正常退出,强制kill
|
const pid = this.springBootProcess.pid;
|
||||||
const timeout = setTimeout(() => {
|
console.log('[Java] Method 1: Stopping Spring Boot by PID:', pid);
|
||||||
console.log('[Java] Force killing Spring Boot process');
|
|
||||||
try {
|
// 使用 /F 强制终止,/T 终止子进程树
|
||||||
this.springBootProcess.kill('SIGKILL');
|
const killCommand = `taskkill /F /T /PID ${pid}`;
|
||||||
} catch (e) {
|
console.log('[Java] Executing:', killCommand);
|
||||||
console.error('[Java] Error force killing:', e);
|
|
||||||
|
exec(killCommand, (error, stdout, stderr) => {
|
||||||
|
if (error) {
|
||||||
|
console.error('[Java] taskkill by PID failed:', error);
|
||||||
|
} else {
|
||||||
|
console.log('[Java] taskkill by PID success:', stdout);
|
||||||
|
killedPids.add(pid);
|
||||||
|
}
|
||||||
|
killAttempts++;
|
||||||
|
checkComplete();
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
killAttempts++;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 清理端口记录文件
|
// 方法2: 通过端口杀死占用进程(精确定位,不会误杀其他Java进程)
|
||||||
this.cleanupJavaPortFile();
|
const recordedPort = this.currentJavaPort || this.getRecordedJavaPort();
|
||||||
resolve();
|
if (recordedPort) {
|
||||||
}, 3000);
|
console.log(`[Java] Method 2: Killing process on port ${recordedPort} (precise targeting)`);
|
||||||
|
|
||||||
this.springBootProcess.on('close', () => {
|
// 查找占用端口的进程
|
||||||
clearTimeout(timeout);
|
const findCommand = `netstat -ano | findstr :${recordedPort}`;
|
||||||
console.log('[Java] Spring Boot application stopped gracefully');
|
exec(findCommand, (error, stdout) => {
|
||||||
|
if (!error && stdout) {
|
||||||
|
// 提取PID(最后一列)
|
||||||
|
const lines = stdout.trim().split('\n');
|
||||||
|
const pids = new Set();
|
||||||
|
|
||||||
// 清理端口记录文件
|
lines.forEach(line => {
|
||||||
this.cleanupJavaPortFile();
|
const parts = line.trim().split(/\s+/);
|
||||||
resolve();
|
const pid = parts[parts.length - 1];
|
||||||
|
if (pid && pid !== '0' && !killedPids.has(pid)) {
|
||||||
|
pids.add(pid);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 先尝试优雅关闭
|
console.log(`[Java] Found PIDs on port ${recordedPort}:`, Array.from(pids));
|
||||||
console.log('[Java] Sending SIGTERM to Spring Boot');
|
|
||||||
this.springBootProcess.kill('SIGTERM');
|
if (pids.size > 0) {
|
||||||
|
// 杀死所有找到的进程
|
||||||
|
let portsKilled = 0;
|
||||||
|
pids.forEach(pid => {
|
||||||
|
exec(`taskkill /F /T /PID ${pid}`, (err, out) => {
|
||||||
|
portsKilled++;
|
||||||
|
if (!err) {
|
||||||
|
console.log(`[Java] Killed process ${pid} on port ${recordedPort}`);
|
||||||
} else {
|
} else {
|
||||||
// 即使没有进程引用,也尝试清理端口记录文件
|
console.warn(`[Java] Failed to kill process ${pid}:`, err);
|
||||||
this.cleanupJavaPortFile();
|
|
||||||
resolve();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (portsKilled === pids.size) {
|
||||||
|
killAttempts++;
|
||||||
|
checkComplete();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.log(`[Java] No process found on port ${recordedPort} (already cleaned)`);
|
||||||
|
killAttempts++;
|
||||||
|
checkComplete();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log(`[Java] No process found on port ${recordedPort}`);
|
||||||
|
killAttempts++;
|
||||||
|
checkComplete();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.log('[Java] No port recorded, skipping port-based kill');
|
||||||
|
killAttempts++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否所有清理方法都已完成
|
||||||
|
function checkComplete() {
|
||||||
|
const expectedAttempts = recordedPort ? 2 : 1;
|
||||||
|
if (killAttempts >= expectedAttempts) {
|
||||||
|
// 清理端口记录文件
|
||||||
|
this.cleanupJavaPortFile();
|
||||||
|
|
||||||
|
// 等待500ms确保进程完全终止
|
||||||
|
setTimeout(() => {
|
||||||
|
console.log('[Java] Spring Boot stop process completed');
|
||||||
|
console.log('[Java] Note: Other Java processes (like IDEA) are NOT affected');
|
||||||
|
resolve();
|
||||||
|
}, 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 绑定this上下文
|
||||||
|
checkComplete = checkComplete.bind(this);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,17 +11,108 @@ class LogWindowManager {
|
|||||||
this.logWindow = null;
|
this.logWindow = null;
|
||||||
this.logs = [];
|
this.logs = [];
|
||||||
this.maxLogs = 1000; // 最多保留1000条日志
|
this.maxLogs = 1000; // 最多保留1000条日志
|
||||||
|
|
||||||
|
// 初始化日志文件路径
|
||||||
|
this.initLogFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化日志文件路径(按天滚动)
|
||||||
|
*/
|
||||||
|
initLogFile() {
|
||||||
|
// 开发环境:项目根目录的 logs 文件夹
|
||||||
|
// 打包后:应用根目录的 logs 文件夹
|
||||||
|
const isDev = !process.resourcesPath;
|
||||||
|
const baseDir = isDev
|
||||||
|
? path.join(__dirname, '..')
|
||||||
|
: path.dirname(process.resourcesPath);
|
||||||
|
|
||||||
|
this.logsDir = path.join(baseDir, 'logs');
|
||||||
|
|
||||||
|
// 确保 logs 目录存在
|
||||||
|
if (!fs.existsSync(this.logsDir)) {
|
||||||
|
fs.mkdirSync(this.logsDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成当天的日志文件名:startup-YYYYMMDD.log
|
||||||
|
const today = new Date();
|
||||||
|
const dateStr = today.getFullYear() +
|
||||||
|
String(today.getMonth() + 1).padStart(2, '0') +
|
||||||
|
String(today.getDate()).padStart(2, '0');
|
||||||
|
this.logFilePath = path.join(this.logsDir, `startup-${dateStr}.log`);
|
||||||
|
|
||||||
|
console.log('[LogWindowManager] Log file:', this.logFilePath);
|
||||||
|
|
||||||
|
// 写入启动标记
|
||||||
|
this.writeToFile(new Date().toISOString().replace('T', ' ').substring(0, 19), 'SYSTEM', '=' .repeat(80));
|
||||||
|
this.writeToFile(new Date().toISOString().replace('T', ' ').substring(0, 19), 'SYSTEM', 'NPQS9100 应用启动');
|
||||||
|
this.writeToFile(new Date().toISOString().replace('T', ' ').substring(0, 19), 'SYSTEM', '=' .repeat(80));
|
||||||
|
|
||||||
|
// 清理超过30天的旧日志
|
||||||
|
this.cleanOldLogs(30);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理旧日志文件
|
||||||
|
* @param {number} days - 保留天数
|
||||||
|
*/
|
||||||
|
cleanOldLogs(days) {
|
||||||
|
try {
|
||||||
|
const now = Date.now();
|
||||||
|
const maxAge = days * 24 * 60 * 60 * 1000; // 转换为毫秒
|
||||||
|
|
||||||
|
const files = fs.readdirSync(this.logsDir);
|
||||||
|
let deletedCount = 0;
|
||||||
|
|
||||||
|
files.forEach(file => {
|
||||||
|
if (file.startsWith('startup-') && file.endsWith('.log')) {
|
||||||
|
const filePath = path.join(this.logsDir, file);
|
||||||
|
const stats = fs.statSync(filePath);
|
||||||
|
const age = now - stats.mtimeMs;
|
||||||
|
|
||||||
|
if (age > maxAge) {
|
||||||
|
fs.unlinkSync(filePath);
|
||||||
|
deletedCount++;
|
||||||
|
console.log(`[LogWindowManager] Deleted old log: ${file}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (deletedCount > 0) {
|
||||||
|
console.log(`[LogWindowManager] Cleaned up ${deletedCount} old log file(s)`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[LogWindowManager] Failed to clean old logs:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 写入日志到文件
|
||||||
|
*/
|
||||||
|
writeToFile(timestamp, type, message) {
|
||||||
|
try {
|
||||||
|
const logLine = `[${timestamp}] [${type.toUpperCase()}] ${message}\n`;
|
||||||
|
fs.appendFileSync(this.logFilePath, logLine, 'utf-8');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[LogWindowManager] Failed to write log to file:', error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建日志窗口
|
* 创建日志窗口
|
||||||
*/
|
*/
|
||||||
createLogWindow() {
|
createLogWindow() {
|
||||||
|
const isDev = !process.resourcesPath;
|
||||||
|
const iconPath = isDev
|
||||||
|
? path.join(__dirname, '..', 'public', 'images', 'icon.png')
|
||||||
|
: path.join(process.resourcesPath, 'app.asar.unpacked', 'public', 'images', 'icon.png');
|
||||||
|
|
||||||
this.logWindow = new BrowserWindow({
|
this.logWindow = new BrowserWindow({
|
||||||
width: 900,
|
width: 900,
|
||||||
height: 600,
|
height: 600,
|
||||||
title: 'NPQS9100 - 服务日志',
|
title: 'NPQS9100 - 服务日志',
|
||||||
backgroundColor: '#1e1e1e',
|
backgroundColor: '#1e1e1e',
|
||||||
|
icon: iconPath,
|
||||||
webPreferences: {
|
webPreferences: {
|
||||||
nodeIntegration: true,
|
nodeIntegration: true,
|
||||||
contextIsolation: false
|
contextIsolation: false
|
||||||
@@ -207,7 +298,10 @@ class LogWindowManager {
|
|||||||
* 添加日志
|
* 添加日志
|
||||||
*/
|
*/
|
||||||
addLog(type, message) {
|
addLog(type, message) {
|
||||||
const timestamp = new Date().toLocaleTimeString();
|
const now = new Date();
|
||||||
|
const timestamp = now.toLocaleTimeString();
|
||||||
|
const fullTimestamp = now.toISOString().replace('T', ' ').substring(0, 19);
|
||||||
|
|
||||||
const logEntry = {
|
const logEntry = {
|
||||||
timestamp,
|
timestamp,
|
||||||
type,
|
type,
|
||||||
@@ -221,6 +315,9 @@ class LogWindowManager {
|
|||||||
this.logs.shift();
|
this.logs.shift();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 写入文件(使用完整时间戳)
|
||||||
|
this.writeToFile(fullTimestamp, type, message);
|
||||||
|
|
||||||
// 发送到窗口
|
// 发送到窗口
|
||||||
if (this.logWindow && !this.logWindow.isDestroyed()) {
|
if (this.logWindow && !this.logWindow.isDestroyed()) {
|
||||||
this.logWindow.webContents.send('log-message', logEntry);
|
this.logWindow.webContents.send('log-message', logEntry);
|
||||||
|
|||||||
@@ -1,373 +0,0 @@
|
|||||||
const { spawn, exec } = require('child_process');
|
|
||||||
const path = require('path');
|
|
||||||
const fs = require('fs');
|
|
||||||
|
|
||||||
class MySQLManager {
|
|
||||||
constructor() {
|
|
||||||
// 在开发与打包后均可解析到应用根目录下的 mysql 目录
|
|
||||||
// 开发环境:项目根目录
|
|
||||||
// 打包后:应用根目录(win-unpacked)
|
|
||||||
const isDev = !process.resourcesPath;
|
|
||||||
const baseDir = isDev
|
|
||||||
? path.join(__dirname, '..')
|
|
||||||
: path.dirname(process.resourcesPath);
|
|
||||||
this.mysqlPath = path.join(baseDir, 'mysql');
|
|
||||||
this.binPath = path.join(this.mysqlPath, 'bin');
|
|
||||||
this.dataPath = path.join(this.mysqlPath, 'data');
|
|
||||||
this.process = null;
|
|
||||||
this.currentPort = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查MySQL是否已初始化
|
|
||||||
isInitialized() {
|
|
||||||
return fs.existsSync(this.dataPath) && fs.readdirSync(this.dataPath).length > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 初始化MySQL数据库
|
|
||||||
async initialize() {
|
|
||||||
if (this.isInitialized()) {
|
|
||||||
console.log('MySQL already initialized');
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Promise(async (resolve, reject) => {
|
|
||||||
const mysqld = path.join(this.binPath, 'mysqld.exe');
|
|
||||||
|
|
||||||
// 创建初始化SQL文件(授权127.0.0.1和所有主机)
|
|
||||||
const initSqlPath = path.join(this.mysqlPath, 'init_grant.sql');
|
|
||||||
const initSql = `
|
|
||||||
CREATE USER IF NOT EXISTS 'root'@'127.0.0.1' IDENTIFIED BY '';
|
|
||||||
GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1' WITH GRANT OPTION;
|
|
||||||
CREATE USER IF NOT EXISTS 'root'@'%' IDENTIFIED BY '';
|
|
||||||
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
|
|
||||||
FLUSH PRIVILEGES;
|
|
||||||
`;
|
|
||||||
|
|
||||||
try {
|
|
||||||
fs.writeFileSync(initSqlPath, initSql, 'utf-8');
|
|
||||||
console.log('[MySQL] Created init SQL file for granting permissions');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[MySQL] Failed to create init SQL file:', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 使用 --init-file 参数初始化并授权
|
|
||||||
const initProcess = spawn(mysqld, [
|
|
||||||
'--initialize-insecure',
|
|
||||||
`--init-file=${initSqlPath}`
|
|
||||||
], {
|
|
||||||
cwd: this.mysqlPath,
|
|
||||||
stdio: 'inherit'
|
|
||||||
});
|
|
||||||
|
|
||||||
initProcess.on('close', (code) => {
|
|
||||||
if (code === 0) {
|
|
||||||
console.log('[MySQL] Initialized successfully with permissions granted');
|
|
||||||
// 删除临时SQL文件
|
|
||||||
try {
|
|
||||||
if (fs.existsSync(initSqlPath)) {
|
|
||||||
fs.unlinkSync(initSqlPath);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
// 忽略删除失败
|
|
||||||
}
|
|
||||||
resolve();
|
|
||||||
} else {
|
|
||||||
reject(new Error(`MySQL initialization failed with code ${code}`));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 启动MySQL服务
|
|
||||||
start(port = 3306) {
|
|
||||||
return new Promise(async (resolve, reject) => {
|
|
||||||
try {
|
|
||||||
// 确保数据库已初始化
|
|
||||||
await this.initialize();
|
|
||||||
|
|
||||||
const mysqld = path.join(this.binPath, 'mysqld.exe');
|
|
||||||
|
|
||||||
// 启动MySQL,指定端口
|
|
||||||
this.process = spawn(mysqld, [
|
|
||||||
'--console',
|
|
||||||
`--port=${port}`
|
|
||||||
], {
|
|
||||||
cwd: this.mysqlPath,
|
|
||||||
stdio: ['ignore', 'pipe', 'pipe']
|
|
||||||
});
|
|
||||||
|
|
||||||
this.currentPort = port;
|
|
||||||
|
|
||||||
// 将当前端口写入文件,供停止脚本使用
|
|
||||||
try {
|
|
||||||
const portFilePath = path.join(this.mysqlPath, '.running-port');
|
|
||||||
fs.writeFileSync(portFilePath, port.toString(), 'utf-8');
|
|
||||||
console.log(`[MySQL] Port ${port} recorded to ${portFilePath}`);
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[MySQL] Failed to record port:', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
let output = '';
|
|
||||||
this.process.stdout.on('data', (data) => {
|
|
||||||
output += data.toString();
|
|
||||||
console.log('MySQL:', data.toString());
|
|
||||||
|
|
||||||
// MySQL启动完成的标志
|
|
||||||
if (output.includes('ready for connections') || output.includes('MySQL Community Server')) {
|
|
||||||
console.log(`MySQL started successfully on port ${port}`);
|
|
||||||
|
|
||||||
// 自动授权 root 用户从任何主机连接
|
|
||||||
setTimeout(async () => {
|
|
||||||
try {
|
|
||||||
console.log('[MySQL] Waiting 3 seconds before granting permissions...');
|
|
||||||
await this.grantRootAccess();
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[MySQL] Failed to grant root access, but MySQL is running:', error.message);
|
|
||||||
}
|
|
||||||
resolve(port);
|
|
||||||
}, 3000);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
this.process.stderr.on('data', (data) => {
|
|
||||||
console.error('MySQL Error:', data.toString());
|
|
||||||
});
|
|
||||||
|
|
||||||
this.process.on('close', (code) => {
|
|
||||||
console.log(`MySQL process exited with code ${code}`);
|
|
||||||
this.process = null;
|
|
||||||
this.currentPort = null;
|
|
||||||
|
|
||||||
// 删除端口记录文件
|
|
||||||
try {
|
|
||||||
const portFilePath = path.join(this.mysqlPath, '.running-port');
|
|
||||||
if (fs.existsSync(portFilePath)) {
|
|
||||||
fs.unlinkSync(portFilePath);
|
|
||||||
console.log('[MySQL] Port record file removed');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[MySQL] Failed to remove port record:', error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// 超时处理
|
|
||||||
setTimeout(async () => {
|
|
||||||
if (this.process && !this.process.killed) {
|
|
||||||
console.log(`MySQL started on port ${port} (timeout reached, assuming success)`);
|
|
||||||
|
|
||||||
// 自动授权 root 用户从任何主机连接
|
|
||||||
try {
|
|
||||||
console.log('[MySQL] Granting permissions...');
|
|
||||||
await this.grantRootAccess();
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[MySQL] Failed to grant root access, but MySQL is running:', error.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
resolve(port);
|
|
||||||
}
|
|
||||||
}, 18000);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
reject(error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 授权 root 用户从 127.0.0.1 访问
|
|
||||||
grantRootAccess() {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
// 创建 SQL 文件
|
|
||||||
const sqlFilePath = path.join(this.mysqlPath, 'grant_root.sql');
|
|
||||||
const sqlContent = `
|
|
||||||
CREATE USER IF NOT EXISTS 'root'@'127.0.0.1' IDENTIFIED BY '';
|
|
||||||
GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1' WITH GRANT OPTION;
|
|
||||||
CREATE USER IF NOT EXISTS 'root'@'%' IDENTIFIED BY '';
|
|
||||||
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
|
|
||||||
FLUSH PRIVILEGES;
|
|
||||||
`;
|
|
||||||
|
|
||||||
try {
|
|
||||||
fs.writeFileSync(sqlFilePath, sqlContent, 'utf-8');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[MySQL] Failed to create grant SQL file:', error);
|
|
||||||
return resolve(); // 继续启动
|
|
||||||
}
|
|
||||||
|
|
||||||
const mysqlExe = path.join(this.binPath, 'mysql.exe');
|
|
||||||
const grantProcess = spawn(mysqlExe, [
|
|
||||||
'--host=localhost',
|
|
||||||
`--port=${this.currentPort}`,
|
|
||||||
'--user=root'
|
|
||||||
], {
|
|
||||||
cwd: this.mysqlPath,
|
|
||||||
stdio: ['pipe', 'pipe', 'pipe']
|
|
||||||
});
|
|
||||||
|
|
||||||
// 通过 stdin 输入 SQL
|
|
||||||
grantProcess.stdin.write(sqlContent);
|
|
||||||
grantProcess.stdin.end();
|
|
||||||
|
|
||||||
let output = '';
|
|
||||||
let errorOutput = '';
|
|
||||||
|
|
||||||
grantProcess.stdout.on('data', (data) => {
|
|
||||||
output += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
grantProcess.stderr.on('data', (data) => {
|
|
||||||
errorOutput += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
grantProcess.on('close', (code) => {
|
|
||||||
if (code === 0) {
|
|
||||||
console.log('[MySQL] Root user granted access from 127.0.0.1 and all hosts');
|
|
||||||
resolve();
|
|
||||||
} else {
|
|
||||||
console.error('[MySQL] Grant access failed (code:', code, ')');
|
|
||||||
console.error('[MySQL] Error output:', errorOutput);
|
|
||||||
console.error('[MySQL] Standard output:', output);
|
|
||||||
// 即使失败也 resolve,让应用继续启动
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取当前MySQL端口
|
|
||||||
getCurrentPort() {
|
|
||||||
return this.currentPort || 3306;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 停止MySQL服务
|
|
||||||
stop() {
|
|
||||||
return new Promise(async (resolve) => {
|
|
||||||
if (this.process && !this.process.killed) {
|
|
||||||
console.log('[MySQL] Stopping MySQL...');
|
|
||||||
|
|
||||||
// 方法1: 尝试使用 mysqladmin shutdown 优雅关闭
|
|
||||||
try {
|
|
||||||
console.log('[MySQL] Trying mysqladmin shutdown...');
|
|
||||||
const mysqladmin = path.join(this.binPath, 'mysqladmin.exe');
|
|
||||||
|
|
||||||
if (fs.existsSync(mysqladmin)) {
|
|
||||||
const shutdownProcess = spawn(mysqladmin, [
|
|
||||||
'-u', 'root',
|
|
||||||
'-pnjcnpqs',
|
|
||||||
'--port=' + this.currentPort,
|
|
||||||
'shutdown'
|
|
||||||
], {
|
|
||||||
cwd: this.mysqlPath,
|
|
||||||
stdio: 'ignore'
|
|
||||||
});
|
|
||||||
|
|
||||||
// 等待 mysqladmin 执行完成(最多5秒)
|
|
||||||
const shutdownPromise = new Promise((res) => {
|
|
||||||
shutdownProcess.on('close', (code) => {
|
|
||||||
console.log(`[MySQL] mysqladmin shutdown exited with code ${code}`);
|
|
||||||
res(code === 0);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const timeoutPromise = new Promise((res) => setTimeout(() => res(false), 5000));
|
|
||||||
const shutdownSuccess = await Promise.race([shutdownPromise, timeoutPromise]);
|
|
||||||
|
|
||||||
if (shutdownSuccess) {
|
|
||||||
console.log('[MySQL] Shutdown successful via mysqladmin');
|
|
||||||
// 等待进程真正退出
|
|
||||||
await new Promise((res) => {
|
|
||||||
if (this.process && !this.process.killed) {
|
|
||||||
this.process.on('close', res);
|
|
||||||
setTimeout(res, 2000); // 最多等2秒
|
|
||||||
} else {
|
|
||||||
res();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
this.cleanupPortFile();
|
|
||||||
return resolve();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[MySQL] mysqladmin shutdown failed:', error.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 方法2: 如果 mysqladmin 失败,尝试 SIGTERM
|
|
||||||
console.log('[MySQL] Trying SIGTERM...');
|
|
||||||
const killTimeout = setTimeout(() => {
|
|
||||||
// 方法3: 5秒后强制 SIGKILL
|
|
||||||
console.log('[MySQL] Force killing with SIGKILL');
|
|
||||||
try {
|
|
||||||
if (this.process && !this.process.killed) {
|
|
||||||
this.process.kill('SIGKILL');
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error('[MySQL] Error force killing:', e);
|
|
||||||
}
|
|
||||||
this.cleanupPortFile();
|
|
||||||
resolve();
|
|
||||||
}, 5000);
|
|
||||||
|
|
||||||
this.process.on('close', () => {
|
|
||||||
clearTimeout(killTimeout);
|
|
||||||
console.log('[MySQL] Process closed');
|
|
||||||
this.cleanupPortFile();
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
this.process.kill('SIGTERM');
|
|
||||||
} catch (e) {
|
|
||||||
console.error('[MySQL] Error sending SIGTERM:', e);
|
|
||||||
clearTimeout(killTimeout);
|
|
||||||
this.cleanupPortFile();
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// 没有进程引用,说明MySQL已经停止或不在我们控制下
|
|
||||||
console.log('[MySQL] No process reference, MySQL may already be stopped');
|
|
||||||
console.log('[MySQL] If MySQL is still running, please use kill-running-port.bat to clean up');
|
|
||||||
this.cleanupPortFile();
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 清理端口记录文件
|
|
||||||
cleanupPortFile() {
|
|
||||||
try {
|
|
||||||
const portFilePath = path.join(this.mysqlPath, '.running-port');
|
|
||||||
if (fs.existsSync(portFilePath)) {
|
|
||||||
fs.unlinkSync(portFilePath);
|
|
||||||
console.log('[MySQL] Port record file cleaned up');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[MySQL] Failed to cleanup port record:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取记录的运行端口
|
|
||||||
getRecordedPort() {
|
|
||||||
try {
|
|
||||||
const portFilePath = path.join(this.mysqlPath, '.running-port');
|
|
||||||
if (fs.existsSync(portFilePath)) {
|
|
||||||
const port = fs.readFileSync(portFilePath, 'utf-8').trim();
|
|
||||||
return parseInt(port);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[MySQL] Failed to read port record:', error);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取MySQL连接配置
|
|
||||||
getConnectionConfig() {
|
|
||||||
return {
|
|
||||||
host: 'localhost',
|
|
||||||
port: 3306,
|
|
||||||
user: 'root',
|
|
||||||
password: '',
|
|
||||||
database: 'app_db'
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = MySQLManager;
|
|
||||||
@@ -10,9 +10,8 @@ class StartupManager {
|
|||||||
this.loadingWindow = null;
|
this.loadingWindow = null;
|
||||||
this.steps = [
|
this.steps = [
|
||||||
{ id: 'init', label: '正在初始化应用...', progress: 0 },
|
{ id: 'init', label: '正在初始化应用...', progress: 0 },
|
||||||
{ id: 'check-mysql-port', label: '正在检测MySQL端口...', progress: 15 },
|
{ id: 'check-mysql-port', label: '正在检查MySQL服务...', progress: 20 },
|
||||||
{ id: 'start-mysql', label: '正在启动MySQL数据库...', progress: 30 },
|
{ id: 'wait-mysql', label: '确保MySQL服务运行...', progress: 40 },
|
||||||
{ id: 'wait-mysql', label: '等待MySQL就绪...', progress: 45 },
|
|
||||||
{ id: 'check-java-port', label: '正在检测后端服务端口...', progress: 60 },
|
{ id: 'check-java-port', label: '正在检测后端服务端口...', progress: 60 },
|
||||||
{ id: 'generate-config', label: '正在生成配置文件...', progress: 70 },
|
{ id: 'generate-config', label: '正在生成配置文件...', progress: 70 },
|
||||||
{ id: 'start-java', label: '正在启动后端服务...', progress: 80 },
|
{ id: 'start-java', label: '正在启动后端服务...', progress: 80 },
|
||||||
@@ -26,6 +25,11 @@ class StartupManager {
|
|||||||
* 创建 Loading 窗口
|
* 创建 Loading 窗口
|
||||||
*/
|
*/
|
||||||
createLoadingWindow() {
|
createLoadingWindow() {
|
||||||
|
const isDev = !process.resourcesPath;
|
||||||
|
const iconPath = isDev
|
||||||
|
? path.join(__dirname, '..', 'public', 'images', 'icon.png')
|
||||||
|
: path.join(process.resourcesPath, 'app.asar.unpacked', 'public', 'images', 'icon.png');
|
||||||
|
|
||||||
this.loadingWindow = new BrowserWindow({
|
this.loadingWindow = new BrowserWindow({
|
||||||
width: 500,
|
width: 500,
|
||||||
height: 300,
|
height: 300,
|
||||||
@@ -34,6 +38,7 @@ class StartupManager {
|
|||||||
resizable: false,
|
resizable: false,
|
||||||
alwaysOnTop: true,
|
alwaysOnTop: true,
|
||||||
skipTaskbar: true, // 不在任务栏显示
|
skipTaskbar: true, // 不在任务栏显示
|
||||||
|
icon: iconPath,
|
||||||
webPreferences: {
|
webPreferences: {
|
||||||
nodeIntegration: true,
|
nodeIntegration: true,
|
||||||
contextIsolation: false
|
contextIsolation: false
|
||||||
@@ -41,7 +46,12 @@ class StartupManager {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 加载 loading 页面
|
// 加载 loading 页面
|
||||||
const loadingHtml = path.join(__dirname, '../public/html/loading.html');
|
const isDev2 = !process.resourcesPath;
|
||||||
|
const loadingHtml = isDev2
|
||||||
|
? path.join(__dirname, '..', 'public', 'html', 'loading.html')
|
||||||
|
: path.join(process.resourcesPath, 'app.asar', 'public', 'html', 'loading.html');
|
||||||
|
|
||||||
|
console.log('[StartupManager] Loading HTML from:', loadingHtml);
|
||||||
this.loadingWindow.loadFile(loadingHtml);
|
this.loadingWindow.loadFile(loadingHtml);
|
||||||
|
|
||||||
return this.loadingWindow;
|
return this.loadingWindow;
|
||||||
|
|||||||
Reference in New Issue
Block a user