fix(client): 设备移除逻辑与认证流程优化
- 修改设备移除时的本地清理方法,统一调用 clearLocalAuth - 优化设备数量限制校验逻辑,避免重复计算当前设备- 移除冗余的设备状态检查,简化设备移除流程- 调整 Redis 连接超时与等待时间,提升连接稳定性- 增强 MySQL 数据库连接配置,添加自动重连机制 -优化 Druid 连接池参数,提高数据库连接性能 - 简化客户端认证与数据上报逻辑,提升处理效率 - 移除过期设备状态更新逻辑,减少不必要的数据库操作- 调整慢 SQL 记录阈值,便于及时发现性能问题-优化版本分布与数据类型统计查询逻辑,提高响应速度
This commit is contained in:
@@ -9,15 +9,12 @@
|
||||
"public/jre/**/*",
|
||||
"public/icon/**/*",
|
||||
"public/image/**/*",
|
||||
"public/splash.html"
|
||||
"public/splash.html",
|
||||
"public/config/**/*"
|
||||
],
|
||||
"directories": {
|
||||
"output": "dist"
|
||||
},
|
||||
"publish": {
|
||||
"provider": "generic",
|
||||
"url": "http://192.168.1.89:8085/static/updates/"
|
||||
},
|
||||
"nsis": {
|
||||
"oneClick": false,
|
||||
"perMachine": false,
|
||||
@@ -28,10 +25,8 @@
|
||||
"target": "nsis",
|
||||
"icon": "public/icon/icon.png"
|
||||
},
|
||||
"linux": {
|
||||
"target": ["snap"]
|
||||
},
|
||||
"files": [
|
||||
"package.json",
|
||||
{
|
||||
"from": "build/main",
|
||||
"to": "main",
|
||||
@@ -43,18 +38,10 @@
|
||||
"filter": ["**/*"]
|
||||
},
|
||||
{
|
||||
|
||||
"from": "src/main/static",
|
||||
"to": "static",
|
||||
"filter": ["**/*"]
|
||||
},
|
||||
{
|
||||
"from": "public",
|
||||
"to": "assets",
|
||||
"filter": [
|
||||
"erp_client_sb-*.jar"
|
||||
]
|
||||
},
|
||||
{
|
||||
"from": "public",
|
||||
"to": "public",
|
||||
@@ -63,58 +50,42 @@
|
||||
"icon/**/*",
|
||||
"image/**/*",
|
||||
"splash.html",
|
||||
"config/**/*",
|
||||
"!erp_client_sb-*.jar",
|
||||
"!data/**/*",
|
||||
"!jre/bin/jabswitch.exe",
|
||||
"!jre/bin/jaccessinspector.exe",
|
||||
"!jre/bin/jaccesswalker.exe",
|
||||
"!jre/bin/jar.exe",
|
||||
"!jre/bin/jarsigner.exe",
|
||||
"!jre/bin/javac.exe",
|
||||
"!jre/bin/javadoc.exe",
|
||||
"!jre/bin/javap.exe",
|
||||
"!jre/bin/jcmd.exe",
|
||||
"!jre/bin/jconsole.exe",
|
||||
"!jre/bin/jdb.exe",
|
||||
"!jre/bin/jdeprscan.exe",
|
||||
"!jre/bin/jdeps.exe",
|
||||
"!jre/bin/jfr.exe",
|
||||
"!jre/bin/jhsdb.exe",
|
||||
"!jre/bin/jimage.exe",
|
||||
"!jre/bin/jinfo.exe",
|
||||
"!jre/bin/jlink.exe",
|
||||
"!jre/bin/jmap.exe",
|
||||
"!jre/bin/jmod.exe",
|
||||
"!jre/bin/jpackage.exe",
|
||||
"!jre/bin/jps.exe",
|
||||
"!jre/bin/jrunscript.exe",
|
||||
"!jre/bin/jshell.exe",
|
||||
"!jre/bin/jstack.exe",
|
||||
"!jre/bin/jstat.exe",
|
||||
"!jre/bin/jstatd.exe",
|
||||
"!jre/bin/keytool.exe",
|
||||
"!jre/bin/kinit.exe",
|
||||
"!jre/bin/klist.exe",
|
||||
"!jre/bin/ktab.exe",
|
||||
"!jre/bin/rmiregistry.exe",
|
||||
"!jre/bin/serialver.exe",
|
||||
"!jre/bin/jab*.exe",
|
||||
"!jre/bin/jac*.exe",
|
||||
"!jre/bin/jar*.exe",
|
||||
"!jre/bin/jc*.exe",
|
||||
"!jre/bin/jd*.exe",
|
||||
"!jre/bin/jf*.exe",
|
||||
"!jre/bin/jh*.exe",
|
||||
"!jre/bin/ji*.exe",
|
||||
"!jre/bin/jl*.exe",
|
||||
"!jre/bin/jm*.exe",
|
||||
"!jre/bin/jp*.exe",
|
||||
"!jre/bin/jr*.exe",
|
||||
"!jre/bin/jsh*.exe",
|
||||
"!jre/bin/jst*.exe",
|
||||
"!jre/bin/k*.exe",
|
||||
"!jre/bin/rmi*.exe",
|
||||
"!jre/bin/serial*.exe",
|
||||
"!jre/include/**",
|
||||
"!jre/lib/src.zip",
|
||||
"!jre/lib/ct.sym",
|
||||
"!jre/lib/jvm.lib",
|
||||
"!icon/image.png",
|
||||
"!icon/img.png"
|
||||
"!jre/lib/jvm.lib"
|
||||
]
|
||||
},
|
||||
"!build",
|
||||
"!dist",
|
||||
"!scripts"
|
||||
}
|
||||
],
|
||||
"electronLanguages": ["en", "zh-CN"],
|
||||
"extraResources": [
|
||||
{
|
||||
"from": "update-helper.bat",
|
||||
"to": "../update-helper.bat"
|
||||
},
|
||||
{
|
||||
"from": "public",
|
||||
"to": "./",
|
||||
"filter": ["erp_client_sb-*.jar"]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"main": "main/main.js",
|
||||
"scripts": {
|
||||
"dev": "node scripts/dev-server.js",
|
||||
"build": "node scripts/build.js && electron-builder",
|
||||
"build:win": "node scripts/build.js && electron-builder --win",
|
||||
"build:mac": "node scripts/build.js && electron-builder --mac",
|
||||
"build:linux": "node scripts/build.js && electron-builder --linux"
|
||||
|
||||
52
electron-vue-template/public/config/logback.xml
Normal file
52
electron-vue-template/public/config/logback.xml
Normal file
@@ -0,0 +1,52 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<!-- 固定日志路径到系统公共数据目录 -->
|
||||
<property name="LOG_HOME" value="C:/ProgramData/erp-logs" />
|
||||
|
||||
<!-- 控制台输出 -->
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
<charset>UTF-8</charset>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- 文件输出 - 按天滚动 -->
|
||||
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_HOME}/spring-boot.log</file>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
<charset>UTF-8</charset>
|
||||
</encoder>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_HOME}/spring-boot-%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||
<maxHistory>30</maxHistory>
|
||||
<totalSizeCap>1GB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
</appender>
|
||||
|
||||
<!-- 设置根日志级别 - 同时输出到控制台和文件 -->
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
<appender-ref ref="FILE" />
|
||||
</root>
|
||||
|
||||
<!-- 设置特定包的日志级别 -->
|
||||
<logger name="com.tashow.erp" level="INFO" additivity="false">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
<appender-ref ref="FILE" />
|
||||
</logger>
|
||||
|
||||
<!-- 确保 Hibernate 日志也输出 -->
|
||||
<logger name="org.hibernate" level="INFO">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
<appender-ref ref="FILE" />
|
||||
</logger>
|
||||
|
||||
<!-- 确保 Spring 日志也输出 -->
|
||||
<logger name="org.springframework" level="INFO">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
<appender-ref ref="FILE" />
|
||||
</logger>
|
||||
</configuration>
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
import {app, BrowserWindow, ipcMain, Menu, screen, dialog} from 'electron';
|
||||
import {existsSync, createWriteStream, promises as fs, mkdirSync, copyFileSync} from 'fs';
|
||||
import {join, dirname} from 'path';
|
||||
import {existsSync, createWriteStream, promises as fs, mkdirSync, copyFileSync, readdirSync, writeFileSync} from 'fs';
|
||||
import {join, dirname, basename} from 'path';
|
||||
import {spawn, ChildProcess} from 'child_process';
|
||||
import * as https from 'https';
|
||||
import * as http from 'http';
|
||||
|
||||
const isDev = process.env.NODE_ENV === 'development';
|
||||
|
||||
let springProcess: ChildProcess | null = null;
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let splashWindow: BrowserWindow | null = null;
|
||||
let appOpened = false;
|
||||
let downloadProgress = {percentage: 0, current: '0 MB', total: '0 MB', speed: ''};
|
||||
let downloadProgress = {percentage: 0, current: '0 MB', total: '0 MB'};
|
||||
let isDownloading = false;
|
||||
let downloadedFilePath: string | null = null;
|
||||
let downloadedAsarPath: string | null = null;
|
||||
let downloadedJarPath: string | null = null;
|
||||
function openAppIfNotOpened() {
|
||||
if (appOpened) return;
|
||||
appOpened = true;
|
||||
@@ -20,8 +25,8 @@ function openAppIfNotOpened() {
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.show();
|
||||
mainWindow.focus();
|
||||
if (isDev) mainWindow.webContents.openDevTools();
|
||||
}
|
||||
// 安全关闭启动画面
|
||||
if (splashWindow && !splashWindow.isDestroyed()) {
|
||||
splashWindow.close();
|
||||
splashWindow = null;
|
||||
@@ -29,141 +34,75 @@ function openAppIfNotOpened() {
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
const rendererPort = process.argv[2] || 8083;
|
||||
mainWindow.loadURL(`http://localhost:${rendererPort}`);
|
||||
} else {
|
||||
mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
|
||||
}
|
||||
isDev
|
||||
? mainWindow.loadURL(`http://localhost:${process.argv[2] || 8083}`)
|
||||
: mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
|
||||
}
|
||||
}
|
||||
|
||||
// 通用资源路径获取函数
|
||||
function getResourcePath(devPath: string, prodPath: string, fallbackPath?: string): string {
|
||||
if (isDev) return join(__dirname, devPath);
|
||||
const bundledPath = join(process.resourcesPath, 'app.asar.unpacked', prodPath);
|
||||
if (existsSync(bundledPath)) return bundledPath;
|
||||
return fallbackPath ? join(__dirname, fallbackPath) : join(__dirname, prodPath);
|
||||
}
|
||||
|
||||
function getJavaExecutablePath(): string {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
return 'java';
|
||||
}
|
||||
|
||||
const bundledJavaPath = join(process.resourcesPath, 'app.asar.unpacked/public/jre/bin/java.exe');
|
||||
if (existsSync(bundledJavaPath)) {
|
||||
return bundledJavaPath;
|
||||
}
|
||||
|
||||
const devJavaPath = join(__dirname, '../../public/jre/bin/java.exe');
|
||||
if (existsSync(devJavaPath)) {
|
||||
return devJavaPath;
|
||||
}
|
||||
|
||||
return 'java';
|
||||
if (isDev) return 'java';
|
||||
const javaPath = getResourcePath('', 'public/jre/bin/java.exe');
|
||||
return existsSync(javaPath) ? javaPath : 'java';
|
||||
}
|
||||
|
||||
function findJarFile(directory: string): string {
|
||||
if (!existsSync(directory)) return '';
|
||||
|
||||
const files = require('fs').readdirSync(directory);
|
||||
const jarFile = files.find((f: string) => f.startsWith('erp_client_sb-') && f.endsWith('.jar'));
|
||||
|
||||
const jarFile = readdirSync(directory).find((f: string) => f.startsWith('erp_client_sb-') && f.endsWith('.jar'));
|
||||
return jarFile ? join(directory, jarFile) : '';
|
||||
}
|
||||
|
||||
function extractVersionFromJar(jarPath: string): string {
|
||||
if (!jarPath) return '';
|
||||
const match = require('path').basename(jarPath).match(/erp_client_sb-(\d+\.\d+\.\d+)\.jar/);
|
||||
return match?.[1] || '';
|
||||
}
|
||||
|
||||
function getJarFilePath(): string {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
return findJarFile(join(__dirname, '../../public'));
|
||||
}
|
||||
|
||||
const tempDir = join(app.getPath('temp'), 'erp-client');
|
||||
if (!existsSync(tempDir)) mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
const asarJarPath = findJarFile(join(__dirname, '../assets'));
|
||||
if (!asarJarPath) return '';
|
||||
|
||||
const asarFileName = require('path').basename(asarJarPath);
|
||||
const tempJarPath = join(tempDir, asarFileName);
|
||||
|
||||
// 如果临时目录版本不同,删除旧版本并复制新版本
|
||||
const existingJar = findJarFile(tempDir);
|
||||
if (existingJar && require('path').basename(existingJar) !== asarFileName) {
|
||||
require('fs').unlinkSync(existingJar);
|
||||
}
|
||||
|
||||
if (!existsSync(tempJarPath)) {
|
||||
copyFileSync(asarJarPath, tempJarPath);
|
||||
}
|
||||
|
||||
return tempJarPath;
|
||||
if (isDev) return findJarFile(join(__dirname, '../../public'));
|
||||
return findJarFile(process.resourcesPath);
|
||||
}
|
||||
|
||||
function getSplashPath(): string {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
return join(__dirname, '../../public/splash.html');
|
||||
}
|
||||
|
||||
const bundledSplashPath = join(process.resourcesPath, 'app.asar.unpacked/public/splash.html');
|
||||
if (existsSync(bundledSplashPath)) {
|
||||
return bundledSplashPath;
|
||||
}
|
||||
|
||||
return join(__dirname, '../../public/splash.html');
|
||||
}
|
||||
function getIconPath(): string {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
return join(__dirname, '../../public/icon/icon.png');
|
||||
}
|
||||
const bundledIconPath = join(process.resourcesPath, 'app.asar.unpacked/public/icon/icon.png');
|
||||
if (existsSync(bundledIconPath)) {
|
||||
return bundledIconPath;
|
||||
}
|
||||
|
||||
return join(__dirname, '../renderer/icon/icon.png');
|
||||
}
|
||||
const getSplashPath = () => getResourcePath('../../public/splash.html', 'public/splash.html');
|
||||
const getIconPath = () => getResourcePath('../../public/icon/icon.png', 'public/icon/icon.png', '../renderer/icon/icon.png');
|
||||
const getLogbackConfigPath = () => getResourcePath('../../public/config/logback.xml', 'public/config/logback.xml');
|
||||
|
||||
function getDataDirectoryPath(): string {
|
||||
// 将用户数据目录放在可写的应用数据目录下
|
||||
const userDataPath = app.getPath('userData');
|
||||
const dataDir = join(userDataPath, 'data');
|
||||
|
||||
// 确保数据目录存在
|
||||
if (!existsSync(dataDir)) {
|
||||
mkdirSync(dataDir, { recursive: true });
|
||||
}
|
||||
|
||||
const dataDir = join(app.getPath('userData'), 'data');
|
||||
if (!existsSync(dataDir)) mkdirSync(dataDir, {recursive: true});
|
||||
return dataDir;
|
||||
}
|
||||
|
||||
function migrateDataFromPublic(): void {
|
||||
// 如果是首次运行,尝试从public/data迁移数据
|
||||
if (!isDev) return;
|
||||
|
||||
const oldDataPath = join(__dirname, '../../public/data');
|
||||
if (!existsSync(oldDataPath)) return;
|
||||
|
||||
const newDataPath = getDataDirectoryPath();
|
||||
|
||||
if (process.env.NODE_ENV === 'development' && existsSync(oldDataPath)) {
|
||||
try {
|
||||
const files = require('fs').readdirSync(oldDataPath);
|
||||
for (const file of files) {
|
||||
const srcFile = join(oldDataPath, file);
|
||||
const destFile = join(newDataPath, file);
|
||||
|
||||
if (!existsSync(destFile)) {
|
||||
require('fs').copyFileSync(srcFile, destFile);
|
||||
}
|
||||
try {
|
||||
readdirSync(oldDataPath).forEach(file => {
|
||||
const destFile = join(newDataPath, file);
|
||||
if (!existsSync(destFile)) {
|
||||
copyFileSync(join(oldDataPath, file), destFile);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('数据迁移失败,使用默认配置');
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.log('数据迁移失败,使用默认配置');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function startSpringBoot() {
|
||||
migrateDataFromPublic();
|
||||
|
||||
const jarPath = getJarFilePath();
|
||||
const javaPath = getJavaExecutablePath();
|
||||
const dataDir = getDataDirectoryPath();
|
||||
|
||||
const logbackConfigPath = getLogbackConfigPath();
|
||||
|
||||
if (!existsSync(jarPath)) {
|
||||
dialog.showErrorBox('启动失败', `JAR 文件不存在:\n${jarPath}`);
|
||||
app.quit();
|
||||
@@ -175,19 +114,14 @@ function startSpringBoot() {
|
||||
const springArgs = [
|
||||
'-jar', jarPath,
|
||||
`--spring.datasource.url=jdbc:sqlite:${dataDir}/erp-cache.db`,
|
||||
`--logging.file.path=${dataDir}`,
|
||||
`--server.port=8081`
|
||||
`--server.port=8081`,
|
||||
`--logging.config=file:${logbackConfigPath}`
|
||||
];
|
||||
|
||||
// 工作目录设为数据目录,这样Spring Boot会在数据目录下创建临时文件
|
||||
springProcess = spawn(javaPath, springArgs, {
|
||||
cwd: dataDir,
|
||||
detached: false,
|
||||
env: {
|
||||
...process.env,
|
||||
'ERP_DATA_DIR': dataDir,
|
||||
'USER_DATA_DIR': dataDir
|
||||
}
|
||||
detached: false
|
||||
});
|
||||
|
||||
let startupCompleted = false;
|
||||
@@ -202,6 +136,16 @@ function startSpringBoot() {
|
||||
}
|
||||
});
|
||||
|
||||
springProcess.stderr?.on('data', (data) => {
|
||||
const output = data.toString();
|
||||
console.log('[Spring Boot]', output.trim());
|
||||
|
||||
if (!startupCompleted && (output.includes('Started Success') || output.includes('Started ErpClientSbApplication'))) {
|
||||
startupCompleted = true;
|
||||
openAppIfNotOpened();
|
||||
}
|
||||
});
|
||||
|
||||
springProcess.on('close', (code) => {
|
||||
mainWindow ? mainWindow.close() : app.quit();
|
||||
});
|
||||
@@ -226,7 +170,9 @@ function startSpringBoot() {
|
||||
app.quit();
|
||||
}
|
||||
}
|
||||
startSpringBoot();
|
||||
|
||||
startSpringBoot();
|
||||
|
||||
function stopSpringBoot() {
|
||||
if (!springProcess) return;
|
||||
try {
|
||||
@@ -264,11 +210,6 @@ function createWindow() {
|
||||
Menu.setApplicationMenu(null);
|
||||
mainWindow.setMenuBarVisibility(false);
|
||||
|
||||
// 打开开发者工具
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
mainWindow.webContents.openDevTools();
|
||||
}
|
||||
|
||||
// 监听窗口关闭事件,确保正确清理引用
|
||||
mainWindow.on('closed', () => {
|
||||
mainWindow = null;
|
||||
@@ -334,14 +275,29 @@ ipcMain.on('message', (event, message) => {
|
||||
console.log(message);
|
||||
});
|
||||
|
||||
ipcMain.handle('get-jar-version', () => extractVersionFromJar(getJarFilePath()));
|
||||
ipcMain.handle('get-jar-version', () => {
|
||||
const jarPath = getJarFilePath();
|
||||
const match = jarPath ? basename(jarPath).match(/erp_client_sb-(\d+\.\d+\.\d+)\.jar/) : null;
|
||||
return match?.[1] || '';
|
||||
});
|
||||
|
||||
function checkPendingUpdate() {
|
||||
try {
|
||||
const updateFilePath = join(process.resourcesPath, 'app.asar.update');
|
||||
const asarUpdatePath = join(process.resourcesPath, 'app.asar.update');
|
||||
const appAsarPath = join(process.resourcesPath, 'app.asar');
|
||||
|
||||
if (!existsSync(updateFilePath)) return;
|
||||
// 查找jar更新文件
|
||||
let jarUpdatePath = '';
|
||||
if (process.resourcesPath && existsSync(process.resourcesPath)) {
|
||||
const files = readdirSync(process.resourcesPath);
|
||||
const jarUpdateFile = files.find(f => f.startsWith('erp_client_sb-') && f.endsWith('.jar.update'));
|
||||
if (jarUpdateFile) {
|
||||
jarUpdatePath = join(process.resourcesPath, jarUpdateFile);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有任何更新文件,直接返回
|
||||
if (!existsSync(asarUpdatePath) && !jarUpdatePath) return;
|
||||
|
||||
const appDir = dirname(process.execPath);
|
||||
const helperPath = join(appDir, 'update-helper.bat');
|
||||
@@ -353,9 +309,9 @@ function checkPendingUpdate() {
|
||||
|
||||
const vbsPath = join(app.getPath('temp'), 'update-silent.vbs');
|
||||
const vbsContent = `Set WshShell = CreateObject("WScript.Shell")
|
||||
WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${appAsarPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${updateFilePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${process.execPath.replace(/\\/g, '\\\\')}" & Chr(34), 0, False`;
|
||||
WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${appAsarPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${asarUpdatePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${jarUpdatePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${process.execPath.replace(/\\/g, '\\\\')}" & Chr(34), 0, False`;
|
||||
|
||||
require('fs').writeFileSync(vbsPath, vbsContent);
|
||||
writeFileSync(vbsPath, vbsContent);
|
||||
|
||||
spawn('wscript.exe', [vbsPath], {
|
||||
detached: true,
|
||||
@@ -369,53 +325,86 @@ WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " &
|
||||
}
|
||||
}
|
||||
|
||||
ipcMain.handle('download-update', async (event, downloadUrl: string) => {
|
||||
ipcMain.handle('download-update', async (event, downloadUrls: {asarUrl?: string, jarUrl?: string}) => {
|
||||
if (isDownloading) return {success: false, error: '正在下载中'};
|
||||
if (downloadedFilePath === 'completed') return {success: true, filePath: 'already-completed'};
|
||||
|
||||
isDownloading = true;
|
||||
let totalDownloaded = 0;
|
||||
let totalSize = 0;
|
||||
|
||||
try {
|
||||
const tempPath = join(app.getPath('temp'), 'app.asar.new');
|
||||
// 获取总大小
|
||||
const sizes = await Promise.all([
|
||||
downloadUrls.asarUrl ? getFileSize(downloadUrls.asarUrl) : 0,
|
||||
downloadUrls.jarUrl ? getFileSize(downloadUrls.jarUrl) : 0
|
||||
]);
|
||||
totalSize = sizes[0] + sizes[1];
|
||||
|
||||
await downloadFile(downloadUrl, tempPath, (progress) => {
|
||||
downloadProgress = progress;
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send('download-progress', progress);
|
||||
// 下载asar文件
|
||||
if (downloadUrls.asarUrl) {
|
||||
const tempAsarPath = join(app.getPath('temp'), 'app.asar.new');
|
||||
const asarSize = sizes[0];
|
||||
|
||||
await downloadFile(downloadUrls.asarUrl, tempAsarPath, (progress) => {
|
||||
const combinedProgress = {
|
||||
percentage: Math.round(((totalDownloaded + progress.downloaded) / totalSize) * 100),
|
||||
current: `${((totalDownloaded + progress.downloaded) / 1024 / 1024).toFixed(1)} MB`,
|
||||
total: `${(totalSize / 1024 / 1024).toFixed(1)} MB`
|
||||
};
|
||||
downloadProgress = combinedProgress;
|
||||
if (mainWindow) mainWindow.webContents.send('download-progress', combinedProgress);
|
||||
});
|
||||
|
||||
const asarUpdatePath = join(process.resourcesPath, 'app.asar.update');
|
||||
await fs.copyFile(tempAsarPath, asarUpdatePath);
|
||||
await fs.unlink(tempAsarPath);
|
||||
downloadedAsarPath = asarUpdatePath;
|
||||
totalDownloaded += asarSize;
|
||||
}
|
||||
|
||||
// 下载jar文件
|
||||
if (downloadUrls.jarUrl) {
|
||||
let jarFileName = basename(downloadUrls.jarUrl);
|
||||
if (!jarFileName.match(/^erp_client_sb-[\d.]+\.jar$/)) {
|
||||
const currentJar = getJarFilePath();
|
||||
const versionMatch = currentJar ? basename(currentJar).match(/erp_client_sb-([\d.]+)\.jar/) : null;
|
||||
if (versionMatch && versionMatch[1]) {
|
||||
const versionParts = versionMatch[1].split('.');
|
||||
versionParts[2] = String(Number(versionParts[2]) + 1);
|
||||
jarFileName = `erp_client_sb-${versionParts.join('.')}.jar`;
|
||||
} else {
|
||||
jarFileName = 'erp_client_sb-2.4.7.jar';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const tempJarPath = join(app.getPath('temp'), jarFileName);
|
||||
|
||||
if (!existsSync(tempPath)) {
|
||||
throw new Error('下载文件不存在');
|
||||
}
|
||||
await downloadFile(downloadUrls.jarUrl, tempJarPath, (progress) => {
|
||||
const combinedProgress = {
|
||||
percentage: Math.round(((totalDownloaded + progress.downloaded) / totalSize) * 100),
|
||||
current: `${((totalDownloaded + progress.downloaded) / 1024 / 1024).toFixed(1)} MB`,
|
||||
total: `${(totalSize / 1024 / 1024).toFixed(1)} MB`
|
||||
};
|
||||
downloadProgress = combinedProgress;
|
||||
if (mainWindow) mainWindow.webContents.send('download-progress', combinedProgress);
|
||||
});
|
||||
|
||||
const fileStats = await fs.stat(tempPath);
|
||||
if (fileStats.size < 1000) {
|
||||
throw new Error('下载文件过小');
|
||||
}
|
||||
|
||||
const updateFilePath = join(process.resourcesPath, 'app.asar.update');
|
||||
await fs.copyFile(tempPath, updateFilePath);
|
||||
await fs.unlink(tempPath);
|
||||
|
||||
if (!existsSync(updateFilePath)) {
|
||||
throw new Error('更新文件保存失败');
|
||||
const jarUpdatePath = join(process.resourcesPath, jarFileName + '.update');
|
||||
await fs.copyFile(tempJarPath, jarUpdatePath);
|
||||
await fs.unlink(tempJarPath);
|
||||
downloadedJarPath = jarUpdatePath;
|
||||
}
|
||||
|
||||
downloadedFilePath = 'completed';
|
||||
isDownloading = false;
|
||||
|
||||
return {success: true, filePath: updateFilePath};
|
||||
return {success: true, asarPath: downloadedAsarPath, jarPath: downloadedJarPath};
|
||||
} catch (error: unknown) {
|
||||
isDownloading = false;
|
||||
downloadedFilePath = null;
|
||||
|
||||
const tempPath = join(app.getPath('temp'), 'app.asar.new');
|
||||
if (existsSync(tempPath)) {
|
||||
fs.unlink(tempPath).catch(() => {
|
||||
});
|
||||
}
|
||||
|
||||
downloadedAsarPath = null;
|
||||
downloadedJarPath = null;
|
||||
return {success: false, error: error instanceof Error ? error.message : '下载失败'};
|
||||
}
|
||||
});
|
||||
@@ -426,26 +415,37 @@ ipcMain.handle('get-download-progress', () => {
|
||||
|
||||
ipcMain.handle('install-update', async () => {
|
||||
try {
|
||||
const updateFilePath = join(process.resourcesPath, 'app.asar.update');
|
||||
const hasUpdateFile = existsSync(updateFilePath);
|
||||
const asarUpdatePath = join(process.resourcesPath, 'app.asar.update');
|
||||
const hasAsarUpdate = existsSync(asarUpdatePath);
|
||||
|
||||
// 查找jar更新文件
|
||||
let jarUpdatePath = '';
|
||||
if (process.resourcesPath && existsSync(process.resourcesPath)) {
|
||||
const files = readdirSync(process.resourcesPath);
|
||||
const jarUpdateFile = files.find(f => f.startsWith('erp_client_sb-') && f.endsWith('.jar.update'));
|
||||
if (jarUpdateFile) {
|
||||
jarUpdatePath = join(process.resourcesPath, jarUpdateFile);
|
||||
}
|
||||
}
|
||||
|
||||
if (!downloadedFilePath || (downloadedFilePath !== 'completed' && !hasUpdateFile)) {
|
||||
if (!hasAsarUpdate && !jarUpdatePath) {
|
||||
return {success: false, error: '更新文件不存在'};
|
||||
}
|
||||
|
||||
const appDir = dirname(process.execPath);
|
||||
const helperPath = join(appDir, 'update-helper.bat');
|
||||
const appAsarPath = join(process.resourcesPath, 'app.asar');
|
||||
|
||||
if (!existsSync(helperPath)) {
|
||||
return {success: false, error: '更新助手不存在'};
|
||||
}
|
||||
|
||||
const appAsarPath = join(process.resourcesPath, 'app.asar');
|
||||
|
||||
const vbsPath = join(app.getPath('temp'), 'update-install.vbs');
|
||||
const vbsContent = `Set WshShell = CreateObject("WScript.Shell")
|
||||
WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${appAsarPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${updateFilePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${process.execPath.replace(/\\/g, '\\\\')}" & Chr(34), 0, False`;
|
||||
WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${appAsarPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${asarUpdatePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${jarUpdatePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${process.execPath.replace(/\\/g, '\\\\')}" & Chr(34), 0, False`;
|
||||
|
||||
require('fs').writeFileSync(vbsPath, vbsContent);
|
||||
writeFileSync(vbsPath, vbsContent);
|
||||
|
||||
spawn('wscript.exe', [vbsPath], {
|
||||
detached: true,
|
||||
@@ -455,6 +455,8 @@ WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " &
|
||||
|
||||
setTimeout(() => {
|
||||
downloadedFilePath = null;
|
||||
downloadedAsarPath = null;
|
||||
downloadedJarPath = null;
|
||||
app.quit();
|
||||
}, 500);
|
||||
|
||||
@@ -466,8 +468,10 @@ WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " &
|
||||
|
||||
ipcMain.handle('cancel-download', () => {
|
||||
isDownloading = false;
|
||||
downloadProgress = {percentage: 0, current: '0 MB', total: '0 MB', speed: ''};
|
||||
downloadProgress = {percentage: 0, current: '0 MB', total: '0 MB'};
|
||||
downloadedFilePath = null;
|
||||
downloadedAsarPath = null;
|
||||
downloadedJarPath = null;
|
||||
return {success: true};
|
||||
});
|
||||
|
||||
@@ -492,7 +496,17 @@ ipcMain.handle('write-file', async (event, filePath: string, data: Uint8Array) =
|
||||
});
|
||||
|
||||
|
||||
async function downloadFile(url: string, filePath: string, onProgress: (progress: any) => void): Promise<void> {
|
||||
async function getFileSize(url: string): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const protocol = url.startsWith('https') ? https : http;
|
||||
protocol.get(url, {method: 'HEAD'}, (response) => {
|
||||
const size = parseInt(response.headers['content-length'] || '0', 10);
|
||||
resolve(size);
|
||||
}).on('error', () => resolve(0));
|
||||
});
|
||||
}
|
||||
|
||||
async function downloadFile(url: string, filePath: string, onProgress: (progress: {downloaded: number}) => void): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const protocol = url.startsWith('https') ? https : http;
|
||||
|
||||
@@ -502,22 +516,12 @@ async function downloadFile(url: string, filePath: string, onProgress: (progress
|
||||
return;
|
||||
}
|
||||
|
||||
const totalBytes = parseInt(response.headers['content-length'] || '0', 10);
|
||||
let downloadedBytes = 0;
|
||||
const startTime = Date.now();
|
||||
|
||||
const fileStream = createWriteStream(filePath);
|
||||
|
||||
response.on('data', (chunk) => {
|
||||
downloadedBytes += chunk.length;
|
||||
|
||||
const percentage = totalBytes > 0 ? Math.round((downloadedBytes / totalBytes) * 100) : 0;
|
||||
const current = `${(downloadedBytes / 1024 / 1024).toFixed(1)} MB`;
|
||||
const total = `${(totalBytes / 1024 / 1024).toFixed(1)} MB`;
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
const speed = elapsed > 0 ? `${((downloadedBytes / elapsed) / 1024 / 1024).toFixed(1)} MB/s` : '';
|
||||
|
||||
onProgress({percentage, current, total, speed});
|
||||
onProgress({downloaded: downloadedBytes});
|
||||
});
|
||||
|
||||
response.pipe(fileStream);
|
||||
@@ -528,8 +532,7 @@ async function downloadFile(url: string, filePath: string, onProgress: (progress
|
||||
});
|
||||
|
||||
fileStream.on('error', (error) => {
|
||||
fs.unlink(filePath).catch(() => {
|
||||
});
|
||||
fs.unlink(filePath).catch(() => {});
|
||||
reject(error);
|
||||
});
|
||||
|
||||
|
||||
@@ -304,7 +304,7 @@ const SSEManager = {
|
||||
console.log('SSE连接已就绪')
|
||||
break
|
||||
case 'DEVICE_REMOVED':
|
||||
logout()
|
||||
clearLocalAuth()
|
||||
ElMessage.warning('您的设备已被移除,请重新登录')
|
||||
break
|
||||
case 'FORCE_LOGOUT':
|
||||
@@ -390,7 +390,7 @@ async function confirmRemoveDevice(row: DeviceItem & { isCurrent?: boolean }) {
|
||||
deviceQuota.value.used = Math.max(0, (deviceQuota.value.used || 0) - 1)
|
||||
|
||||
if (row.deviceId === getClientIdFromToken()) {
|
||||
clearLocalAuth() // 移除当前设备:只清理本地状态,不调用offline(避免覆盖removed状态)
|
||||
clearLocalAuth()
|
||||
}
|
||||
|
||||
ElMessage.success('已移除设备')
|
||||
|
||||
@@ -21,11 +21,6 @@ export const deviceApi = {
|
||||
return http.post('/monitor/device/remove', payload)
|
||||
},
|
||||
|
||||
heartbeat(payload: { username: string; deviceId: string; version?: string }) {
|
||||
// 直接调用 RuoYi 后端的心跳接口
|
||||
return http.post('/monitor/device/heartbeat', payload)
|
||||
},
|
||||
|
||||
offline(payload: { deviceId: string }) {
|
||||
// 直接调用 RuoYi 后端的离线接口
|
||||
return http.post('/monitor/device/offline', payload)
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
v{{ version || '-' }}
|
||||
<span v-if="hasNewVersion" class="update-badge"></span>
|
||||
</div>
|
||||
<el-dialog v-model="show" width="522px" :close-on-click-modal="false" align-center class="update-dialog"
|
||||
<el-dialog v-model="show" width="522px" :close-on-click-modal="false" align-center
|
||||
:class="['update-dialog', `stage-${stage}`]"
|
||||
:title="stage === 'downloading' ? `正在更新 ${appName}` : '软件更新'">
|
||||
<div v-if="stage === 'check'" class="update-content">
|
||||
<div class="update-layout">
|
||||
@@ -48,7 +49,7 @@
|
||||
</div>
|
||||
<div class="download-content">
|
||||
<div class="download-info">
|
||||
<p>正在下载更新</p>
|
||||
<p>正在下载安装...</p>
|
||||
</div>
|
||||
<div class="download-progress">
|
||||
<el-progress
|
||||
@@ -65,26 +66,29 @@
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="stage === 'completed'" class="update-content">
|
||||
<div class="update-header text-center">
|
||||
<img src="/icon/icon.png" class="app-icon" alt="App Icon"/>
|
||||
<h3>更新完成</h3>
|
||||
<p>更新文件已下载,将在重启后自动应用</p>
|
||||
</div>
|
||||
|
||||
<div class="download-progress">
|
||||
<div class="progress-info">
|
||||
<span>{{ prog.current }} / {{ prog.total }}</span>
|
||||
<div class="download-main">
|
||||
<div class="download-icon">
|
||||
<img src="/icon/icon.png" class="app-icon" alt="App Icon"/>
|
||||
</div>
|
||||
<div class="download-content">
|
||||
<div class="download-info">
|
||||
<p>可以开始安装了</p>
|
||||
</div>
|
||||
<div class="download-progress">
|
||||
<el-progress
|
||||
:percentage="100"
|
||||
:show-text="false"
|
||||
:stroke-width="6"
|
||||
color="#67C23A"/>
|
||||
<div class="progress-details">
|
||||
<span style="font-weight: 500" v-if="prog.current !== '0 MB' && prog.total !== '0 MB'">{{ prog.current }} / {{ prog.total }}</span>
|
||||
<span style="font-weight: 500" v-else>下载完成</span>
|
||||
<div class="action-buttons">
|
||||
<el-button size="small" type="primary" @click="installUpdate">立即重启</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<el-progress
|
||||
:percentage="100"
|
||||
:show-text="false"
|
||||
:stroke-width="6"
|
||||
color="#67C23A"/>
|
||||
</div>
|
||||
|
||||
<div class="update-buttons">
|
||||
<el-button @click="cancelDownload">稍后更新</el-button>
|
||||
<el-button type="primary" @click="installUpdate">重启应用新版本</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</el-dialog>
|
||||
@@ -92,7 +96,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import {ref, computed, onMounted, onUnmounted} from 'vue'
|
||||
import {ref, computed, onMounted, onUnmounted, watch} from 'vue'
|
||||
import {ElMessage, ElMessageBox} from 'element-plus'
|
||||
import {updateApi} from '../../api/update'
|
||||
|
||||
@@ -109,11 +113,13 @@ const stage = ref<Stage>('check')
|
||||
const appName = ref('我了个电商')
|
||||
const version = ref('')
|
||||
const hasNewVersion = ref(false) // 控制小红点显示
|
||||
const prog = ref({percentage: 0, current: '0 MB', total: '0 MB', speed: ''})
|
||||
const prog = ref({percentage: 0, current: '0 MB', total: '0 MB'})
|
||||
const info = ref({
|
||||
latestVersion: '2.4.8',
|
||||
downloadUrl: '',
|
||||
updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性\n• 增加了新的功能模块\n• 优化了数据处理性能',
|
||||
asarUrl: '',
|
||||
jarUrl: '',
|
||||
updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性',
|
||||
currentVersion: '',
|
||||
hasUpdate: false
|
||||
})
|
||||
@@ -140,7 +146,9 @@ async function autoCheck(silent = false) {
|
||||
currentVersion: result.currentVersion,
|
||||
latestVersion: result.latestVersion,
|
||||
downloadUrl: result.downloadUrl || '',
|
||||
updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性\n• 轻量级更新(仅替换app.asar)',
|
||||
asarUrl: result.asarUrl || '',
|
||||
jarUrl: result.jarUrl || '',
|
||||
updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性\n• 同步更新前端和后端',
|
||||
hasUpdate: true
|
||||
}
|
||||
hasNewVersion.value = true
|
||||
@@ -176,8 +184,10 @@ async function autoCheck(silent = false) {
|
||||
function handleVersionClick() {
|
||||
// 如果有新版本,直接显示更新对话框
|
||||
if (hasNewVersion.value) {
|
||||
show.value = true
|
||||
// 重置状态确保从检查阶段开始
|
||||
stage.value = 'check'
|
||||
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
|
||||
show.value = true
|
||||
} else {
|
||||
// 没有新版本,执行检查更新
|
||||
autoCheck(false)
|
||||
@@ -196,29 +206,35 @@ function remindLater() {
|
||||
}
|
||||
|
||||
async function start() {
|
||||
if (!info.value.downloadUrl) {
|
||||
if (!info.value.asarUrl && !info.value.jarUrl) {
|
||||
ElMessage.error('下载链接不可用')
|
||||
return
|
||||
}
|
||||
|
||||
stage.value = 'downloading'
|
||||
prog.value = {percentage: 0, current: '0 MB', total: '0 MB', speed: ''}
|
||||
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
|
||||
|
||||
;(window as any).electronAPI.onDownloadProgress((progress: any) => {
|
||||
prog.value = {
|
||||
percentage: progress.percentage || 0,
|
||||
current: progress.current || '0 MB',
|
||||
total: progress.total || '0 MB',
|
||||
speed: progress.speed || ''
|
||||
total: progress.total || '0 MB'
|
||||
}
|
||||
})
|
||||
|
||||
try {
|
||||
const response = await (window as any).electronAPI.downloadUpdate(info.value.downloadUrl)
|
||||
const response = await (window as any).electronAPI.downloadUpdate({
|
||||
asarUrl: info.value.asarUrl,
|
||||
jarUrl: info.value.jarUrl
|
||||
})
|
||||
|
||||
if (response.success) {
|
||||
stage.value = 'completed'
|
||||
prog.value.percentage = 100
|
||||
// 如果没有有效的进度信息,设置默认值
|
||||
if (prog.value.current === '0 MB' && prog.value.total === '0 MB') {
|
||||
// 保持原有的"0 MB"值,让模板中的条件判断来处理显示
|
||||
}
|
||||
ElMessage.success('下载完成')
|
||||
} else {
|
||||
ElMessage.error('下载失败: ' + (response.error || '未知错误'))
|
||||
@@ -270,6 +286,15 @@ onMounted(async () => {
|
||||
await autoCheck(true)
|
||||
})
|
||||
|
||||
// 监听对话框关闭,重置状态
|
||||
watch(show, (newValue) => {
|
||||
if (!newValue) {
|
||||
// 对话框关闭时重置状态
|
||||
stage.value = 'check'
|
||||
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
(window as any).electronAPI.removeDownloadProgressListener()
|
||||
})
|
||||
@@ -320,11 +345,39 @@ onUnmounted(() => {
|
||||
box-shadow: 0 24px 48px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
:deep(.update-dialog .el-dialog__header) {
|
||||
/* 通用标题样式 */
|
||||
:deep(.update-dialog .el-dialog__title) {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
/* 默认标题样式(第一阶段 - 检查阶段) */
|
||||
:deep(.update-dialog.stage-check .el-dialog__header) {
|
||||
display: block;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* 第二阶段 - 下载中,标题居中 */
|
||||
:deep(.update-dialog.stage-downloading .el-dialog__header) {
|
||||
display: block;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
:deep(.update-dialog.stage-downloading .el-dialog__title) {
|
||||
margin-left: 20px;
|
||||
}
|
||||
|
||||
/* 第三阶段 - 下载完成,标题居中 */
|
||||
:deep(.update-dialog.stage-completed .el-dialog__header) {
|
||||
display: block;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
:deep(.update-dialog.stage-completed .el-dialog__title) {
|
||||
margin-left: 20px;
|
||||
}
|
||||
|
||||
:deep(.update-dialog .el-dialog__body) {
|
||||
padding: 0;
|
||||
}
|
||||
@@ -538,6 +591,11 @@ onUnmounted(() => {
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
:deep(.el-progress-bar__outer) {
|
||||
border-radius: 4px;
|
||||
background-color: #e5e7eb;
|
||||
|
||||
@@ -3,86 +3,77 @@ setlocal enabledelayedexpansion
|
||||
|
||||
set APP_ASAR=%~1
|
||||
set UPDATE_FILE=%~2
|
||||
set EXE_PATH=%~3
|
||||
set LOG_FILE=%TEMP%\electron-update.log
|
||||
set JAR_UPDATE=%~3
|
||||
set EXE_PATH=%~4
|
||||
|
||||
echo ======================================== > "%LOG_FILE%"
|
||||
echo Electron App Auto-Update Helper >> "%LOG_FILE%"
|
||||
echo Started: %date% %time% >> "%LOG_FILE%"
|
||||
echo ======================================== >> "%LOG_FILE%"
|
||||
echo. >> "%LOG_FILE%"
|
||||
if not exist "%UPDATE_FILE%" if "%JAR_UPDATE%"=="" exit /b 1
|
||||
if not exist "%UPDATE_FILE%" if not exist "%JAR_UPDATE%" exit /b 1
|
||||
|
||||
if not exist "%UPDATE_FILE%" (
|
||||
echo [ERROR] Update file not found: %UPDATE_FILE% >> "%LOG_FILE%"
|
||||
goto :start_app
|
||||
)
|
||||
|
||||
echo [INFO] Update file found: %UPDATE_FILE% >> "%LOG_FILE%"
|
||||
echo [INFO] Target app.asar: %APP_ASAR% >> "%LOG_FILE%"
|
||||
echo [INFO] Application exe: %EXE_PATH% >> "%LOG_FILE%"
|
||||
echo [INFO] Waiting for application to close... >> "%LOG_FILE%"
|
||||
|
||||
REM 获取应用进程名
|
||||
REM Wait for application to close
|
||||
for /f "tokens=*" %%a in ("%EXE_PATH%") do set EXE_NAME=%%~nxa
|
||||
echo [INFO] Waiting for %EXE_NAME% to close... >> "%LOG_FILE%"
|
||||
|
||||
REM 等待应用进程完全关闭(最多等待10秒)
|
||||
set COUNT=0
|
||||
:wait_loop
|
||||
tasklist /FI "IMAGENAME eq %EXE_NAME%" 2>nul | find /I "%EXE_NAME%" >nul
|
||||
if errorlevel 1 goto process_closed
|
||||
set /a COUNT+=1
|
||||
if %COUNT% GEQ 20 (
|
||||
echo [WARN] Application still running after 10 seconds >> "%LOG_FILE%"
|
||||
goto process_closed
|
||||
)
|
||||
if %COUNT% GEQ 20 goto process_closed
|
||||
timeout /t 1 /nobreak >nul
|
||||
goto wait_loop
|
||||
|
||||
:process_closed
|
||||
echo [INFO] Application process closed >> "%LOG_FILE%"
|
||||
timeout /t 1 /nobreak >nul
|
||||
|
||||
echo [INFO] Backing up current app.asar... >> "%LOG_FILE%"
|
||||
if exist "%APP_ASAR%.backup" (
|
||||
del /f /q "%APP_ASAR%.backup" >nul 2>&1
|
||||
REM Update ASAR
|
||||
if exist "%UPDATE_FILE%" (
|
||||
if exist "%APP_ASAR%.backup" del /f /q "%APP_ASAR%.backup" >nul 2>&1
|
||||
if exist "%APP_ASAR%" move /y "%APP_ASAR%" "%APP_ASAR%.backup" >nul 2>&1
|
||||
move /y "%UPDATE_FILE%" "%APP_ASAR%" >nul 2>&1
|
||||
if errorlevel 1 if exist "%APP_ASAR%.backup" move /y "%APP_ASAR%.backup" "%APP_ASAR%" >nul 2>&1
|
||||
if exist "%UPDATE_FILE%" del /f /q "%UPDATE_FILE%" >nul 2>&1
|
||||
)
|
||||
|
||||
if exist "%APP_ASAR%" (
|
||||
move /y "%APP_ASAR%" "%APP_ASAR%.backup" >nul 2>&1
|
||||
REM Update JAR
|
||||
:update_jar
|
||||
if "%JAR_UPDATE%"=="" goto :start_app
|
||||
if not exist "%JAR_UPDATE%" goto :start_app
|
||||
timeout /t 3 /nobreak >nul
|
||||
for %%I in ("%APP_ASAR%") do set RESOURCES_DIR=%%~dpI
|
||||
for %%F in ("%JAR_UPDATE%") do set JAR_NAME=%%~nF
|
||||
echo %JAR_NAME% | findstr /B /C:"erp_client_sb-" >nul
|
||||
if errorlevel 1 (
|
||||
for /f "tokens=1-3 delims=/ " %%a in ("%date%") do set TODAY=%%a%%b%%c
|
||||
for /f "tokens=1-3 delims=:." %%a in ("%time%") do set NOW=%%a%%b%%c
|
||||
set JAR_NAME=erp_client_sb-2.4.7-!TODAY!!NOW!.jar
|
||||
)
|
||||
|
||||
REM Delete old JAR files
|
||||
for %%F in ("%RESOURCES_DIR%erp_client_sb-*.jar") do (
|
||||
set RETRY_COUNT=0
|
||||
:retry_delete
|
||||
del /f /q "%%F" >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo [WARN] First move attempt failed, retrying... >> "%LOG_FILE%"
|
||||
timeout /t 2 /nobreak >nul
|
||||
move /y "%APP_ASAR%" "%APP_ASAR%.backup" >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] Failed to backup app.asar, file is locked >> "%LOG_FILE%"
|
||||
goto :start_app
|
||||
set /a RETRY_COUNT+=1
|
||||
if !RETRY_COUNT! LEQ 5 (
|
||||
timeout /t 2 /nobreak >nul
|
||||
goto :retry_delete
|
||||
)
|
||||
)
|
||||
echo [SUCCESS] Backup completed >> "%LOG_FILE%"
|
||||
)
|
||||
|
||||
echo [INFO] Applying update... >> "%LOG_FILE%"
|
||||
move /y "%UPDATE_FILE%" "%APP_ASAR%" >nul 2>&1
|
||||
|
||||
REM Install new JAR file
|
||||
set NEW_JAR_PATH=%RESOURCES_DIR%%JAR_NAME%
|
||||
set INSTALL_RETRY=0
|
||||
:retry_install
|
||||
move /y "%JAR_UPDATE%" "%NEW_JAR_PATH%" >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] Failed to apply update >> "%LOG_FILE%"
|
||||
if exist "%APP_ASAR%.backup" (
|
||||
echo [INFO] Restoring backup... >> "%LOG_FILE%"
|
||||
move /y "%APP_ASAR%.backup" "%APP_ASAR%" >nul 2>&1
|
||||
set /a INSTALL_RETRY+=1
|
||||
if %INSTALL_RETRY% LEQ 5 (
|
||||
timeout /t 2 /nobreak >nul
|
||||
goto :retry_install
|
||||
)
|
||||
goto :start_app
|
||||
)
|
||||
|
||||
echo [SUCCESS] Update applied successfully! >> "%LOG_FILE%"
|
||||
|
||||
if exist "%UPDATE_FILE%" (
|
||||
del /f /q "%UPDATE_FILE%" >nul 2>&1
|
||||
)
|
||||
if exist "%JAR_UPDATE%" del /f /q "%JAR_UPDATE%" >nul 2>&1
|
||||
|
||||
:start_app
|
||||
echo [INFO] Restarting application... >> "%LOG_FILE%"
|
||||
echo ======================================== >> "%LOG_FILE%"
|
||||
|
||||
start "" "%EXE_PATH%"
|
||||
exit /b 0
|
||||
|
||||
Reference in New Issue
Block a user