fix(client): 设备移除逻辑与认证流程优化
- 修改设备移除时的本地清理方法,统一调用 clearLocalAuth - 优化设备数量限制校验逻辑,避免重复计算当前设备- 移除冗余的设备状态检查,简化设备移除流程- 调整 Redis 连接超时与等待时间,提升连接稳定性- 增强 MySQL 数据库连接配置,添加自动重连机制 -优化 Druid 连接池参数,提高数据库连接性能 - 简化客户端认证与数据上报逻辑,提升处理效率 - 移除过期设备状态更新逻辑,减少不必要的数据库操作- 调整慢 SQL 记录阈值,便于及时发现性能问题-优化版本分布与数据类型统计查询逻辑,提高响应速度
This commit is contained in:
@@ -9,15 +9,12 @@
|
|||||||
"public/jre/**/*",
|
"public/jre/**/*",
|
||||||
"public/icon/**/*",
|
"public/icon/**/*",
|
||||||
"public/image/**/*",
|
"public/image/**/*",
|
||||||
"public/splash.html"
|
"public/splash.html",
|
||||||
|
"public/config/**/*"
|
||||||
],
|
],
|
||||||
"directories": {
|
"directories": {
|
||||||
"output": "dist"
|
"output": "dist"
|
||||||
},
|
},
|
||||||
"publish": {
|
|
||||||
"provider": "generic",
|
|
||||||
"url": "http://192.168.1.89:8085/static/updates/"
|
|
||||||
},
|
|
||||||
"nsis": {
|
"nsis": {
|
||||||
"oneClick": false,
|
"oneClick": false,
|
||||||
"perMachine": false,
|
"perMachine": false,
|
||||||
@@ -28,10 +25,8 @@
|
|||||||
"target": "nsis",
|
"target": "nsis",
|
||||||
"icon": "public/icon/icon.png"
|
"icon": "public/icon/icon.png"
|
||||||
},
|
},
|
||||||
"linux": {
|
|
||||||
"target": ["snap"]
|
|
||||||
},
|
|
||||||
"files": [
|
"files": [
|
||||||
|
"package.json",
|
||||||
{
|
{
|
||||||
"from": "build/main",
|
"from": "build/main",
|
||||||
"to": "main",
|
"to": "main",
|
||||||
@@ -43,18 +38,10 @@
|
|||||||
"filter": ["**/*"]
|
"filter": ["**/*"]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
||||||
"from": "src/main/static",
|
"from": "src/main/static",
|
||||||
"to": "static",
|
"to": "static",
|
||||||
"filter": ["**/*"]
|
"filter": ["**/*"]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"from": "public",
|
|
||||||
"to": "assets",
|
|
||||||
"filter": [
|
|
||||||
"erp_client_sb-*.jar"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"from": "public",
|
"from": "public",
|
||||||
"to": "public",
|
"to": "public",
|
||||||
@@ -63,58 +50,42 @@
|
|||||||
"icon/**/*",
|
"icon/**/*",
|
||||||
"image/**/*",
|
"image/**/*",
|
||||||
"splash.html",
|
"splash.html",
|
||||||
|
"config/**/*",
|
||||||
"!erp_client_sb-*.jar",
|
"!erp_client_sb-*.jar",
|
||||||
"!data/**/*",
|
"!data/**/*",
|
||||||
"!jre/bin/jabswitch.exe",
|
"!jre/bin/jab*.exe",
|
||||||
"!jre/bin/jaccessinspector.exe",
|
"!jre/bin/jac*.exe",
|
||||||
"!jre/bin/jaccesswalker.exe",
|
"!jre/bin/jar*.exe",
|
||||||
"!jre/bin/jar.exe",
|
"!jre/bin/jc*.exe",
|
||||||
"!jre/bin/jarsigner.exe",
|
"!jre/bin/jd*.exe",
|
||||||
"!jre/bin/javac.exe",
|
"!jre/bin/jf*.exe",
|
||||||
"!jre/bin/javadoc.exe",
|
"!jre/bin/jh*.exe",
|
||||||
"!jre/bin/javap.exe",
|
"!jre/bin/ji*.exe",
|
||||||
"!jre/bin/jcmd.exe",
|
"!jre/bin/jl*.exe",
|
||||||
"!jre/bin/jconsole.exe",
|
"!jre/bin/jm*.exe",
|
||||||
"!jre/bin/jdb.exe",
|
"!jre/bin/jp*.exe",
|
||||||
"!jre/bin/jdeprscan.exe",
|
"!jre/bin/jr*.exe",
|
||||||
"!jre/bin/jdeps.exe",
|
"!jre/bin/jsh*.exe",
|
||||||
"!jre/bin/jfr.exe",
|
"!jre/bin/jst*.exe",
|
||||||
"!jre/bin/jhsdb.exe",
|
"!jre/bin/k*.exe",
|
||||||
"!jre/bin/jimage.exe",
|
"!jre/bin/rmi*.exe",
|
||||||
"!jre/bin/jinfo.exe",
|
"!jre/bin/serial*.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/include/**",
|
"!jre/include/**",
|
||||||
"!jre/lib/src.zip",
|
"!jre/lib/src.zip",
|
||||||
"!jre/lib/ct.sym",
|
"!jre/lib/ct.sym",
|
||||||
"!jre/lib/jvm.lib",
|
"!jre/lib/jvm.lib"
|
||||||
"!icon/image.png",
|
|
||||||
"!icon/img.png"
|
|
||||||
]
|
]
|
||||||
},
|
}
|
||||||
"!build",
|
|
||||||
"!dist",
|
|
||||||
"!scripts"
|
|
||||||
],
|
],
|
||||||
"electronLanguages": ["en", "zh-CN"],
|
|
||||||
"extraResources": [
|
"extraResources": [
|
||||||
{
|
{
|
||||||
"from": "update-helper.bat",
|
"from": "update-helper.bat",
|
||||||
"to": "../update-helper.bat"
|
"to": "../update-helper.bat"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "public",
|
||||||
|
"to": "./",
|
||||||
|
"filter": ["erp_client_sb-*.jar"]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
"main": "main/main.js",
|
"main": "main/main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "node scripts/dev-server.js",
|
"dev": "node scripts/dev-server.js",
|
||||||
|
"build": "node scripts/build.js && electron-builder",
|
||||||
"build:win": "node scripts/build.js && electron-builder --win",
|
"build:win": "node scripts/build.js && electron-builder --win",
|
||||||
"build:mac": "node scripts/build.js && electron-builder --mac",
|
"build:mac": "node scripts/build.js && electron-builder --mac",
|
||||||
"build:linux": "node scripts/build.js && electron-builder --linux"
|
"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 {app, BrowserWindow, ipcMain, Menu, screen, dialog} from 'electron';
|
||||||
import {existsSync, createWriteStream, promises as fs, mkdirSync, copyFileSync} from 'fs';
|
import {existsSync, createWriteStream, promises as fs, mkdirSync, copyFileSync, readdirSync, writeFileSync} from 'fs';
|
||||||
import {join, dirname} from 'path';
|
import {join, dirname, basename} from 'path';
|
||||||
import {spawn, ChildProcess} from 'child_process';
|
import {spawn, ChildProcess} from 'child_process';
|
||||||
import * as https from 'https';
|
import * as https from 'https';
|
||||||
import * as http from 'http';
|
import * as http from 'http';
|
||||||
|
|
||||||
|
const isDev = process.env.NODE_ENV === 'development';
|
||||||
|
|
||||||
let springProcess: ChildProcess | null = null;
|
let springProcess: ChildProcess | null = null;
|
||||||
let mainWindow: BrowserWindow | null = null;
|
let mainWindow: BrowserWindow | null = null;
|
||||||
let splashWindow: BrowserWindow | null = null;
|
let splashWindow: BrowserWindow | null = null;
|
||||||
let appOpened = false;
|
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 isDownloading = false;
|
||||||
let downloadedFilePath: string | null = null;
|
let downloadedFilePath: string | null = null;
|
||||||
|
let downloadedAsarPath: string | null = null;
|
||||||
|
let downloadedJarPath: string | null = null;
|
||||||
function openAppIfNotOpened() {
|
function openAppIfNotOpened() {
|
||||||
if (appOpened) return;
|
if (appOpened) return;
|
||||||
appOpened = true;
|
appOpened = true;
|
||||||
@@ -20,8 +25,8 @@ function openAppIfNotOpened() {
|
|||||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||||
mainWindow.show();
|
mainWindow.show();
|
||||||
mainWindow.focus();
|
mainWindow.focus();
|
||||||
|
if (isDev) mainWindow.webContents.openDevTools();
|
||||||
}
|
}
|
||||||
// 安全关闭启动画面
|
|
||||||
if (splashWindow && !splashWindow.isDestroyed()) {
|
if (splashWindow && !splashWindow.isDestroyed()) {
|
||||||
splashWindow.close();
|
splashWindow.close();
|
||||||
splashWindow = null;
|
splashWindow = null;
|
||||||
@@ -29,140 +34,74 @@ function openAppIfNotOpened() {
|
|||||||
}, 1000);
|
}, 1000);
|
||||||
});
|
});
|
||||||
|
|
||||||
if (process.env.NODE_ENV === 'development') {
|
isDev
|
||||||
const rendererPort = process.argv[2] || 8083;
|
? mainWindow.loadURL(`http://localhost:${process.argv[2] || 8083}`)
|
||||||
mainWindow.loadURL(`http://localhost:${rendererPort}`);
|
: mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
|
||||||
} else {
|
|
||||||
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 {
|
function getJavaExecutablePath(): string {
|
||||||
if (process.env.NODE_ENV === 'development') {
|
if (isDev) return 'java';
|
||||||
return 'java';
|
const javaPath = getResourcePath('', 'public/jre/bin/java.exe');
|
||||||
}
|
return existsSync(javaPath) ? javaPath : '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';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function findJarFile(directory: string): string {
|
function findJarFile(directory: string): string {
|
||||||
if (!existsSync(directory)) return '';
|
if (!existsSync(directory)) return '';
|
||||||
|
const jarFile = readdirSync(directory).find((f: string) => f.startsWith('erp_client_sb-') && f.endsWith('.jar'));
|
||||||
const files = require('fs').readdirSync(directory);
|
|
||||||
const jarFile = files.find((f: string) => f.startsWith('erp_client_sb-') && f.endsWith('.jar'));
|
|
||||||
|
|
||||||
return jarFile ? join(directory, jarFile) : '';
|
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 {
|
function getJarFilePath(): string {
|
||||||
if (process.env.NODE_ENV === 'development') {
|
if (isDev) return findJarFile(join(__dirname, '../../public'));
|
||||||
return findJarFile(join(__dirname, '../../public'));
|
return findJarFile(process.resourcesPath);
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getSplashPath(): string {
|
const getSplashPath = () => getResourcePath('../../public/splash.html', 'public/splash.html');
|
||||||
if (process.env.NODE_ENV === 'development') {
|
const getIconPath = () => getResourcePath('../../public/icon/icon.png', 'public/icon/icon.png', '../renderer/icon/icon.png');
|
||||||
return join(__dirname, '../../public/splash.html');
|
const getLogbackConfigPath = () => getResourcePath('../../public/config/logback.xml', 'public/config/logback.xml');
|
||||||
}
|
|
||||||
|
|
||||||
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');
|
|
||||||
}
|
|
||||||
|
|
||||||
function getDataDirectoryPath(): string {
|
function getDataDirectoryPath(): string {
|
||||||
// 将用户数据目录放在可写的应用数据目录下
|
const dataDir = join(app.getPath('userData'), 'data');
|
||||||
const userDataPath = app.getPath('userData');
|
if (!existsSync(dataDir)) mkdirSync(dataDir, {recursive: true});
|
||||||
const dataDir = join(userDataPath, 'data');
|
|
||||||
|
|
||||||
// 确保数据目录存在
|
|
||||||
if (!existsSync(dataDir)) {
|
|
||||||
mkdirSync(dataDir, { recursive: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
return dataDir;
|
return dataDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
function migrateDataFromPublic(): void {
|
function migrateDataFromPublic(): void {
|
||||||
// 如果是首次运行,尝试从public/data迁移数据
|
if (!isDev) return;
|
||||||
|
|
||||||
const oldDataPath = join(__dirname, '../../public/data');
|
const oldDataPath = join(__dirname, '../../public/data');
|
||||||
|
if (!existsSync(oldDataPath)) return;
|
||||||
|
|
||||||
const newDataPath = getDataDirectoryPath();
|
const newDataPath = getDataDirectoryPath();
|
||||||
|
|
||||||
if (process.env.NODE_ENV === 'development' && existsSync(oldDataPath)) {
|
|
||||||
try {
|
try {
|
||||||
const files = require('fs').readdirSync(oldDataPath);
|
readdirSync(oldDataPath).forEach(file => {
|
||||||
for (const file of files) {
|
|
||||||
const srcFile = join(oldDataPath, file);
|
|
||||||
const destFile = join(newDataPath, file);
|
const destFile = join(newDataPath, file);
|
||||||
|
|
||||||
if (!existsSync(destFile)) {
|
if (!existsSync(destFile)) {
|
||||||
require('fs').copyFileSync(srcFile, destFile);
|
copyFileSync(join(oldDataPath, file), destFile);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('数据迁移失败,使用默认配置');
|
console.log('数据迁移失败,使用默认配置');
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function startSpringBoot() {
|
function startSpringBoot() {
|
||||||
migrateDataFromPublic();
|
migrateDataFromPublic();
|
||||||
|
|
||||||
const jarPath = getJarFilePath();
|
const jarPath = getJarFilePath();
|
||||||
const javaPath = getJavaExecutablePath();
|
const javaPath = getJavaExecutablePath();
|
||||||
const dataDir = getDataDirectoryPath();
|
const dataDir = getDataDirectoryPath();
|
||||||
|
const logbackConfigPath = getLogbackConfigPath();
|
||||||
|
|
||||||
if (!existsSync(jarPath)) {
|
if (!existsSync(jarPath)) {
|
||||||
dialog.showErrorBox('启动失败', `JAR 文件不存在:\n${jarPath}`);
|
dialog.showErrorBox('启动失败', `JAR 文件不存在:\n${jarPath}`);
|
||||||
@@ -175,19 +114,14 @@ function startSpringBoot() {
|
|||||||
const springArgs = [
|
const springArgs = [
|
||||||
'-jar', jarPath,
|
'-jar', jarPath,
|
||||||
`--spring.datasource.url=jdbc:sqlite:${dataDir}/erp-cache.db`,
|
`--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会在数据目录下创建临时文件
|
// 工作目录设为数据目录,这样Spring Boot会在数据目录下创建临时文件
|
||||||
springProcess = spawn(javaPath, springArgs, {
|
springProcess = spawn(javaPath, springArgs, {
|
||||||
cwd: dataDir,
|
cwd: dataDir,
|
||||||
detached: false,
|
detached: false
|
||||||
env: {
|
|
||||||
...process.env,
|
|
||||||
'ERP_DATA_DIR': dataDir,
|
|
||||||
'USER_DATA_DIR': dataDir
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let startupCompleted = 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) => {
|
springProcess.on('close', (code) => {
|
||||||
mainWindow ? mainWindow.close() : app.quit();
|
mainWindow ? mainWindow.close() : app.quit();
|
||||||
});
|
});
|
||||||
@@ -226,7 +170,9 @@ function startSpringBoot() {
|
|||||||
app.quit();
|
app.quit();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
startSpringBoot();
|
|
||||||
|
startSpringBoot();
|
||||||
|
|
||||||
function stopSpringBoot() {
|
function stopSpringBoot() {
|
||||||
if (!springProcess) return;
|
if (!springProcess) return;
|
||||||
try {
|
try {
|
||||||
@@ -264,11 +210,6 @@ function createWindow() {
|
|||||||
Menu.setApplicationMenu(null);
|
Menu.setApplicationMenu(null);
|
||||||
mainWindow.setMenuBarVisibility(false);
|
mainWindow.setMenuBarVisibility(false);
|
||||||
|
|
||||||
// 打开开发者工具
|
|
||||||
if (process.env.NODE_ENV === 'development') {
|
|
||||||
mainWindow.webContents.openDevTools();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 监听窗口关闭事件,确保正确清理引用
|
// 监听窗口关闭事件,确保正确清理引用
|
||||||
mainWindow.on('closed', () => {
|
mainWindow.on('closed', () => {
|
||||||
mainWindow = null;
|
mainWindow = null;
|
||||||
@@ -334,14 +275,29 @@ ipcMain.on('message', (event, message) => {
|
|||||||
console.log(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() {
|
function checkPendingUpdate() {
|
||||||
try {
|
try {
|
||||||
const updateFilePath = join(process.resourcesPath, 'app.asar.update');
|
const asarUpdatePath = join(process.resourcesPath, 'app.asar.update');
|
||||||
const appAsarPath = join(process.resourcesPath, 'app.asar');
|
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 appDir = dirname(process.execPath);
|
||||||
const helperPath = join(appDir, 'update-helper.bat');
|
const helperPath = join(appDir, 'update-helper.bat');
|
||||||
@@ -353,9 +309,9 @@ function checkPendingUpdate() {
|
|||||||
|
|
||||||
const vbsPath = join(app.getPath('temp'), 'update-silent.vbs');
|
const vbsPath = join(app.getPath('temp'), 'update-silent.vbs');
|
||||||
const vbsContent = `Set WshShell = CreateObject("WScript.Shell")
|
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], {
|
spawn('wscript.exe', [vbsPath], {
|
||||||
detached: true,
|
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 (isDownloading) return {success: false, error: '正在下载中'};
|
||||||
if (downloadedFilePath === 'completed') return {success: true, filePath: 'already-completed'};
|
if (downloadedFilePath === 'completed') return {success: true, filePath: 'already-completed'};
|
||||||
|
|
||||||
isDownloading = true;
|
isDownloading = true;
|
||||||
|
let totalDownloaded = 0;
|
||||||
|
let totalSize = 0;
|
||||||
|
|
||||||
try {
|
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) => {
|
// 下载asar文件
|
||||||
downloadProgress = progress;
|
if (downloadUrls.asarUrl) {
|
||||||
if (mainWindow) {
|
const tempAsarPath = join(app.getPath('temp'), 'app.asar.new');
|
||||||
mainWindow.webContents.send('download-progress', progress);
|
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);
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!existsSync(tempPath)) {
|
const asarUpdatePath = join(process.resourcesPath, 'app.asar.update');
|
||||||
throw new Error('下载文件不存在');
|
await fs.copyFile(tempAsarPath, asarUpdatePath);
|
||||||
|
await fs.unlink(tempAsarPath);
|
||||||
|
downloadedAsarPath = asarUpdatePath;
|
||||||
|
totalDownloaded += asarSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
const fileStats = await fs.stat(tempPath);
|
// 下载jar文件
|
||||||
if (fileStats.size < 1000) {
|
if (downloadUrls.jarUrl) {
|
||||||
throw new Error('下载文件过小');
|
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 updateFilePath = join(process.resourcesPath, 'app.asar.update');
|
const tempJarPath = join(app.getPath('temp'), jarFileName);
|
||||||
await fs.copyFile(tempPath, updateFilePath);
|
|
||||||
await fs.unlink(tempPath);
|
|
||||||
|
|
||||||
if (!existsSync(updateFilePath)) {
|
await downloadFile(downloadUrls.jarUrl, tempJarPath, (progress) => {
|
||||||
throw new Error('更新文件保存失败');
|
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 jarUpdatePath = join(process.resourcesPath, jarFileName + '.update');
|
||||||
|
await fs.copyFile(tempJarPath, jarUpdatePath);
|
||||||
|
await fs.unlink(tempJarPath);
|
||||||
|
downloadedJarPath = jarUpdatePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
downloadedFilePath = 'completed';
|
downloadedFilePath = 'completed';
|
||||||
isDownloading = false;
|
isDownloading = false;
|
||||||
|
|
||||||
return {success: true, filePath: updateFilePath};
|
return {success: true, asarPath: downloadedAsarPath, jarPath: downloadedJarPath};
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
isDownloading = false;
|
isDownloading = false;
|
||||||
downloadedFilePath = null;
|
downloadedFilePath = null;
|
||||||
|
downloadedAsarPath = null;
|
||||||
const tempPath = join(app.getPath('temp'), 'app.asar.new');
|
downloadedJarPath = null;
|
||||||
if (existsSync(tempPath)) {
|
|
||||||
fs.unlink(tempPath).catch(() => {
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {success: false, error: error instanceof Error ? error.message : '下载失败'};
|
return {success: false, error: error instanceof Error ? error.message : '下载失败'};
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -426,26 +415,37 @@ ipcMain.handle('get-download-progress', () => {
|
|||||||
|
|
||||||
ipcMain.handle('install-update', async () => {
|
ipcMain.handle('install-update', async () => {
|
||||||
try {
|
try {
|
||||||
const updateFilePath = join(process.resourcesPath, 'app.asar.update');
|
const asarUpdatePath = join(process.resourcesPath, 'app.asar.update');
|
||||||
const hasUpdateFile = existsSync(updateFilePath);
|
const hasAsarUpdate = existsSync(asarUpdatePath);
|
||||||
|
|
||||||
if (!downloadedFilePath || (downloadedFilePath !== 'completed' && !hasUpdateFile)) {
|
// 查找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 (!hasAsarUpdate && !jarUpdatePath) {
|
||||||
return {success: false, error: '更新文件不存在'};
|
return {success: false, error: '更新文件不存在'};
|
||||||
}
|
}
|
||||||
|
|
||||||
const appDir = dirname(process.execPath);
|
const appDir = dirname(process.execPath);
|
||||||
const helperPath = join(appDir, 'update-helper.bat');
|
const helperPath = join(appDir, 'update-helper.bat');
|
||||||
const appAsarPath = join(process.resourcesPath, 'app.asar');
|
|
||||||
|
|
||||||
if (!existsSync(helperPath)) {
|
if (!existsSync(helperPath)) {
|
||||||
return {success: false, error: '更新助手不存在'};
|
return {success: false, error: '更新助手不存在'};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const appAsarPath = join(process.resourcesPath, 'app.asar');
|
||||||
|
|
||||||
const vbsPath = join(app.getPath('temp'), 'update-install.vbs');
|
const vbsPath = join(app.getPath('temp'), 'update-install.vbs');
|
||||||
const vbsContent = `Set WshShell = CreateObject("WScript.Shell")
|
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], {
|
spawn('wscript.exe', [vbsPath], {
|
||||||
detached: true,
|
detached: true,
|
||||||
@@ -455,6 +455,8 @@ WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " &
|
|||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
downloadedFilePath = null;
|
downloadedFilePath = null;
|
||||||
|
downloadedAsarPath = null;
|
||||||
|
downloadedJarPath = null;
|
||||||
app.quit();
|
app.quit();
|
||||||
}, 500);
|
}, 500);
|
||||||
|
|
||||||
@@ -466,8 +468,10 @@ WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " &
|
|||||||
|
|
||||||
ipcMain.handle('cancel-download', () => {
|
ipcMain.handle('cancel-download', () => {
|
||||||
isDownloading = false;
|
isDownloading = false;
|
||||||
downloadProgress = {percentage: 0, current: '0 MB', total: '0 MB', speed: ''};
|
downloadProgress = {percentage: 0, current: '0 MB', total: '0 MB'};
|
||||||
downloadedFilePath = null;
|
downloadedFilePath = null;
|
||||||
|
downloadedAsarPath = null;
|
||||||
|
downloadedJarPath = null;
|
||||||
return {success: true};
|
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) => {
|
return new Promise((resolve, reject) => {
|
||||||
const protocol = url.startsWith('https') ? https : http;
|
const protocol = url.startsWith('https') ? https : http;
|
||||||
|
|
||||||
@@ -502,22 +516,12 @@ async function downloadFile(url: string, filePath: string, onProgress: (progress
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const totalBytes = parseInt(response.headers['content-length'] || '0', 10);
|
|
||||||
let downloadedBytes = 0;
|
let downloadedBytes = 0;
|
||||||
const startTime = Date.now();
|
|
||||||
|
|
||||||
const fileStream = createWriteStream(filePath);
|
const fileStream = createWriteStream(filePath);
|
||||||
|
|
||||||
response.on('data', (chunk) => {
|
response.on('data', (chunk) => {
|
||||||
downloadedBytes += chunk.length;
|
downloadedBytes += chunk.length;
|
||||||
|
onProgress({downloaded: downloadedBytes});
|
||||||
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});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
response.pipe(fileStream);
|
response.pipe(fileStream);
|
||||||
@@ -528,8 +532,7 @@ async function downloadFile(url: string, filePath: string, onProgress: (progress
|
|||||||
});
|
});
|
||||||
|
|
||||||
fileStream.on('error', (error) => {
|
fileStream.on('error', (error) => {
|
||||||
fs.unlink(filePath).catch(() => {
|
fs.unlink(filePath).catch(() => {});
|
||||||
});
|
|
||||||
reject(error);
|
reject(error);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -304,7 +304,7 @@ const SSEManager = {
|
|||||||
console.log('SSE连接已就绪')
|
console.log('SSE连接已就绪')
|
||||||
break
|
break
|
||||||
case 'DEVICE_REMOVED':
|
case 'DEVICE_REMOVED':
|
||||||
logout()
|
clearLocalAuth()
|
||||||
ElMessage.warning('您的设备已被移除,请重新登录')
|
ElMessage.warning('您的设备已被移除,请重新登录')
|
||||||
break
|
break
|
||||||
case 'FORCE_LOGOUT':
|
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)
|
deviceQuota.value.used = Math.max(0, (deviceQuota.value.used || 0) - 1)
|
||||||
|
|
||||||
if (row.deviceId === getClientIdFromToken()) {
|
if (row.deviceId === getClientIdFromToken()) {
|
||||||
clearLocalAuth() // 移除当前设备:只清理本地状态,不调用offline(避免覆盖removed状态)
|
clearLocalAuth()
|
||||||
}
|
}
|
||||||
|
|
||||||
ElMessage.success('已移除设备')
|
ElMessage.success('已移除设备')
|
||||||
|
|||||||
@@ -21,11 +21,6 @@ export const deviceApi = {
|
|||||||
return http.post('/monitor/device/remove', payload)
|
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 }) {
|
offline(payload: { deviceId: string }) {
|
||||||
// 直接调用 RuoYi 后端的离线接口
|
// 直接调用 RuoYi 后端的离线接口
|
||||||
return http.post('/monitor/device/offline', payload)
|
return http.post('/monitor/device/offline', payload)
|
||||||
|
|||||||
@@ -4,7 +4,8 @@
|
|||||||
v{{ version || '-' }}
|
v{{ version || '-' }}
|
||||||
<span v-if="hasNewVersion" class="update-badge"></span>
|
<span v-if="hasNewVersion" class="update-badge"></span>
|
||||||
</div>
|
</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}` : '软件更新'">
|
:title="stage === 'downloading' ? `正在更新 ${appName}` : '软件更新'">
|
||||||
<div v-if="stage === 'check'" class="update-content">
|
<div v-if="stage === 'check'" class="update-content">
|
||||||
<div class="update-layout">
|
<div class="update-layout">
|
||||||
@@ -48,7 +49,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="download-content">
|
<div class="download-content">
|
||||||
<div class="download-info">
|
<div class="download-info">
|
||||||
<p>正在下载更新</p>
|
<p>正在下载安装...</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="download-progress">
|
<div class="download-progress">
|
||||||
<el-progress
|
<el-progress
|
||||||
@@ -65,26 +66,29 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-else-if="stage === 'completed'" class="update-content">
|
<div v-else-if="stage === 'completed'" class="update-content">
|
||||||
<div class="update-header text-center">
|
<div class="download-main">
|
||||||
|
<div class="download-icon">
|
||||||
<img src="/icon/icon.png" class="app-icon" alt="App Icon"/>
|
<img src="/icon/icon.png" class="app-icon" alt="App Icon"/>
|
||||||
<h3>更新完成</h3>
|
|
||||||
<p>更新文件已下载,将在重启后自动应用</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div class="download-content">
|
||||||
|
<div class="download-info">
|
||||||
|
<p>可以开始安装了</p>
|
||||||
|
</div>
|
||||||
<div class="download-progress">
|
<div class="download-progress">
|
||||||
<div class="progress-info">
|
|
||||||
<span>{{ prog.current }} / {{ prog.total }}</span>
|
|
||||||
</div>
|
|
||||||
<el-progress
|
<el-progress
|
||||||
:percentage="100"
|
:percentage="100"
|
||||||
:show-text="false"
|
:show-text="false"
|
||||||
:stroke-width="6"
|
:stroke-width="6"
|
||||||
color="#67C23A"/>
|
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>
|
</div>
|
||||||
|
|
||||||
<div class="update-buttons">
|
|
||||||
<el-button @click="cancelDownload">稍后更新</el-button>
|
|
||||||
<el-button type="primary" @click="installUpdate">重启应用新版本</el-button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
@@ -92,7 +96,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<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 {ElMessage, ElMessageBox} from 'element-plus'
|
||||||
import {updateApi} from '../../api/update'
|
import {updateApi} from '../../api/update'
|
||||||
|
|
||||||
@@ -109,11 +113,13 @@ const stage = ref<Stage>('check')
|
|||||||
const appName = ref('我了个电商')
|
const appName = ref('我了个电商')
|
||||||
const version = ref('')
|
const version = ref('')
|
||||||
const hasNewVersion = ref(false) // 控制小红点显示
|
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({
|
const info = ref({
|
||||||
latestVersion: '2.4.8',
|
latestVersion: '2.4.8',
|
||||||
downloadUrl: '',
|
downloadUrl: '',
|
||||||
updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性\n• 增加了新的功能模块\n• 优化了数据处理性能',
|
asarUrl: '',
|
||||||
|
jarUrl: '',
|
||||||
|
updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性',
|
||||||
currentVersion: '',
|
currentVersion: '',
|
||||||
hasUpdate: false
|
hasUpdate: false
|
||||||
})
|
})
|
||||||
@@ -140,7 +146,9 @@ async function autoCheck(silent = false) {
|
|||||||
currentVersion: result.currentVersion,
|
currentVersion: result.currentVersion,
|
||||||
latestVersion: result.latestVersion,
|
latestVersion: result.latestVersion,
|
||||||
downloadUrl: result.downloadUrl || '',
|
downloadUrl: result.downloadUrl || '',
|
||||||
updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性\n• 轻量级更新(仅替换app.asar)',
|
asarUrl: result.asarUrl || '',
|
||||||
|
jarUrl: result.jarUrl || '',
|
||||||
|
updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性\n• 同步更新前端和后端',
|
||||||
hasUpdate: true
|
hasUpdate: true
|
||||||
}
|
}
|
||||||
hasNewVersion.value = true
|
hasNewVersion.value = true
|
||||||
@@ -176,8 +184,10 @@ async function autoCheck(silent = false) {
|
|||||||
function handleVersionClick() {
|
function handleVersionClick() {
|
||||||
// 如果有新版本,直接显示更新对话框
|
// 如果有新版本,直接显示更新对话框
|
||||||
if (hasNewVersion.value) {
|
if (hasNewVersion.value) {
|
||||||
show.value = true
|
// 重置状态确保从检查阶段开始
|
||||||
stage.value = 'check'
|
stage.value = 'check'
|
||||||
|
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
|
||||||
|
show.value = true
|
||||||
} else {
|
} else {
|
||||||
// 没有新版本,执行检查更新
|
// 没有新版本,执行检查更新
|
||||||
autoCheck(false)
|
autoCheck(false)
|
||||||
@@ -196,29 +206,35 @@ function remindLater() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function start() {
|
async function start() {
|
||||||
if (!info.value.downloadUrl) {
|
if (!info.value.asarUrl && !info.value.jarUrl) {
|
||||||
ElMessage.error('下载链接不可用')
|
ElMessage.error('下载链接不可用')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
stage.value = 'downloading'
|
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) => {
|
;(window as any).electronAPI.onDownloadProgress((progress: any) => {
|
||||||
prog.value = {
|
prog.value = {
|
||||||
percentage: progress.percentage || 0,
|
percentage: progress.percentage || 0,
|
||||||
current: progress.current || '0 MB',
|
current: progress.current || '0 MB',
|
||||||
total: progress.total || '0 MB',
|
total: progress.total || '0 MB'
|
||||||
speed: progress.speed || ''
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
try {
|
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) {
|
if (response.success) {
|
||||||
stage.value = 'completed'
|
stage.value = 'completed'
|
||||||
prog.value.percentage = 100
|
prog.value.percentage = 100
|
||||||
|
// 如果没有有效的进度信息,设置默认值
|
||||||
|
if (prog.value.current === '0 MB' && prog.value.total === '0 MB') {
|
||||||
|
// 保持原有的"0 MB"值,让模板中的条件判断来处理显示
|
||||||
|
}
|
||||||
ElMessage.success('下载完成')
|
ElMessage.success('下载完成')
|
||||||
} else {
|
} else {
|
||||||
ElMessage.error('下载失败: ' + (response.error || '未知错误'))
|
ElMessage.error('下载失败: ' + (response.error || '未知错误'))
|
||||||
@@ -270,6 +286,15 @@ onMounted(async () => {
|
|||||||
await autoCheck(true)
|
await autoCheck(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 监听对话框关闭,重置状态
|
||||||
|
watch(show, (newValue) => {
|
||||||
|
if (!newValue) {
|
||||||
|
// 对话框关闭时重置状态
|
||||||
|
stage.value = 'check'
|
||||||
|
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
(window as any).electronAPI.removeDownloadProgressListener()
|
(window as any).electronAPI.removeDownloadProgressListener()
|
||||||
})
|
})
|
||||||
@@ -320,11 +345,39 @@ onUnmounted(() => {
|
|||||||
box-shadow: 0 24px 48px rgba(0, 0, 0, 0.15);
|
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;
|
display: block;
|
||||||
text-align: left;
|
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) {
|
:deep(.update-dialog .el-dialog__body) {
|
||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
@@ -538,6 +591,11 @@ onUnmounted(() => {
|
|||||||
color: #909399;
|
color: #909399;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.action-buttons {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
:deep(.el-progress-bar__outer) {
|
:deep(.el-progress-bar__outer) {
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
background-color: #e5e7eb;
|
background-color: #e5e7eb;
|
||||||
|
|||||||
@@ -3,86 +3,77 @@ setlocal enabledelayedexpansion
|
|||||||
|
|
||||||
set APP_ASAR=%~1
|
set APP_ASAR=%~1
|
||||||
set UPDATE_FILE=%~2
|
set UPDATE_FILE=%~2
|
||||||
set EXE_PATH=%~3
|
set JAR_UPDATE=%~3
|
||||||
set LOG_FILE=%TEMP%\electron-update.log
|
set EXE_PATH=%~4
|
||||||
|
|
||||||
echo ======================================== > "%LOG_FILE%"
|
if not exist "%UPDATE_FILE%" if "%JAR_UPDATE%"=="" exit /b 1
|
||||||
echo Electron App Auto-Update Helper >> "%LOG_FILE%"
|
if not exist "%UPDATE_FILE%" if not exist "%JAR_UPDATE%" exit /b 1
|
||||||
echo Started: %date% %time% >> "%LOG_FILE%"
|
|
||||||
echo ======================================== >> "%LOG_FILE%"
|
|
||||||
echo. >> "%LOG_FILE%"
|
|
||||||
|
|
||||||
if not exist "%UPDATE_FILE%" (
|
REM Wait for application to close
|
||||||
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 获取应用进程名
|
|
||||||
for /f "tokens=*" %%a in ("%EXE_PATH%") do set EXE_NAME=%%~nxa
|
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
|
set COUNT=0
|
||||||
:wait_loop
|
:wait_loop
|
||||||
tasklist /FI "IMAGENAME eq %EXE_NAME%" 2>nul | find /I "%EXE_NAME%" >nul
|
tasklist /FI "IMAGENAME eq %EXE_NAME%" 2>nul | find /I "%EXE_NAME%" >nul
|
||||||
if errorlevel 1 goto process_closed
|
if errorlevel 1 goto process_closed
|
||||||
set /a COUNT+=1
|
set /a COUNT+=1
|
||||||
if %COUNT% GEQ 20 (
|
if %COUNT% GEQ 20 goto process_closed
|
||||||
echo [WARN] Application still running after 10 seconds >> "%LOG_FILE%"
|
|
||||||
goto process_closed
|
|
||||||
)
|
|
||||||
timeout /t 1 /nobreak >nul
|
timeout /t 1 /nobreak >nul
|
||||||
goto wait_loop
|
goto wait_loop
|
||||||
|
|
||||||
:process_closed
|
:process_closed
|
||||||
echo [INFO] Application process closed >> "%LOG_FILE%"
|
|
||||||
timeout /t 1 /nobreak >nul
|
timeout /t 1 /nobreak >nul
|
||||||
|
|
||||||
echo [INFO] Backing up current app.asar... >> "%LOG_FILE%"
|
REM Update ASAR
|
||||||
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
|
|
||||||
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
|
|
||||||
)
|
|
||||||
)
|
|
||||||
echo [SUCCESS] Backup completed >> "%LOG_FILE%"
|
|
||||||
)
|
|
||||||
|
|
||||||
echo [INFO] Applying update... >> "%LOG_FILE%"
|
|
||||||
move /y "%UPDATE_FILE%" "%APP_ASAR%" >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
|
|
||||||
)
|
|
||||||
goto :start_app
|
|
||||||
)
|
|
||||||
|
|
||||||
echo [SUCCESS] Update applied successfully! >> "%LOG_FILE%"
|
|
||||||
|
|
||||||
if exist "%UPDATE_FILE%" (
|
if exist "%UPDATE_FILE%" (
|
||||||
del /f /q "%UPDATE_FILE%" >nul 2>&1
|
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
|
||||||
)
|
)
|
||||||
|
|
||||||
|
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 (
|
||||||
|
set /a RETRY_COUNT+=1
|
||||||
|
if !RETRY_COUNT! LEQ 5 (
|
||||||
|
timeout /t 2 /nobreak >nul
|
||||||
|
goto :retry_delete
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
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 (
|
||||||
|
set /a INSTALL_RETRY+=1
|
||||||
|
if %INSTALL_RETRY% LEQ 5 (
|
||||||
|
timeout /t 2 /nobreak >nul
|
||||||
|
goto :retry_install
|
||||||
|
)
|
||||||
|
goto :start_app
|
||||||
|
)
|
||||||
|
if exist "%JAR_UPDATE%" del /f /q "%JAR_UPDATE%" >nul 2>&1
|
||||||
|
|
||||||
:start_app
|
:start_app
|
||||||
echo [INFO] Restarting application... >> "%LOG_FILE%"
|
|
||||||
echo ======================================== >> "%LOG_FILE%"
|
|
||||||
|
|
||||||
start "" "%EXE_PATH%"
|
start "" "%EXE_PATH%"
|
||||||
exit /b 0
|
exit /b 0
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
package com.tashow.erp;
|
package com.tashow.erp;
|
||||||
|
|
||||||
import com.tashow.erp.utils.ErrorReporter;
|
import com.tashow.erp.utils.ErrorReporter;
|
||||||
import com.tashow.erp.utils.ResourcePreloader;
|
import com.tashow.erp.utils.ResourcePreloader;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -10,7 +9,6 @@ import org.springframework.context.ConfigurableApplicationContext;
|
|||||||
@Slf4j
|
@Slf4j
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class ErpClientSbApplication {
|
public class ErpClientSbApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
ConfigurableApplicationContext applicationContext = SpringApplication.run(ErpClientSbApplication.class, args);
|
ConfigurableApplicationContext applicationContext = SpringApplication.run(ErpClientSbApplication.class, args);
|
||||||
ErrorReporter errorReporter = applicationContext.getBean(ErrorReporter.class);
|
ErrorReporter errorReporter = applicationContext.getBean(ErrorReporter.class);
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
package com.tashow.erp.test;
|
package com.tashow.erp.test;
|
||||||
|
|
||||||
import com.tashow.erp.utils.DeviceUtils;
|
import com.tashow.erp.utils.DeviceUtils;
|
||||||
|
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
public class SeleniumWithProfile {
|
public class SeleniumWithProfile {
|
||||||
private static final Pattern WEIGHT_PATTERN = Pattern.compile("\"(?:unitWeight|weight)\":(\\d+(?:\\.\\d+)?)");
|
private static final Pattern WEIGHT_PATTERN = Pattern.compile("\"(?:unitWeight|weight)\":(\\d+(?:\\.\\d+)?)");
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.tashow.erp.utils;
|
package com.tashow.erp.utils;
|
||||||
|
|
||||||
import cn.hutool.crypto.SecureUtil;
|
import cn.hutool.crypto.SecureUtil;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
@@ -11,6 +12,7 @@ import java.util.Enumeration;
|
|||||||
* 设备工具类 - 基于 Windows Registry + PowerShell 实现稳定的设备ID获取
|
* 设备工具类 - 基于 Windows Registry + PowerShell 实现稳定的设备ID获取
|
||||||
* 兼容 Windows 10/11
|
* 兼容 Windows 10/11
|
||||||
*/
|
*/
|
||||||
|
@Slf4j
|
||||||
public class DeviceUtils {
|
public class DeviceUtils {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -19,8 +21,10 @@ public class DeviceUtils {
|
|||||||
*
|
*
|
||||||
* @return 固定的设备ID,格式: 类型前缀_MD5哈希值
|
* @return 固定的设备ID,格式: 类型前缀_MD5哈希值
|
||||||
*/
|
*/
|
||||||
|
|
||||||
public static String generateDeviceId() {
|
public static String generateDeviceId() {
|
||||||
String deviceId = null;
|
String deviceId = null;
|
||||||
|
log.info("========== 开始生成设备ID ==========");
|
||||||
|
|
||||||
// 策略1: Windows MachineGuid(注册表)
|
// 策略1: Windows MachineGuid(注册表)
|
||||||
deviceId = getMachineGuid();
|
deviceId = getMachineGuid();
|
||||||
@@ -72,7 +76,7 @@ public class DeviceUtils {
|
|||||||
}
|
}
|
||||||
process.waitFor();
|
process.waitFor();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.err.println("获取 MachineGuid 失败: " + e.getMessage());
|
log.error("获取 MachineGuid 异常: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -97,7 +101,7 @@ public class DeviceUtils {
|
|||||||
}
|
}
|
||||||
process.waitFor();
|
process.waitFor();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.err.println("获取硬件 UUID 失败: " + e.getMessage());
|
log.error("获取硬件 UUID 异常: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -121,7 +125,7 @@ public class DeviceUtils {
|
|||||||
}
|
}
|
||||||
process.waitFor();
|
process.waitFor();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.err.println("获取处理器 ID 失败: " + e.getMessage());
|
log.error("获取处理器 ID 异常: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -145,7 +149,7 @@ public class DeviceUtils {
|
|||||||
}
|
}
|
||||||
process.waitFor();
|
process.waitFor();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.err.println("获取主板序列号失败: " + e.getMessage());
|
log.error("获取主板序列号异常: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -171,7 +175,7 @@ public class DeviceUtils {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.err.println("获取 MAC 地址失败: " + e.getMessage());
|
log.error("获取 MAC 地址异常: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -191,9 +195,11 @@ public class DeviceUtils {
|
|||||||
String combined = sb.toString();
|
String combined = sb.toString();
|
||||||
return "SYS_" + SecureUtil.md5(combined).substring(0, 16).toUpperCase();
|
return "SYS_" + SecureUtil.md5(combined).substring(0, 16).toUpperCase();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.err.println("获取系统信息失败: " + e.getMessage());
|
log.error("获取系统信息异常: {}", e.getMessage());
|
||||||
// 最终的最终降级:时间戳哈希(不推荐,但保证不返回null)
|
// 最终的最终降级:时间戳哈希(不推荐,但保证不返回null)
|
||||||
return "FALLBACK_" + SecureUtil.md5(String.valueOf(System.currentTimeMillis())).substring(0, 16).toUpperCase();
|
String fallbackId = "FALLBACK_" + SecureUtil.md5(String.valueOf(System.currentTimeMillis())).substring(0, 16).toUpperCase();
|
||||||
|
log.warn("使用最终降级方案(时间戳哈希),设备ID: {}", fallbackId);
|
||||||
|
return fallbackId;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<configuration>
|
<configuration>
|
||||||
|
<!-- 固定日志路径到系统公共数据目录 -->
|
||||||
|
<property name="LOG_HOME" value="C:/ProgramData/erp-logs" />
|
||||||
|
|
||||||
|
<!-- 控制台输出 -->
|
||||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
<encoder>
|
<encoder>
|
||||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||||
@@ -7,13 +11,43 @@
|
|||||||
</encoder>
|
</encoder>
|
||||||
</appender>
|
</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">
|
<root level="INFO">
|
||||||
<appender-ref ref="CONSOLE" />
|
<appender-ref ref="CONSOLE" />
|
||||||
|
<appender-ref ref="FILE" />
|
||||||
</root>
|
</root>
|
||||||
|
|
||||||
<!-- 设置特定包的日志级别 -->
|
<!-- 设置特定包的日志级别 -->
|
||||||
<logger name="com.tashow.erp" level="INFO" additivity="false">
|
<logger name="com.tashow.erp" level="INFO" additivity="false">
|
||||||
<appender-ref ref="CONSOLE" />
|
<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>
|
</logger>
|
||||||
</configuration>
|
</configuration>
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.ruoyi.web.controller.monitor;
|
package com.ruoyi.web.controller.monitor;
|
||||||
|
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
|
||||||
@@ -142,33 +143,17 @@ public class ClientAccountController extends BaseController {
|
|||||||
|
|
||||||
// 检查设备数量限制
|
// 检查设备数量限制
|
||||||
String clientId = loginData.get("clientId");
|
String clientId = loginData.get("clientId");
|
||||||
if (!StringUtils.isEmpty(clientId)) {
|
|
||||||
ClientDevice currentDevice = clientDeviceMapper.selectByDeviceId(clientId);
|
|
||||||
if (currentDevice == null || "removed".equals(currentDevice.getStatus())) {
|
|
||||||
int deviceLimit = account.getDeviceLimit();
|
int deviceLimit = account.getDeviceLimit();
|
||||||
java.util.List<ClientDevice> userDevices = clientDeviceMapper.selectByUsername(username);
|
List<ClientDevice> userDevices = clientDeviceMapper.selectByUsername(username);
|
||||||
int activeDeviceCount = 0;
|
int userDevice = userDevices.size();
|
||||||
for (ClientDevice d : userDevices) {
|
boolean exists = userDevices.stream()
|
||||||
if (!"removed".equals(d.getStatus()) && !d.getDeviceId().equals(clientId)) {
|
.anyMatch(d -> clientId.equals(d.getDeviceId()));
|
||||||
activeDeviceCount++;
|
if(exists)userDevice--;
|
||||||
}
|
if (userDevice >= deviceLimit) {
|
||||||
}
|
|
||||||
if (activeDeviceCount >= deviceLimit) {
|
|
||||||
return AjaxResult.error("设备数量已达上限(" + deviceLimit + "个),请先移除其他设备");
|
return AjaxResult.error("设备数量已达上限(" + deviceLimit + "个),请先移除其他设备");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String accessToken = Jwts.builder()
|
String accessToken = Jwts.builder().setHeaderParam("kid", jwtRsaKeyService.getKeyId()).setSubject(username).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION)).claim("accountId", account.getId()).claim("username", username).claim("clientId", clientId).signWith(SignatureAlgorithm.RS256, jwtRsaKeyService.getPrivateKey()).compact();
|
||||||
.setHeaderParam("kid", jwtRsaKeyService.getKeyId())
|
|
||||||
.setSubject(username)
|
|
||||||
.setIssuedAt(new Date())
|
|
||||||
.setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION))
|
|
||||||
.claim("accountId", account.getId())
|
|
||||||
.claim("username", username)
|
|
||||||
.claim("clientId", clientId)
|
|
||||||
.signWith(SignatureAlgorithm.RS256, jwtRsaKeyService.getPrivateKey())
|
|
||||||
.compact();
|
|
||||||
Map<String, Object> result = new HashMap<>();
|
Map<String, Object> result = new HashMap<>();
|
||||||
result.put("accessToken", accessToken);
|
result.put("accessToken", accessToken);
|
||||||
result.put("permissions", account.getPermissions());
|
result.put("permissions", account.getPermissions());
|
||||||
@@ -178,8 +163,6 @@ public class ClientAccountController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 验证token
|
* 验证token
|
||||||
*/
|
*/
|
||||||
@@ -224,7 +207,10 @@ public class ClientAccountController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
SseEmitter emitter = sseHubService.register(username, clientId, 0L);
|
SseEmitter emitter = sseHubService.register(username, clientId, 0L);
|
||||||
try { emitter.send(SseEmitter.event().data("{\"type\":\"ready\"}")); } catch (Exception ignored) {}
|
try {
|
||||||
|
emitter.send(SseEmitter.event().data("{\"type\":\"ready\"}"));
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
return emitter;
|
return emitter;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -270,15 +256,7 @@ public class ClientAccountController extends BaseController {
|
|||||||
return AjaxResult.error("注册失败");
|
return AjaxResult.error("注册失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
String accessToken = Jwts.builder()
|
String accessToken = Jwts.builder().setHeaderParam("kid", jwtRsaKeyService.getKeyId()).setSubject(clientAccount.getUsername()).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION)).claim("accountId", clientAccount.getId()).claim("clientId", deviceId).signWith(SignatureAlgorithm.RS256, jwtRsaKeyService.getPrivateKey()).compact();
|
||||||
.setHeaderParam("kid", jwtRsaKeyService.getKeyId())
|
|
||||||
.setSubject(clientAccount.getUsername())
|
|
||||||
.setIssuedAt(new Date())
|
|
||||||
.setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION))
|
|
||||||
.claim("accountId", clientAccount.getId())
|
|
||||||
.claim("clientId", deviceId)
|
|
||||||
.signWith(SignatureAlgorithm.RS256, jwtRsaKeyService.getPrivateKey())
|
|
||||||
.compact();
|
|
||||||
|
|
||||||
Map<String, Object> dataMap = new HashMap<>();
|
Map<String, Object> dataMap = new HashMap<>();
|
||||||
dataMap.put("accessToken", accessToken);
|
dataMap.put("accessToken", accessToken);
|
||||||
@@ -330,8 +308,7 @@ public class ClientAccountController extends BaseController {
|
|||||||
|
|
||||||
// 通过SSE推送续费通知给该账号的所有在线设备
|
// 通过SSE推送续费通知给该账号的所有在线设备
|
||||||
try {
|
try {
|
||||||
sseHubService.sendEventToAllDevices(account.getUsername(), "VIP_RENEWED",
|
sseHubService.sendEventToAllDevices(account.getUsername(), "VIP_RENEWED", "{\"expireTime\":\"" + newExpireTime + "\"}");
|
||||||
"{\"expireTime\":\"" + newExpireTime + "\"}");
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
// SSE推送失败不影响续费操作
|
// SSE推送失败不影响续费操作
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,8 @@ public class VersionController extends BaseController {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private RedisTemplate<String, String> redisTemplate;
|
private RedisTemplate<String, String> redisTemplate;
|
||||||
private static final String VERSION_REDIS_KEY = "erp:client:version";
|
private static final String VERSION_REDIS_KEY = "erp:client:version";
|
||||||
private static final String DOWNLOAD_URL_REDIS_KEY = "erp:client:url";
|
private static final String ASAR_URL_REDIS_KEY = "erp:client:asar_url";
|
||||||
|
private static final String JAR_URL_REDIS_KEY = "erp:client:jar_url";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检查版本更新
|
* 检查版本更新
|
||||||
@@ -44,8 +45,12 @@ public class VersionController extends BaseController {
|
|||||||
result.put("latestVersion", latestVersion);
|
result.put("latestVersion", latestVersion);
|
||||||
result.put("needUpdate", needUpdate);
|
result.put("needUpdate", needUpdate);
|
||||||
// 从Redis获取下载链接
|
// 从Redis获取下载链接
|
||||||
String downloadUrl = redisTemplate.opsForValue().get(DOWNLOAD_URL_REDIS_KEY);
|
String asarUrl = redisTemplate.opsForValue().get(ASAR_URL_REDIS_KEY);
|
||||||
result.put("downloadUrl", downloadUrl);
|
String jarUrl = redisTemplate.opsForValue().get(JAR_URL_REDIS_KEY);
|
||||||
|
result.put("asarUrl", asarUrl);
|
||||||
|
result.put("jarUrl", jarUrl);
|
||||||
|
// 兼容旧版本,保留downloadUrl字段(指向asar)
|
||||||
|
result.put("downloadUrl", asarUrl);
|
||||||
|
|
||||||
return AjaxResult.success(result);
|
return AjaxResult.success(result);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -63,11 +68,13 @@ public class VersionController extends BaseController {
|
|||||||
if (StringUtils.isEmpty(currentVersion)) {
|
if (StringUtils.isEmpty(currentVersion)) {
|
||||||
currentVersion = "2.0.0";
|
currentVersion = "2.0.0";
|
||||||
}
|
}
|
||||||
String downloadUrl = redisTemplate.opsForValue().get(DOWNLOAD_URL_REDIS_KEY);
|
String asarUrl = redisTemplate.opsForValue().get(ASAR_URL_REDIS_KEY);
|
||||||
|
String jarUrl = redisTemplate.opsForValue().get(JAR_URL_REDIS_KEY);
|
||||||
|
|
||||||
Map<String, Object> result = new HashMap<>();
|
Map<String, Object> result = new HashMap<>();
|
||||||
result.put("currentVersion", currentVersion);
|
result.put("currentVersion", currentVersion);
|
||||||
result.put("downloadUrl", downloadUrl);
|
result.put("asarUrl", asarUrl);
|
||||||
|
result.put("jarUrl", jarUrl);
|
||||||
result.put("updateTime", System.currentTimeMillis());
|
result.put("updateTime", System.currentTimeMillis());
|
||||||
|
|
||||||
return AjaxResult.success(result);
|
return AjaxResult.success(result);
|
||||||
@@ -83,13 +90,20 @@ public class VersionController extends BaseController {
|
|||||||
@PreAuthorize("@ss.hasPermi('system:version:update')")
|
@PreAuthorize("@ss.hasPermi('system:version:update')")
|
||||||
@PostMapping("/update")
|
@PostMapping("/update")
|
||||||
public AjaxResult updateVersionInfo(@RequestParam("version") String version,
|
public AjaxResult updateVersionInfo(@RequestParam("version") String version,
|
||||||
@RequestParam("downloadUrl") String downloadUrl) {
|
@RequestParam(value = "asarUrl", required = false) String asarUrl,
|
||||||
|
@RequestParam(value = "jarUrl", required = false) String jarUrl) {
|
||||||
try {
|
try {
|
||||||
redisTemplate.opsForValue().set(VERSION_REDIS_KEY, version);
|
redisTemplate.opsForValue().set(VERSION_REDIS_KEY, version);
|
||||||
redisTemplate.opsForValue().set(DOWNLOAD_URL_REDIS_KEY, downloadUrl);
|
if (StringUtils.isNotEmpty(asarUrl)) {
|
||||||
|
redisTemplate.opsForValue().set(ASAR_URL_REDIS_KEY, asarUrl);
|
||||||
|
}
|
||||||
|
if (StringUtils.isNotEmpty(jarUrl)) {
|
||||||
|
redisTemplate.opsForValue().set(JAR_URL_REDIS_KEY, jarUrl);
|
||||||
|
}
|
||||||
Map<String, Object> result = new HashMap<>();
|
Map<String, Object> result = new HashMap<>();
|
||||||
result.put("version", version);
|
result.put("version", version);
|
||||||
result.put("downloadUrl", downloadUrl);
|
result.put("asarUrl", asarUrl);
|
||||||
|
result.put("jarUrl", jarUrl);
|
||||||
result.put("updateTime", System.currentTimeMillis());
|
result.put("updateTime", System.currentTimeMillis());
|
||||||
return AjaxResult.success("版本信息更新成功", result);
|
return AjaxResult.success("版本信息更新成功", result);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -107,7 +121,6 @@ public class VersionController extends BaseController {
|
|||||||
if (StringUtils.isEmpty(version1) || StringUtils.isEmpty(version2)) {
|
if (StringUtils.isEmpty(version1) || StringUtils.isEmpty(version2)) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
String[] v1Parts = version1.split("\\.");
|
String[] v1Parts = version1.split("\\.");
|
||||||
String[] v2Parts = version2.split("\\.");
|
String[] v2Parts = version2.split("\\.");
|
||||||
|
|
||||||
|
|||||||
@@ -53,15 +53,10 @@ public class ClientDeviceController {
|
|||||||
private void checkDeviceLimit(String username, String currentDeviceId) {
|
private void checkDeviceLimit(String username, String currentDeviceId) {
|
||||||
int deviceLimit = getDeviceLimit(username);
|
int deviceLimit = getDeviceLimit(username);
|
||||||
List<ClientDevice> userDevices = clientDeviceMapper.selectByUsername(username);
|
List<ClientDevice> userDevices = clientDeviceMapper.selectByUsername(username);
|
||||||
int activeDeviceCount = 0;
|
if (userDevices.size() >= deviceLimit) {
|
||||||
for (ClientDevice d : userDevices) {
|
|
||||||
if (!"removed".equals(d.getStatus()) && !d.getDeviceId().equals(currentDeviceId)) {
|
|
||||||
activeDeviceCount++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (activeDeviceCount >= deviceLimit) {
|
|
||||||
throw new RuntimeException("设备数量已达上限(" + deviceLimit + "个),请先移除其他设备");
|
throw new RuntimeException("设备数量已达上限(" + deviceLimit + "个),请先移除其他设备");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -157,14 +152,11 @@ public class ClientDeviceController {
|
|||||||
return AjaxResult.success();
|
return AjaxResult.success();
|
||||||
}
|
}
|
||||||
if (!"removed".equals(exists.getStatus())) {
|
if (!"removed".equals(exists.getStatus())) {
|
||||||
// 先推送下线事件,再断开连接
|
|
||||||
sseHubService.sendEvent(exists.getUsername(), deviceId, "DEVICE_REMOVED", "{}");
|
|
||||||
// 立即断开SSE连接,防止重新上线
|
|
||||||
sseHubService.disconnectDevice(exists.getUsername(), deviceId);
|
|
||||||
// 更新设备状态
|
|
||||||
exists.setStatus("removed");
|
exists.setStatus("removed");
|
||||||
exists.setLastActiveAt(new java.util.Date());
|
exists.setLastActiveAt(new java.util.Date());
|
||||||
clientDeviceMapper.updateByDeviceId(exists);
|
clientDeviceMapper.updateByDeviceId(exists);
|
||||||
|
sseHubService.sendEvent(exists.getUsername(), deviceId, "DEVICE_REMOVED", "{}");
|
||||||
|
sseHubService.disconnectDevice(exists.getUsername(), deviceId);
|
||||||
}
|
}
|
||||||
return AjaxResult.success();
|
return AjaxResult.success();
|
||||||
}
|
}
|
||||||
@@ -175,13 +167,11 @@ public class ClientDeviceController {
|
|||||||
@PostMapping("/offline")
|
@PostMapping("/offline")
|
||||||
public AjaxResult offline(@RequestBody Map<String, String> body) {
|
public AjaxResult offline(@RequestBody Map<String, String> body) {
|
||||||
String deviceId = body.get("deviceId");
|
String deviceId = body.get("deviceId");
|
||||||
if (deviceId == null) return AjaxResult.error("deviceId不能为空");
|
|
||||||
ClientDevice device = clientDeviceMapper.selectByDeviceId(deviceId);
|
ClientDevice device = clientDeviceMapper.selectByDeviceId(deviceId);
|
||||||
if (device != null) {
|
|
||||||
device.setStatus("offline");
|
device.setStatus("offline");
|
||||||
device.setLastActiveAt(new java.util.Date());
|
device.setLastActiveAt(new java.util.Date());
|
||||||
clientDeviceMapper.updateByDeviceId(device);
|
clientDeviceMapper.updateByDeviceId(device);
|
||||||
}
|
|
||||||
return AjaxResult.success();
|
return AjaxResult.success();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,12 +188,6 @@ public class ClientDeviceController {
|
|||||||
String os = device.getOs();
|
String os = device.getOs();
|
||||||
String deviceName = username + "@" + ip + " (" + os + ")";
|
String deviceName = username + "@" + ip + " (" + os + ")";
|
||||||
|
|
||||||
// 统一检查设备数量限制
|
|
||||||
try {
|
|
||||||
checkDeviceLimit(device.getUsername(), device.getDeviceId());
|
|
||||||
} catch (RuntimeException e) {
|
|
||||||
return AjaxResult.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (exists == null) {
|
if (exists == null) {
|
||||||
// 新设备注册
|
// 新设备注册
|
||||||
|
|||||||
@@ -42,7 +42,6 @@ public class FileController {
|
|||||||
|
|
||||||
@PostMapping("/uploads")
|
@PostMapping("/uploads")
|
||||||
public AjaxResult uploadFiles(@RequestParam("files") List<MultipartFile> files) {
|
public AjaxResult uploadFiles(@RequestParam("files") List<MultipartFile> files) {
|
||||||
|
|
||||||
List<FileDto> fileDtoS = new ArrayList<>();
|
List<FileDto> fileDtoS = new ArrayList<>();
|
||||||
for (MultipartFile file : files) {
|
for (MultipartFile file : files) {
|
||||||
String extName = FileUtil.extName(file.getOriginalFilename());
|
String extName = FileUtil.extName(file.getOriginalFilename());
|
||||||
|
|||||||
@@ -11,11 +11,6 @@ import com.ruoyi.system.domain.*;
|
|||||||
*/
|
*/
|
||||||
public interface IClientMonitorService {
|
public interface IClientMonitorService {
|
||||||
|
|
||||||
/**
|
|
||||||
* 查询客户端设备列表
|
|
||||||
*/
|
|
||||||
List<ClientDevice> selectClientDeviceList(String username);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 查询客户端错误报告列表
|
* 查询客户端错误报告列表
|
||||||
*/
|
*/
|
||||||
@@ -31,36 +26,11 @@ public interface IClientMonitorService {
|
|||||||
*/
|
*/
|
||||||
List<ClientDataReport> selectClientDataReportList(ClientDataReport clientDataReport);
|
List<ClientDataReport> selectClientDataReportList(ClientDataReport clientDataReport);
|
||||||
|
|
||||||
/**
|
|
||||||
* 查询在线客户端数量
|
|
||||||
*/
|
|
||||||
int selectOnlineClientCount();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 检查客户端是否在线
|
|
||||||
*/
|
|
||||||
boolean isClientOnline(String clientId);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取在线客户端ID列表
|
|
||||||
*/
|
|
||||||
List<String> getOnlineClientIds();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 查询客户端总数
|
|
||||||
*/
|
|
||||||
int selectTotalClientCount();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取客户端统计数据
|
* 获取客户端统计数据
|
||||||
*/
|
*/
|
||||||
Map<String, Object> getClientStatistics();
|
Map<String, Object> getClientStatistics();
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取客户端活跃趋势
|
|
||||||
*/
|
|
||||||
Map<String, Object> getClientActiveTrend();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取数据采集类型分布
|
* 获取数据采集类型分布
|
||||||
*/
|
*/
|
||||||
@@ -96,26 +66,6 @@ public interface IClientMonitorService {
|
|||||||
*/
|
*/
|
||||||
List<Map<String, Object>> getVersionDistribution();
|
List<Map<String, Object>> getVersionDistribution();
|
||||||
|
|
||||||
/**
|
|
||||||
* 插入客户端错误报告
|
|
||||||
*/
|
|
||||||
int insertClientError(ClientErrorReport clientErrorReport);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 插入客户端设备
|
|
||||||
*/
|
|
||||||
int insertClientDevice(ClientDevice clientDevice);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 插入客户端事件日志
|
|
||||||
*/
|
|
||||||
int insertClientEventLog(ClientEventLog clientEventLog);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 插入数据报告
|
|
||||||
*/
|
|
||||||
int insertDataReport(ClientDataReport clientDataReport);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 查询客户端信息列表
|
* 查询客户端信息列表
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,26 +1,14 @@
|
|||||||
package com.ruoyi.web.service.impl;
|
package com.ruoyi.web.service.impl;
|
||||||
import java.util.*;
|
|
||||||
import java.util.concurrent.*;
|
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
import com.ruoyi.system.domain.*;
|
import com.ruoyi.system.domain.*;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.scheduling.annotation.Async;
|
|
||||||
import javax.annotation.PreDestroy;
|
|
||||||
import com.ruoyi.common.utils.DateUtils;
|
import com.ruoyi.common.utils.DateUtils;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
import java.io.*;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.text.SimpleDateFormat;
|
|
||||||
import java.util.Date;
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.ruoyi.web.service.IClientAccountService;
|
|
||||||
import com.ruoyi.web.service.IClientMonitorService;
|
import com.ruoyi.web.service.IClientMonitorService;
|
||||||
import com.ruoyi.system.mapper.ClientMonitorMapper;
|
import com.ruoyi.system.mapper.ClientMonitorMapper;
|
||||||
import com.ruoyi.system.mapper.ClientDeviceMapper;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 客户端监控服务实现
|
* 客户端监控服务实现
|
||||||
@@ -35,42 +23,11 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private ClientMonitorMapper clientMonitorMapper;
|
private ClientMonitorMapper clientMonitorMapper;
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private ClientDeviceMapper clientDeviceMapper;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private IClientAccountService clientAccountService;
|
|
||||||
|
|
||||||
|
|
||||||
// 线程池用于异步处理日志记录
|
|
||||||
private final ExecutorService logExecutor = new ThreadPoolExecutor(
|
|
||||||
2, 4, 60L, TimeUnit.SECONDS,
|
|
||||||
new LinkedBlockingQueue<>(100),
|
|
||||||
new ThreadPoolExecutor.CallerRunsPolicy()
|
|
||||||
);
|
|
||||||
|
|
||||||
// API调用计数器,减少频繁日志记录
|
|
||||||
private final AtomicLong apiCallCounter = new AtomicLong(0);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 查询设备列表 - 基于ClientDevice表
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public List<ClientDevice> selectClientDeviceList(String username) {
|
|
||||||
logApiCallAsync("selectClientDeviceList", null);
|
|
||||||
if (username != null && !username.isEmpty()) {
|
|
||||||
return clientDeviceMapper.selectByUsername(username);
|
|
||||||
} else {
|
|
||||||
return clientMonitorMapper.selectOnlineDevices();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 查询客户端错误报告列表
|
* 查询客户端错误报告列表
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public List<Map<String, Object>> selectClientErrorList(ClientErrorReport clientErrorReport) {
|
public List<Map<String, Object>> selectClientErrorList(ClientErrorReport clientErrorReport) {
|
||||||
logApiCallAsync("selectClientErrorList", null);
|
|
||||||
return clientMonitorMapper.selectClientErrorList(clientErrorReport);
|
return clientMonitorMapper.selectClientErrorList(clientErrorReport);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,7 +36,6 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public List<ClientEventLog> selectClientEventLogList(ClientEventLog clientEventLog) {
|
public List<ClientEventLog> selectClientEventLogList(ClientEventLog clientEventLog) {
|
||||||
logApiCallAsync("selectClientEventLogList", null);
|
|
||||||
return clientMonitorMapper.selectClientEventLogList(clientEventLog);
|
return clientMonitorMapper.selectClientEventLogList(clientEventLog);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,136 +44,53 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public List<ClientDataReport> selectClientDataReportList(ClientDataReport clientDataReport) {
|
public List<ClientDataReport> selectClientDataReportList(ClientDataReport clientDataReport) {
|
||||||
logApiCallAsync("selectClientDataReportList", null);
|
|
||||||
return clientMonitorMapper.selectClientDataReportList(clientDataReport);
|
return clientMonitorMapper.selectClientDataReportList(clientDataReport);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 查询在线客户端数量 - 基于数据库
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public int selectOnlineClientCount() {
|
|
||||||
logApiCallAsync("selectOnlineClientCount", null);
|
|
||||||
return clientMonitorMapper.selectOnlineClientCount();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 检查客户端是否在线 - 基于数据库
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public boolean isClientOnline(String clientId) {
|
|
||||||
if (clientId == null || clientId.isEmpty()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
ClientInfo clientInfo = clientMonitorMapper.selectClientInfoByClientId(clientId);
|
|
||||||
return clientInfo != null && "1".equals(clientInfo.getOnline());
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println("检查客户端在线状态失败: " + e.getMessage());
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取在线客户端列表 - 基于数据库
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public List<String> getOnlineClientIds() {
|
|
||||||
try {
|
|
||||||
ClientInfo queryParam = new ClientInfo();
|
|
||||||
queryParam.setOnline("1");
|
|
||||||
List<ClientInfo> onlineClients = clientMonitorMapper.selectClientInfoList(queryParam);
|
|
||||||
List<String> onlineClientIds = new ArrayList<>();
|
|
||||||
for (ClientInfo client : onlineClients) {
|
|
||||||
onlineClientIds.add(client.getClientId());
|
|
||||||
}
|
|
||||||
return onlineClientIds;
|
|
||||||
} catch (Exception e) {
|
|
||||||
return new ArrayList<>();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 查询客户端总数
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public int selectTotalClientCount() {
|
|
||||||
logApiCallAsync("selectTotalClientCount", null);
|
|
||||||
return clientMonitorMapper.selectTotalClientCount();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取客户端统计数据
|
* 获取客户端统计数据
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Object> getClientStatistics() {
|
public Map<String, Object> getClientStatistics() {
|
||||||
Map<String, Object> statistics = new HashMap<>();
|
Map<String, Object> statistics = new HashMap<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 基础统计数据
|
|
||||||
int totalClients = clientMonitorMapper.selectTotalClientCount();
|
int totalClients = clientMonitorMapper.selectTotalClientCount();
|
||||||
int onlineClients = selectOnlineClientCount(); // 使用Redis优化的方法
|
int onlineClients = clientMonitorMapper.selectOnlineClientCount();
|
||||||
int errorCount = clientMonitorMapper.selectTodayErrorCount();
|
int errorCount = clientMonitorMapper.selectTodayErrorCount();
|
||||||
int todayDataCount = clientMonitorMapper.selectTodayDataCount();
|
int todayDataCount = clientMonitorMapper.selectTodayDataCount();
|
||||||
|
|
||||||
// 构建返回数据
|
|
||||||
statistics.put("totalClients", totalClients);
|
statistics.put("totalClients", totalClients);
|
||||||
statistics.put("onlineClients", onlineClients);
|
statistics.put("onlineClients", onlineClients);
|
||||||
statistics.put("errorCount", errorCount);
|
statistics.put("errorCount", errorCount);
|
||||||
statistics.put("todayDataCount", todayDataCount);
|
statistics.put("todayDataCount", todayDataCount);
|
||||||
// 计算错误率
|
|
||||||
double errorRate = (todayDataCount > 0) ? (errorCount * 100.0 / todayDataCount) : 0;
|
double errorRate = (todayDataCount > 0) ? (errorCount * 100.0 / todayDataCount) : 0;
|
||||||
statistics.put("errorRate", Math.round(errorRate * 10) / 10.0);
|
statistics.put("errorRate", Math.round(errorRate * 10) / 10.0);
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
// 查询失败时返回默认值
|
|
||||||
statistics.put("totalClients", 0);
|
statistics.put("totalClients", 0);
|
||||||
statistics.put("onlineClients", 0);
|
statistics.put("onlineClients", 0);
|
||||||
statistics.put("errorCount", 0);
|
statistics.put("errorCount", 0);
|
||||||
statistics.put("todayDataCount", 0);
|
statistics.put("todayDataCount", 0);
|
||||||
statistics.put("errorRate", 0.0);
|
statistics.put("errorRate", 0.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 异步记录API调用日志,减少阻塞
|
|
||||||
logApiCallAsync("getClientStatistics", null);
|
|
||||||
|
|
||||||
return statistics;
|
return statistics;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取客户端新增趋势 - 近7天每日新注册用户数量
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public Map<String, Object> getClientActiveTrend() {
|
|
||||||
// 使用新增用户趋势数据
|
|
||||||
return getOnlineClientTrend();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取数据采集类型分布
|
* 获取数据采集类型分布
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Object> getDataTypeDistribution() {
|
public Map<String, Object> getDataTypeDistribution() {
|
||||||
Map<String, Object> distribution = new HashMap<>();
|
Map<String, Object> distribution = new HashMap<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 异步查询数据类型分布,设置2秒超时
|
List<Map<String, Object>> dataTypeList = clientMonitorMapper.selectDataTypeDistribution();
|
||||||
CompletableFuture<List<Map<String, Object>>> distributionFuture = CompletableFuture
|
|
||||||
.supplyAsync(() -> clientMonitorMapper.selectDataTypeDistribution(), logExecutor);
|
|
||||||
|
|
||||||
List<Map<String, Object>> dataTypeList = distributionFuture.get(2, TimeUnit.SECONDS);
|
|
||||||
|
|
||||||
// 将查询结果转换为前端需要的格式
|
|
||||||
for (Map<String, Object> item : dataTypeList) {
|
for (Map<String, Object> item : dataTypeList) {
|
||||||
String dataType = (String) item.get("dataType");
|
String dataType = (String) item.get("dataType");
|
||||||
Object count = item.get("count");
|
Object count = item.get("count");
|
||||||
|
|
||||||
if (dataType != null) {
|
if (dataType != null) {
|
||||||
// 根据数据类型设置对应的键名
|
|
||||||
if ("ORDER".equalsIgnoreCase(dataType) || "BANMA".equalsIgnoreCase(dataType)) {
|
if ("ORDER".equalsIgnoreCase(dataType) || "BANMA".equalsIgnoreCase(dataType)) {
|
||||||
// 将ORDER和BANMA都作为orderCount
|
|
||||||
if (distribution.containsKey("orderCount")) {
|
if (distribution.containsKey("orderCount")) {
|
||||||
// 如果已经存在,则累加
|
|
||||||
int existingCount = Integer.parseInt(distribution.get("orderCount").toString());
|
int existingCount = Integer.parseInt(distribution.get("orderCount").toString());
|
||||||
int newCount = Integer.parseInt(count.toString());
|
int newCount = Integer.parseInt(count.toString());
|
||||||
distribution.put("orderCount", existingCount + newCount);
|
distribution.put("orderCount", existingCount + newCount);
|
||||||
@@ -229,7 +102,6 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
} else if ("AMAZON".equalsIgnoreCase(dataType)) {
|
} else if ("AMAZON".equalsIgnoreCase(dataType)) {
|
||||||
distribution.put("amazonCount", count);
|
distribution.put("amazonCount", count);
|
||||||
} else {
|
} else {
|
||||||
// 其他类型的数据,使用dataType + "Count"作为键名
|
|
||||||
distribution.put(dataType.toLowerCase() + "Count", count);
|
distribution.put(dataType.toLowerCase() + "Count", count);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -237,23 +109,15 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// 确保必要的键存在
|
distribution.putIfAbsent("orderCount", 0);
|
||||||
if (!distribution.containsKey("orderCount")) {
|
distribution.putIfAbsent("rakutenCount", 0);
|
||||||
distribution.put("orderCount", 0);
|
distribution.putIfAbsent("amazonCount", 0);
|
||||||
}
|
|
||||||
if (!distribution.containsKey("rakutenCount")) {
|
|
||||||
distribution.put("rakutenCount", 0);
|
|
||||||
}
|
|
||||||
if (!distribution.containsKey("amazonCount")) {
|
|
||||||
distribution.put("amazonCount", 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
logApiCallAsync("getDataTypeDistribution", null);
|
|
||||||
return distribution;
|
return distribution;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取近7天新增客户端趋势 - 基于认证时间统计每日新注册用户
|
* 获取近7天新增客户端趋势
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Object> getOnlineClientTrend() {
|
public Map<String, Object> getOnlineClientTrend() {
|
||||||
@@ -262,7 +126,6 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
List<Integer> counts = new ArrayList<>();
|
List<Integer> counts = new ArrayList<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 使用数据库查询获取近7天客户端活跃趋势
|
|
||||||
List<Map<String, Object>> activeTrendData = clientMonitorMapper.selectClientActiveTrend();
|
List<Map<String, Object>> activeTrendData = clientMonitorMapper.selectClientActiveTrend();
|
||||||
|
|
||||||
if (activeTrendData != null && !activeTrendData.isEmpty()) {
|
if (activeTrendData != null && !activeTrendData.isEmpty()) {
|
||||||
@@ -270,59 +133,42 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
String dateStr = (String) dayData.get("date");
|
String dateStr = (String) dayData.get("date");
|
||||||
Integer count = ((Number) dayData.get("count")).intValue();
|
Integer count = ((Number) dayData.get("count")).intValue();
|
||||||
|
|
||||||
// 转换日期格式从 yyyy-MM-dd 到 MM/dd
|
|
||||||
String[] dateParts = dateStr.split("-");
|
String[] dateParts = dateStr.split("-");
|
||||||
if (dateParts.length == 3) {
|
if (dateParts.length == 3) {
|
||||||
String formattedDate = String.format("%02d/%02d",
|
dates.add(String.format("%02d/%02d",
|
||||||
Integer.parseInt(dateParts[1]),
|
Integer.parseInt(dateParts[1]),
|
||||||
Integer.parseInt(dateParts[2]));
|
Integer.parseInt(dateParts[2])));
|
||||||
dates.add(formattedDate);
|
|
||||||
} else {
|
} else {
|
||||||
dates.add(dateStr);
|
dates.add(dateStr);
|
||||||
}
|
}
|
||||||
|
|
||||||
counts.add(count);
|
counts.add(count);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果没有数据,生成默认的7天数据
|
|
||||||
if (dates.isEmpty()) {
|
if (dates.isEmpty()) {
|
||||||
Calendar calendar = Calendar.getInstance();
|
generateDefaultTrendData(dates, counts);
|
||||||
for (int i = 6; i >= 0; i--) {
|
|
||||||
calendar.setTime(new Date());
|
|
||||||
calendar.add(Calendar.DAY_OF_MONTH, -i);
|
|
||||||
|
|
||||||
String dateStr = String.format("%02d/%02d",
|
|
||||||
calendar.get(Calendar.MONTH) + 1,
|
|
||||||
calendar.get(Calendar.DAY_OF_MONTH));
|
|
||||||
dates.add(dateStr);
|
|
||||||
counts.add(0);
|
|
||||||
}
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
generateDefaultTrendData(dates, counts);
|
||||||
}
|
}
|
||||||
|
|
||||||
trend.put("dates", dates);
|
trend.put("dates", dates);
|
||||||
trend.put("counts", counts);
|
trend.put("counts", counts);
|
||||||
} catch (Exception e) {
|
return trend;
|
||||||
// 异常时返回默认的7天数据
|
}
|
||||||
|
|
||||||
|
private void generateDefaultTrendData(List<String> dates, List<Integer> counts) {
|
||||||
dates.clear();
|
dates.clear();
|
||||||
counts.clear();
|
counts.clear();
|
||||||
Calendar calendar = Calendar.getInstance();
|
Calendar calendar = Calendar.getInstance();
|
||||||
for (int i = 6; i >= 0; i--) {
|
for (int i = 6; i >= 0; i--) {
|
||||||
calendar.setTime(new Date());
|
calendar.setTime(new Date());
|
||||||
calendar.add(Calendar.DAY_OF_MONTH, -i);
|
calendar.add(Calendar.DAY_OF_MONTH, -i);
|
||||||
|
dates.add(String.format("%02d/%02d",
|
||||||
String dateStr = String.format("%02d/%02d",
|
|
||||||
calendar.get(Calendar.MONTH) + 1,
|
calendar.get(Calendar.MONTH) + 1,
|
||||||
calendar.get(Calendar.DAY_OF_MONTH));
|
calendar.get(Calendar.DAY_OF_MONTH)));
|
||||||
dates.add(dateStr);
|
|
||||||
counts.add(0);
|
counts.add(0);
|
||||||
}
|
}
|
||||||
trend.put("dates", dates);
|
|
||||||
trend.put("counts", counts);
|
|
||||||
}
|
|
||||||
|
|
||||||
logApiCallAsync("getOnlineClientTrend", null);
|
|
||||||
return trend;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -332,26 +178,11 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
public Map<String, Object> authenticateClient(String authKey, Map<String, Object> clientInfo) {
|
public Map<String, Object> authenticateClient(String authKey, Map<String, Object> clientInfo) {
|
||||||
Map<String, Object> result = new HashMap<>();
|
Map<String, Object> result = new HashMap<>();
|
||||||
try {
|
try {
|
||||||
// TODO
|
String accessToken = UUID.randomUUID().toString().replace("-", "");
|
||||||
|
String clientId = (String) clientInfo.get("clientId");
|
||||||
// 生成访问令牌
|
|
||||||
String accessToken = generateAccessToken();
|
|
||||||
|
|
||||||
// 获取客户端传来的clientId
|
|
||||||
String clientIdFromClient = (String) clientInfo.get("clientId");
|
|
||||||
|
|
||||||
// 根据clientId查找现有客户端
|
|
||||||
ClientInfo existingClient = findClientByClientId(clientIdFromClient);
|
|
||||||
|
|
||||||
String clientId;
|
|
||||||
String username;
|
|
||||||
|
|
||||||
|
ClientInfo existingClient = findClientByClientId(clientId);
|
||||||
if (existingClient != null) {
|
if (existingClient != null) {
|
||||||
// 重用已有客户端ID和用户名
|
|
||||||
clientId = existingClient.getClientId();
|
|
||||||
username = existingClient.getUsername();
|
|
||||||
|
|
||||||
// 更新现有客户端信息
|
|
||||||
existingClient.setAccessToken(accessToken);
|
existingClient.setAccessToken(accessToken);
|
||||||
existingClient.setOsName((String) clientInfo.get("osName"));
|
existingClient.setOsName((String) clientInfo.get("osName"));
|
||||||
existingClient.setOsVersion((String) clientInfo.get("osVersion"));
|
existingClient.setOsVersion((String) clientInfo.get("osVersion"));
|
||||||
@@ -361,35 +192,20 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
existingClient.setLastActiveTime(DateUtils.getNowDate());
|
existingClient.setLastActiveTime(DateUtils.getNowDate());
|
||||||
existingClient.setOnline("1");
|
existingClient.setOnline("1");
|
||||||
clientMonitorMapper.updateClientOnlineStatus(clientId, "1");
|
clientMonitorMapper.updateClientOnlineStatus(clientId, "1");
|
||||||
} else {
|
|
||||||
clientId = clientIdFromClient;
|
|
||||||
username = (String) clientInfo.getOrDefault("username", "user");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// 获取权限配置 - 暂时设为空,后续根据账号体系实现
|
|
||||||
String permissions = null;
|
|
||||||
|
|
||||||
// 返回标准格式
|
|
||||||
result.put("success", true);
|
result.put("success", true);
|
||||||
result.put("accessToken", accessToken);
|
result.put("accessToken", accessToken);
|
||||||
result.put("tokenType", "Bearer");
|
result.put("tokenType", "Bearer");
|
||||||
result.put("expiresIn", 7200); // 2小时过期
|
result.put("expiresIn", 7200);
|
||||||
result.put("clientId", clientId);
|
result.put("clientId", clientId);
|
||||||
result.put("permissions", permissions); // 添加权限配置
|
result.put("permissions", null);
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
throw new RuntimeException("认证失败: " + e.getMessage());
|
||||||
throw new RuntimeException("认证过程中出现错误: " + e.getMessage());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 查找IP地址对应的客户端
|
|
||||||
*/
|
|
||||||
private ClientInfo findClientByClientId(String clientId) {
|
private ClientInfo findClientByClientId(String clientId) {
|
||||||
if (clientId == null || clientId.isEmpty()) {
|
if (clientId == null || clientId.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
@@ -398,147 +214,67 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
ClientInfo queryParams = new ClientInfo();
|
ClientInfo queryParams = new ClientInfo();
|
||||||
queryParams.setClientId(clientId);
|
queryParams.setClientId(clientId);
|
||||||
List<ClientInfo> clients = clientMonitorMapper.selectClientInfoList(queryParams);
|
List<ClientInfo> clients = clientMonitorMapper.selectClientInfoList(queryParams);
|
||||||
|
|
||||||
return clients != null && !clients.isEmpty() ? clients.get(0) : null;
|
return clients != null && !clients.isEmpty() ? clients.get(0) : null;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private ClientInfo findClientByIp(String ipAddress) {
|
|
||||||
if (ipAddress == null || ipAddress.isEmpty()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
ClientInfo queryParams = new ClientInfo();
|
|
||||||
queryParams.setIpAddress(ipAddress);
|
|
||||||
List<ClientInfo> clients = clientMonitorMapper.selectClientInfoList(queryParams);
|
|
||||||
|
|
||||||
return clients != null && !clients.isEmpty() ? clients.get(0) : null;
|
|
||||||
} catch (Exception e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 记录客户端认证信息 - 已在authenticateClient方法中内联实现
|
|
||||||
*/
|
|
||||||
private void recordClientAuth(String username, String authKey, String clientId, Map<String, Object> clientInfo, String accessToken) {
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 安全解析Double值
|
|
||||||
*/
|
|
||||||
private Double parseDouble(Object value, Double defaultValue) {
|
|
||||||
if (value == null) return defaultValue;
|
|
||||||
try {
|
|
||||||
return Double.valueOf(value.toString());
|
|
||||||
} catch (Exception e) {
|
|
||||||
return defaultValue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 记录客户端错误
|
* 记录客户端错误
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void recordErrorReport(Map<String, Object> errorData) {
|
public void recordErrorReport(Map<String, Object> errorData) {
|
||||||
ClientErrorReport errorReport = new ClientErrorReport();
|
ClientErrorReport errorReport = new ClientErrorReport();
|
||||||
|
|
||||||
// 基础错误信息
|
|
||||||
errorReport.setClientId((String) errorData.get("clientId"));
|
errorReport.setClientId((String) errorData.get("clientId"));
|
||||||
errorReport.setErrorType((String) errorData.get("errorType"));
|
errorReport.setErrorType((String) errorData.get("errorType"));
|
||||||
errorReport.setErrorMessage((String) errorData.get("errorMessage"));
|
errorReport.setErrorMessage((String) errorData.get("errorMessage"));
|
||||||
errorReport.setStackTrace((String) errorData.get("stackTrace"));
|
errorReport.setStackTrace((String) errorData.get("stackTrace"));
|
||||||
errorReport.setErrorTime(DateUtils.getNowDate());
|
errorReport.setErrorTime(DateUtils.getNowDate());
|
||||||
|
|
||||||
// 补充系统信息和用户名(从客户端传入的数据中获取)
|
|
||||||
errorReport.setUsername((String) errorData.get("username"));
|
errorReport.setUsername((String) errorData.get("username"));
|
||||||
errorReport.setOsName((String) errorData.get("osName"));
|
errorReport.setOsName((String) errorData.get("osName"));
|
||||||
errorReport.setOsVersion((String) errorData.get("osVersion"));
|
errorReport.setOsVersion((String) errorData.get("osVersion"));
|
||||||
errorReport.setAppVersion((String) errorData.get("appVersion"));
|
errorReport.setAppVersion((String) errorData.get("appVersion"));
|
||||||
|
|
||||||
clientMonitorMapper.insertClientError(errorReport);
|
clientMonitorMapper.insertClientError(errorReport);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 记录客户端数据采集报告 - 优化版:相同条件下累加数量
|
* 记录客户端数据采集报告
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void recordDataReport(Map<String, Object> dataReport) {
|
public void recordDataReport(Map<String, Object> dataReport) {
|
||||||
try {
|
try {
|
||||||
String clientId = (String) dataReport.get("clientId");
|
String clientId = (String) dataReport.get("clientId");
|
||||||
String dataType = normalizeDataType((String) dataReport.get("dataType"));
|
String dataType = normalizeDataType((String) dataReport.get("dataType"));
|
||||||
if (dataType == null) {
|
|
||||||
return; // 直接跳过不记录
|
|
||||||
}
|
|
||||||
String status = (String) dataReport.get("status");
|
String status = (String) dataReport.get("status");
|
||||||
int dataCount = parseInteger(dataReport.get("dataCount"), 1);
|
int dataCount = parseInteger(dataReport.get("dataCount"), 1);
|
||||||
|
|
||||||
// 查找当天相同clientId、dataType、status的记录
|
ClientDataReport existingReport = clientMonitorMapper.findRecentDataReport(clientId, dataType, status);
|
||||||
ClientDataReport existingReport = findRecentDataReport(clientId, dataType, status);
|
|
||||||
|
|
||||||
if (existingReport != null) {
|
if (existingReport != null) {
|
||||||
// 累加数量到现有记录
|
clientMonitorMapper.updateDataReportCount(existingReport.getId(), existingReport.getDataCount() + dataCount);
|
||||||
int newCount = existingReport.getDataCount() + dataCount;
|
|
||||||
updateDataReportCount(existingReport.getId(), newCount);
|
|
||||||
} else {
|
} else {
|
||||||
// 创建新记录
|
|
||||||
ClientDataReport report = new ClientDataReport();
|
ClientDataReport report = new ClientDataReport();
|
||||||
report.setClientId(clientId);
|
report.setClientId(clientId);
|
||||||
report.setDataType(dataType);
|
report.setDataType(dataType);
|
||||||
report.setDataCount(dataCount);
|
report.setDataCount(dataCount);
|
||||||
report.setCollectTime(DateUtils.getNowDate());
|
report.setCollectTime(DateUtils.getNowDate());
|
||||||
report.setStatus(status);
|
report.setStatus(status);
|
||||||
|
|
||||||
// 保存到数据库
|
|
||||||
clientMonitorMapper.insertDataReport(report);
|
clientMonitorMapper.insertDataReport(report);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 更新客户端在线状态
|
|
||||||
if (clientId != null && !clientId.isEmpty()) {
|
if (clientId != null && !clientId.isEmpty()) {
|
||||||
clientMonitorMapper.updateClientOnlineStatus(clientId, "1");
|
clientMonitorMapper.updateClientOnlineStatus(clientId, "1");
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.err.println("记录数据采集失败: " + e.getMessage());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 查找当天相同条件的数据报告
|
|
||||||
*/
|
|
||||||
private ClientDataReport findRecentDataReport(String clientId, String dataType, String status) {
|
|
||||||
try {
|
|
||||||
return clientMonitorMapper.findRecentDataReport(clientId, dataType, status);
|
|
||||||
} catch (Exception e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 更新数据报告的数量
|
|
||||||
*/
|
|
||||||
private void updateDataReportCount(Long id, int newCount) {
|
|
||||||
try {
|
|
||||||
clientMonitorMapper.updateDataReportCount(id, newCount);
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println("更新数据报告数量失败: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 标准化数据类型
|
|
||||||
*/
|
|
||||||
private String normalizeDataType(String dataType) {
|
private String normalizeDataType(String dataType) {
|
||||||
if (dataType == null) {
|
if (dataType == null) {
|
||||||
return "UNKNOWN";
|
return "UNKNOWN";
|
||||||
}
|
}
|
||||||
|
|
||||||
dataType = dataType.toUpperCase();
|
dataType = dataType.toUpperCase();
|
||||||
|
|
||||||
|
|
||||||
// 统一数据类型标识
|
|
||||||
if ("ORDER".equals(dataType)) {
|
if ("ORDER".equals(dataType)) {
|
||||||
return "BANMA";
|
return "BANMA";
|
||||||
} else if (dataType.contains("AMAZON")) {
|
} else if (dataType.contains("AMAZON")) {
|
||||||
@@ -546,13 +282,9 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
} else if (dataType.contains("RAKUTEN")) {
|
} else if (dataType.contains("RAKUTEN")) {
|
||||||
return "RAKUTEN";
|
return "RAKUTEN";
|
||||||
}
|
}
|
||||||
|
|
||||||
return dataType;
|
return dataType;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 安全解析Integer值
|
|
||||||
*/
|
|
||||||
private Integer parseInteger(Object value, Integer defaultValue) {
|
private Integer parseInteger(Object value, Integer defaultValue) {
|
||||||
if (value == null) return defaultValue;
|
if (value == null) return defaultValue;
|
||||||
try {
|
try {
|
||||||
@@ -567,74 +299,7 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Object> getClientDetail(String clientId) {
|
public Map<String, Object> getClientDetail(String clientId) {
|
||||||
// 从数据库查询客户端详细信息
|
return clientMonitorMapper.selectClientDetail(clientId);
|
||||||
Map<String, Object> detail = clientMonitorMapper.selectClientDetail(clientId);
|
|
||||||
// 记录API调用日志
|
|
||||||
logApiCall("getClientDetail", "客户端ID: " + clientId);
|
|
||||||
|
|
||||||
return detail;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 记录API调用日志
|
|
||||||
*/
|
|
||||||
private void logApiCall(String apiName, String remark) {
|
|
||||||
ClientDataReport report = new ClientDataReport();
|
|
||||||
report.setClientId("system");
|
|
||||||
report.setDataType("API_CALL");
|
|
||||||
report.setDataCount(1);
|
|
||||||
report.setCollectTime(DateUtils.getNowDate());
|
|
||||||
report.setStatus("0");
|
|
||||||
report.setRemark("调用" + apiName + "接口" + (remark != null ? ", " + remark : ""));
|
|
||||||
clientMonitorMapper.insertDataReport(report);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 异步记录API调用日志,减少阻塞
|
|
||||||
*/
|
|
||||||
@Async
|
|
||||||
private void logApiCallAsync(String apiName, String remark) {
|
|
||||||
|
|
||||||
if (apiCallCounter.incrementAndGet() % 10 == 0) {
|
|
||||||
logExecutor.submit(() -> {
|
|
||||||
try {
|
|
||||||
ClientDataReport report = new ClientDataReport();
|
|
||||||
report.setClientId("system");
|
|
||||||
report.setDataType("API_CALL");
|
|
||||||
report.setDataCount(10); // 表示10次调用的批量记录
|
|
||||||
report.setCollectTime(DateUtils.getNowDate());
|
|
||||||
report.setStatus("0");
|
|
||||||
report.setRemark("批量调用" + apiName + "接口" + (remark != null ? ", " + remark : ""));
|
|
||||||
clientMonitorMapper.insertDataReport(report);
|
|
||||||
} catch (Exception e) {
|
|
||||||
// 日志记录失败不影响主业务
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 优雅关闭线程池
|
|
||||||
*/
|
|
||||||
@PreDestroy
|
|
||||||
public void shutdown() {
|
|
||||||
if (logExecutor != null && !logExecutor.isShutdown()) {
|
|
||||||
logExecutor.shutdown();
|
|
||||||
try {
|
|
||||||
// 等待30秒让任务完成
|
|
||||||
if (!logExecutor.awaitTermination(30, TimeUnit.SECONDS)) {
|
|
||||||
logExecutor.shutdownNow();
|
|
||||||
// 再等待10秒
|
|
||||||
if (!logExecutor.awaitTermination(10, TimeUnit.SECONDS)) {
|
|
||||||
System.err.println("线程池未能在指定时间内关闭");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
logExecutor.shutdownNow();
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -642,62 +307,8 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public List<Map<String, Object>> getVersionDistribution() {
|
public List<Map<String, Object>> getVersionDistribution() {
|
||||||
// 从数据库查询真实的版本分布数据
|
|
||||||
List<Map<String, Object>> distribution = clientMonitorMapper.selectVersionDistribution();
|
List<Map<String, Object>> distribution = clientMonitorMapper.selectVersionDistribution();
|
||||||
|
return distribution != null ? distribution : new ArrayList<>();
|
||||||
// 如果没有数据,返回空列表
|
|
||||||
if (distribution == null) {
|
|
||||||
distribution = new ArrayList<>();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 记录API调用日志
|
|
||||||
logApiCall("getVersionDistribution", null);
|
|
||||||
|
|
||||||
return distribution;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 生成会话令牌
|
|
||||||
*/
|
|
||||||
private String generateAccessToken() {
|
|
||||||
return UUID.randomUUID().toString().replace("-", "");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 新增客户端错误报告
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public int insertClientError(ClientErrorReport clientErrorReport) {
|
|
||||||
return clientMonitorMapper.insertClientError(clientErrorReport);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 新增客户端信息
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public int insertClientDevice(ClientDevice clientDevice) {
|
|
||||||
return clientDeviceMapper.insert(clientDevice);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 新增客户端事件日志
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public int insertClientEventLog(ClientEventLog clientEventLog) {
|
|
||||||
return clientMonitorMapper.insertClientEventLog(clientEventLog);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 新增客户端数据采集报告
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public int insertDataReport(ClientDataReport clientDataReport) {
|
|
||||||
return clientMonitorMapper.insertDataReport(clientDataReport);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -714,16 +325,7 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
|||||||
@Override
|
@Override
|
||||||
public void cleanExpiredData() {
|
public void cleanExpiredData() {
|
||||||
try {
|
try {
|
||||||
// // 清理过期的客户端(设置为离线状态)
|
|
||||||
// clientMonitorMapper.updateExpiredClientsOffline();
|
|
||||||
|
|
||||||
// 清理过期的设备(设置为离线状态)
|
|
||||||
clientMonitorMapper.updateExpiredDevicesOffline();
|
|
||||||
|
|
||||||
// 删除过期的错误报告
|
|
||||||
clientMonitorMapper.deleteExpiredErrorReports();
|
clientMonitorMapper.deleteExpiredErrorReports();
|
||||||
|
|
||||||
// 删除过期的事件日志
|
|
||||||
clientMonitorMapper.deleteExpiredEventLogs();
|
clientMonitorMapper.deleteExpiredEventLogs();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("清理过期数据失败: {}", e.getMessage(), e);
|
logger.error("清理过期数据失败: {}", e.getMessage(), e);
|
||||||
|
|||||||
@@ -50,9 +50,7 @@ public class SseHubService {
|
|||||||
public void sendEvent(String username, String clientId, String type, String message) {
|
public void sendEvent(String username, String clientId, String type, String message) {
|
||||||
String key = buildSessionKey(username, clientId);
|
String key = buildSessionKey(username, clientId);
|
||||||
SseEmitter emitter = sessionEmitters.get(key);
|
SseEmitter emitter = sessionEmitters.get(key);
|
||||||
|
|
||||||
if (emitter == null) return;
|
if (emitter == null) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
String data = message != null ? message : "{}";
|
String data = message != null ? message : "{}";
|
||||||
String eventData = "{\"type\":\"" + type + "\",\"message\":" + escapeJson(data) + "}";
|
String eventData = "{\"type\":\"" + type + "\",\"message\":" + escapeJson(data) + "}";
|
||||||
@@ -66,12 +64,28 @@ public class SseHubService {
|
|||||||
public void sendPing(String username, String clientId) {
|
public void sendPing(String username, String clientId) {
|
||||||
String key = buildSessionKey(username, clientId);
|
String key = buildSessionKey(username, clientId);
|
||||||
SseEmitter emitter = sessionEmitters.get(key);
|
SseEmitter emitter = sessionEmitters.get(key);
|
||||||
if (emitter == null) return;
|
if (emitter == null) {
|
||||||
|
try {
|
||||||
|
ClientDevice device = clientDeviceMapper.selectByDeviceId(clientId);
|
||||||
|
// 只有当设备状态不是removed时,才更新为offline
|
||||||
|
if (device != null && !"removed".equals(device.getStatus())) {
|
||||||
|
device.setStatus("offline");
|
||||||
|
device.setLastActiveAt(new Date());
|
||||||
|
clientDeviceMapper.updateByDeviceId(device);
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// 静默处理,不影响心跳主流程
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
emitter.send(SseEmitter.event().name("ping").data(String.valueOf(System.currentTimeMillis())));
|
emitter.send(SseEmitter.event().name("ping").data(String.valueOf(System.currentTimeMillis())));
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
sessionEmitters.remove(key);
|
sessionEmitters.remove(key);
|
||||||
try { emitter.complete(); } catch (Exception ignored) {}
|
try { emitter.complete(); } catch (Exception ignored) {}
|
||||||
|
// 发送失败也更新为离线
|
||||||
|
updateDeviceStatus(clientId, "offline");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,6 +135,10 @@ public class SseHubService {
|
|||||||
try {
|
try {
|
||||||
ClientDevice device = clientDeviceMapper.selectByDeviceId(deviceId);
|
ClientDevice device = clientDeviceMapper.selectByDeviceId(deviceId);
|
||||||
if (device != null) {
|
if (device != null) {
|
||||||
|
if ("removed".equals(device.getStatus()) && "offline".equals(status)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if ("removed".equals(status)) {
|
if ("removed".equals(status)) {
|
||||||
disconnectDevice(device.getUsername(), deviceId);
|
disconnectDevice(device.getUsername(), deviceId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,12 +33,4 @@ public class DeviceHeartbeatTask {
|
|||||||
sseHubService.sendPing(device.getUsername(), device.getDeviceId());
|
sseHubService.sendPing(device.getUsername(), device.getDeviceId());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 每2分钟清理一次过期设备
|
|
||||||
*/
|
|
||||||
@Scheduled(fixedRate = 120000)
|
|
||||||
public void cleanExpiredDevices() {
|
|
||||||
clientDeviceMapper.updateExpiredDevicesOffline();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,7 @@ spring:
|
|||||||
druid:
|
druid:
|
||||||
# 主库数据源
|
# 主库数据源
|
||||||
master:
|
master:
|
||||||
url: jdbc:mysql://8.138.23.49:8896/erp?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
|
url: jdbc:mysql://8.138.23.49:8896/erp?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&failOverReadOnly=false&maxReconnects=3&initialTimeout=2&connectTimeout=5000&socketTimeout=5000
|
||||||
username: root
|
username: root
|
||||||
password: jaz7fMSiCrQK48nK
|
password: jaz7fMSiCrQK48nK
|
||||||
# url: jdbc:mysql://localhost:3306/erp?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
|
# url: jdbc:mysql://localhost:3306/erp?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
|
||||||
@@ -19,20 +19,20 @@ spring:
|
|||||||
url:
|
url:
|
||||||
username:
|
username:
|
||||||
password:
|
password:
|
||||||
# 初始连接数
|
# 初始连接数(增加预热连接)
|
||||||
initialSize: 5
|
initialSize: 8
|
||||||
# 最小连接池数量
|
# 最小连接池数量
|
||||||
minIdle: 10
|
minIdle: 10
|
||||||
# 最大连接池数量
|
# 最大连接池数量
|
||||||
maxActive: 20
|
maxActive: 25
|
||||||
# 配置获取连接等待超时的时间
|
# 配置获取连接等待超时的时间(5秒)
|
||||||
maxWait: 60000
|
maxWait: 5000
|
||||||
# 配置连接超时时间
|
# 配置连接超时时间(5秒)
|
||||||
connectTimeout: 30000
|
connectTimeout: 5000
|
||||||
# 配置网络超时时间
|
# 配置网络超时时间(5秒)
|
||||||
socketTimeout: 60000
|
socketTimeout: 5000
|
||||||
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
|
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒(30秒检测一次)
|
||||||
timeBetweenEvictionRunsMillis: 60000
|
timeBetweenEvictionRunsMillis: 30000
|
||||||
# 配置一个连接在池中最小生存的时间,单位是毫秒
|
# 配置一个连接在池中最小生存的时间,单位是毫秒
|
||||||
minEvictableIdleTimeMillis: 300000
|
minEvictableIdleTimeMillis: 300000
|
||||||
# 配置一个连接在池中最大生存的时间,单位是毫秒
|
# 配置一个连接在池中最大生存的时间,单位是毫秒
|
||||||
@@ -55,9 +55,9 @@ spring:
|
|||||||
filter:
|
filter:
|
||||||
stat:
|
stat:
|
||||||
enabled: true
|
enabled: true
|
||||||
# 慢SQL记录
|
# 慢SQL记录(500ms以上记录为慢SQL)
|
||||||
log-slow-sql: true
|
log-slow-sql: true
|
||||||
slow-sql-millis: 1000
|
slow-sql-millis: 500
|
||||||
merge-sql: true
|
merge-sql: true
|
||||||
wall:
|
wall:
|
||||||
config:
|
config:
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ spring:
|
|||||||
# password:
|
# password:
|
||||||
password: 123123
|
password: 123123
|
||||||
# 连接超时时间(降低超时,快速失败)
|
# 连接超时时间(降低超时,快速失败)
|
||||||
timeout: 3s
|
timeout: 5s
|
||||||
lettuce:
|
lettuce:
|
||||||
pool:
|
pool:
|
||||||
# 连接池中的最小空闲连接(保持预热连接,避免临时建连)
|
# 连接池中的最小空闲连接(保持预热连接,避免临时建连)
|
||||||
@@ -98,7 +98,7 @@ spring:
|
|||||||
# 连接池的最大数据库连接数(增加以应对并发)
|
# 连接池的最大数据库连接数(增加以应对并发)
|
||||||
max-active: 20
|
max-active: 20
|
||||||
# 连接池最大阻塞等待时间(设置合理超时,避免无限等待)
|
# 连接池最大阻塞等待时间(设置合理超时,避免无限等待)
|
||||||
max-wait: 3000ms
|
max-wait: 5000ms
|
||||||
# 关闭超时时间
|
# 关闭超时时间
|
||||||
shutdown-timeout: 100ms
|
shutdown-timeout: 100ms
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,9 @@ PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
|
|||||||
<!-- 允许JDBC 支持自动生成主键 -->
|
<!-- 允许JDBC 支持自动生成主键 -->
|
||||||
<setting name="useGeneratedKeys" value="true" />
|
<setting name="useGeneratedKeys" value="true" />
|
||||||
<!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 -->
|
<!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 -->
|
||||||
<setting name="defaultExecutorType" value="SIMPLE" />
|
<setting name="defaultExecutorType" value="REUSE" />
|
||||||
|
<!-- 设置超时时间,防止慢查询(5秒) -->
|
||||||
|
<setting name="defaultStatementTimeout" value="5" />
|
||||||
<!-- 指定 MyBatis 所用日志的具体实现 -->
|
<!-- 指定 MyBatis 所用日志的具体实现 -->
|
||||||
<setting name="logImpl" value="SLF4J" />
|
<setting name="logImpl" value="SLF4J" />
|
||||||
<!-- 使用驼峰命名法转换字段 -->
|
<!-- 使用驼峰命名法转换字段 -->
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
package com.ruoyi.system.mapper;
|
package com.ruoyi.system.mapper;
|
||||||
|
|
||||||
import com.ruoyi.system.domain.ClientDevice;
|
import com.ruoyi.system.domain.ClientDevice;
|
||||||
|
import io.lettuce.core.dynamic.annotation.Param;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public interface ClientDeviceMapper {
|
public interface ClientDeviceMapper {
|
||||||
ClientDevice selectByDeviceId(String deviceId);
|
ClientDevice selectByDeviceId(String deviceId);
|
||||||
List<ClientDevice> selectByUsername(String username);
|
List<ClientDevice> selectByUsername(@Param("username") String username);
|
||||||
List<ClientDevice> selectOnlineDevices();
|
List<ClientDevice> selectOnlineDevices();
|
||||||
int insert(ClientDevice device);
|
int insert(ClientDevice device);
|
||||||
int updateByDeviceId(ClientDevice device);
|
int updateByDeviceId(ClientDevice device);
|
||||||
int updateExpiredDevicesOffline();
|
|
||||||
int deleteByDeviceId(String deviceId);
|
int deleteByDeviceId(String deviceId);
|
||||||
int countByUsername(String username);
|
int countByUsername(String username);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -247,11 +247,4 @@ public interface ClientMonitorMapper {
|
|||||||
* @return 在线设备列表
|
* @return 在线设备列表
|
||||||
*/
|
*/
|
||||||
public List<ClientDevice> selectOnlineDevices();
|
public List<ClientDevice> selectOnlineDevices();
|
||||||
|
|
||||||
/**
|
|
||||||
* 将过期设备设置为离线状态
|
|
||||||
*
|
|
||||||
* @return 影响行数
|
|
||||||
*/
|
|
||||||
public int updateExpiredDevicesOffline();
|
|
||||||
}
|
}
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
</select>
|
</select>
|
||||||
|
|
||||||
<select id="selectByUsername" resultMap="ClientDeviceMap">
|
<select id="selectByUsername" resultMap="ClientDeviceMap">
|
||||||
select * from client_device where username = #{username} order by update_time desc
|
select * from client_device where username = #{username} and status != 'removed' order by update_time desc
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
<insert id="insert" parameterType="com.ruoyi.system.domain.ClientDevice" useGeneratedKeys="true" keyProperty="id">
|
<insert id="insert" parameterType="com.ruoyi.system.domain.ClientDevice" useGeneratedKeys="true" keyProperty="id">
|
||||||
@@ -52,11 +52,6 @@
|
|||||||
<select id="selectOnlineDevices" resultMap="ClientDeviceMap">
|
<select id="selectOnlineDevices" resultMap="ClientDeviceMap">
|
||||||
select * from client_device where status = 'online' order by last_active_at desc
|
select * from client_device where status = 'online' order by last_active_at desc
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
<update id="updateExpiredDevicesOffline">
|
|
||||||
update client_device set status = 'offline'
|
|
||||||
where status = 'online' and (last_active_at is null or last_active_at < date_sub(now(), interval 2 minute))
|
|
||||||
</update>
|
|
||||||
</mapper>
|
</mapper>
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -456,14 +456,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||||||
ORDER BY last_active_at DESC
|
ORDER BY last_active_at DESC
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
<!-- 将过期设备设置为离线状态(5分钟未活跃) -->
|
|
||||||
<update id="updateExpiredDevicesOffline">
|
|
||||||
UPDATE client_device
|
|
||||||
SET status = 'offline'
|
|
||||||
WHERE status = 'online'
|
|
||||||
AND (last_active_at IS NULL OR last_active_at < DATE_SUB(NOW(), INTERVAL 5 MINUTE))
|
|
||||||
</update>
|
|
||||||
|
|
||||||
<!-- 删除30天前的错误报告 -->
|
<!-- 删除30天前的错误报告 -->
|
||||||
<delete id="deleteExpiredErrorReports">
|
<delete id="deleteExpiredErrorReports">
|
||||||
DELETE FROM client_error_report
|
DELETE FROM client_error_report
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ export function uploadFile(data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 更新版本信息和下载链接
|
// 更新版本信息和下载链接
|
||||||
|
// data: { version, asarUrl, jarUrl }
|
||||||
export function updateVersion(data) {
|
export function updateVersion(data) {
|
||||||
return request({
|
return request({
|
||||||
url: '/system/version/update',
|
url: '/system/version/update',
|
||||||
|
|||||||
@@ -21,9 +21,14 @@
|
|||||||
<el-descriptions-item label="更新时间">
|
<el-descriptions-item label="更新时间">
|
||||||
{{ parseTime(versionInfo.updateTime) }}
|
{{ parseTime(versionInfo.updateTime) }}
|
||||||
</el-descriptions-item>
|
</el-descriptions-item>
|
||||||
<el-descriptions-item label="下载链接" v-if="versionInfo.downloadUrl">
|
<el-descriptions-item label="ASAR下载链接" v-if="versionInfo.asarUrl">
|
||||||
<el-link :href="versionInfo.downloadUrl" target="_blank" type="primary">
|
<el-link :href="versionInfo.asarUrl" target="_blank" type="primary">
|
||||||
{{ versionInfo.downloadUrl }}
|
{{ versionInfo.asarUrl }}
|
||||||
|
</el-link>
|
||||||
|
</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="JAR下载链接" v-if="versionInfo.jarUrl">
|
||||||
|
<el-link :href="versionInfo.jarUrl" target="_blank" type="success">
|
||||||
|
{{ versionInfo.jarUrl }}
|
||||||
</el-link>
|
</el-link>
|
||||||
</el-descriptions-item>
|
</el-descriptions-item>
|
||||||
</el-descriptions>
|
</el-descriptions>
|
||||||
@@ -34,25 +39,40 @@
|
|||||||
|
|
||||||
<!-- 上传对话框 -->
|
<!-- 上传对话框 -->
|
||||||
<el-dialog title="上传新版本" :visible.sync="uploadVisible" width="500px" append-to-body>
|
<el-dialog title="上传新版本" :visible.sync="uploadVisible" width="500px" append-to-body>
|
||||||
<el-form ref="uploadForm" :model="uploadForm" :rules="uploadRules" label-width="80px">
|
<el-form ref="uploadForm" :model="uploadForm" :rules="uploadRules" label-width="100px">
|
||||||
<el-form-item label="版本号" prop="version">
|
<el-form-item label="版本号" prop="version">
|
||||||
<el-input v-model="uploadForm.version" placeholder="请输入版本号,如:2.1.0"></el-input>
|
<el-input v-model="uploadForm.version" placeholder="请输入版本号,如:2.4.7"></el-input>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="版本文件" prop="file">
|
<el-form-item label="ASAR文件" prop="asarFile">
|
||||||
<el-upload
|
<el-upload
|
||||||
ref="upload"
|
ref="asarUpload"
|
||||||
action="#"
|
action="#"
|
||||||
:limit="1"
|
:limit="1"
|
||||||
accept=".asar"
|
accept=".asar"
|
||||||
:on-exceed="handleExceed"
|
:on-exceed="handleAsarExceed"
|
||||||
:file-list="fileList"
|
:file-list="asarFileList"
|
||||||
:auto-upload="false"
|
:auto-upload="false"
|
||||||
:on-change="handleFileChange"
|
:on-change="handleAsarFileChange"
|
||||||
:on-remove="handleFileRemove">
|
:on-remove="handleAsarFileRemove">
|
||||||
<el-button slot="trigger" size="small" type="primary">选择文件</el-button>
|
<el-button slot="trigger" size="small" type="primary">选择ASAR文件</el-button>
|
||||||
<div slot="tip" class="el-upload__tip">只能上传asar文件,且不超过800MB</div>
|
<div slot="tip" class="el-upload__tip">只能上传asar文件,且不超过800MB</div>
|
||||||
</el-upload>
|
</el-upload>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
|
<el-form-item label="JAR文件" prop="jarFile">
|
||||||
|
<el-upload
|
||||||
|
ref="jarUpload"
|
||||||
|
action="#"
|
||||||
|
:limit="1"
|
||||||
|
accept=".jar"
|
||||||
|
:on-exceed="handleJarExceed"
|
||||||
|
:file-list="jarFileList"
|
||||||
|
:auto-upload="false"
|
||||||
|
:on-change="handleJarFileChange"
|
||||||
|
:on-remove="handleJarFileRemove">
|
||||||
|
<el-button slot="trigger" size="small" type="success">选择JAR文件</el-button>
|
||||||
|
<div slot="tip" class="el-upload__tip">只能上传jar文件,且不超过200MB</div>
|
||||||
|
</el-upload>
|
||||||
|
</el-form-item>
|
||||||
</el-form>
|
</el-form>
|
||||||
<div slot="footer" class="dialog-footer">
|
<div slot="footer" class="dialog-footer">
|
||||||
<el-button @click="uploadVisible = false">取 消</el-button>
|
<el-button @click="uploadVisible = false">取 消</el-button>
|
||||||
@@ -77,7 +97,8 @@ export default {
|
|||||||
versionInfo: {
|
versionInfo: {
|
||||||
currentVersion: '2.0.0',
|
currentVersion: '2.0.0',
|
||||||
updateTime: null,
|
updateTime: null,
|
||||||
downloadUrl: null
|
asarUrl: null,
|
||||||
|
jarUrl: null
|
||||||
},
|
},
|
||||||
// 版本检查表单
|
// 版本检查表单
|
||||||
checkForm: {
|
checkForm: {
|
||||||
@@ -92,20 +113,19 @@ export default {
|
|||||||
// 上传表单
|
// 上传表单
|
||||||
uploadForm: {
|
uploadForm: {
|
||||||
version: '',
|
version: '',
|
||||||
file: null
|
asarFile: null,
|
||||||
|
jarFile: null
|
||||||
},
|
},
|
||||||
// 上传规则
|
// 上传规则
|
||||||
uploadRules: {
|
uploadRules: {
|
||||||
version: [
|
version: [
|
||||||
{ required: true, message: "版本号不能为空", trigger: "blur" },
|
{ required: true, message: "版本号不能为空", trigger: "blur" },
|
||||||
{ pattern: /^\d+\.\d+\.\d+$/, message: "版本号格式不正确,应为x.y.z格式", trigger: "blur" }
|
{ pattern: /^\d+\.\d+\.\d+$/, message: "版本号格式不正确,应为x.y.z格式", trigger: "blur" }
|
||||||
],
|
|
||||||
file: [
|
|
||||||
{ required: true, message: "请选择要上传的文件", trigger: "change" }
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
// 文件列表
|
// 文件列表
|
||||||
fileList: [],
|
asarFileList: [],
|
||||||
|
jarFileList: [],
|
||||||
// 上传加载状态
|
// 上传加载状态
|
||||||
uploadLoading: false,
|
uploadLoading: false,
|
||||||
// 上传进度
|
// 上传进度
|
||||||
@@ -132,59 +152,106 @@ export default {
|
|||||||
resetUploadForm() {
|
resetUploadForm() {
|
||||||
this.uploadForm = {
|
this.uploadForm = {
|
||||||
version: '',
|
version: '',
|
||||||
file: null
|
asarFile: null,
|
||||||
|
jarFile: null
|
||||||
};
|
};
|
||||||
this.fileList = [];
|
this.asarFileList = [];
|
||||||
|
this.jarFileList = [];
|
||||||
this.uploadProgress = 0;
|
this.uploadProgress = 0;
|
||||||
if (this.$refs.uploadForm) {
|
if (this.$refs.uploadForm) {
|
||||||
this.$refs.uploadForm.resetFields();
|
this.$refs.uploadForm.resetFields();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
/** 文件超出限制 */
|
/** ASAR文件超出限制 */
|
||||||
handleExceed() {
|
handleAsarExceed() {
|
||||||
this.$modal.msgError("只能选择一个文件");
|
this.$modal.msgError("只能选择一个ASAR文件");
|
||||||
},
|
},
|
||||||
/** 文件改变 */
|
/** ASAR文件改变 */
|
||||||
handleFileChange(file, fileList) {
|
handleAsarFileChange(file, fileList) {
|
||||||
this.uploadForm.file = file.raw;
|
this.uploadForm.asarFile = file.raw;
|
||||||
this.fileList = fileList;
|
this.asarFileList = fileList;
|
||||||
},
|
},
|
||||||
/** 文件移除 */
|
/** ASAR文件移除 */
|
||||||
handleFileRemove() {
|
handleAsarFileRemove() {
|
||||||
this.uploadForm.file = null;
|
this.uploadForm.asarFile = null;
|
||||||
this.fileList = [];
|
this.asarFileList = [];
|
||||||
|
},
|
||||||
|
/** JAR文件超出限制 */
|
||||||
|
handleJarExceed() {
|
||||||
|
this.$modal.msgError("只能选择一个JAR文件");
|
||||||
|
},
|
||||||
|
/** JAR文件改变 */
|
||||||
|
handleJarFileChange(file, fileList) {
|
||||||
|
this.uploadForm.jarFile = file.raw;
|
||||||
|
this.jarFileList = fileList;
|
||||||
|
},
|
||||||
|
/** JAR文件移除 */
|
||||||
|
handleJarFileRemove() {
|
||||||
|
this.uploadForm.jarFile = null;
|
||||||
|
this.jarFileList = [];
|
||||||
},
|
},
|
||||||
/** 提交上传 */
|
/** 提交上传 */
|
||||||
submitUpload() {
|
submitUpload() {
|
||||||
this.$refs.uploadForm.validate(valid => {
|
this.$refs.uploadForm.validate(valid => {
|
||||||
if (valid) {
|
if (valid) {
|
||||||
if (!this.uploadForm.file) {
|
if (!this.uploadForm.asarFile && !this.uploadForm.jarFile) {
|
||||||
this.$modal.msgError("请选择要上传的文件");
|
this.$modal.msgError("请至少选择一个文件上传");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.uploadForm.file.size > 800 * 1024 * 1024) {
|
// 验证ASAR文件
|
||||||
this.$modal.msgError("文件大小不能超过800MB");
|
if (this.uploadForm.asarFile) {
|
||||||
|
if (this.uploadForm.asarFile.size > 800 * 1024 * 1024) {
|
||||||
|
this.$modal.msgError("ASAR文件大小不能超过800MB");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!this.uploadForm.asarFile.name.endsWith('.asar')) {
|
||||||
if (!this.uploadForm.file.name.endsWith('.asar')) {
|
|
||||||
this.$modal.msgError("只支持上传.asar文件");
|
this.$modal.msgError("只支持上传.asar文件");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证JAR文件
|
||||||
|
if (this.uploadForm.jarFile) {
|
||||||
|
if (this.uploadForm.jarFile.size > 200 * 1024 * 1024) {
|
||||||
|
this.$modal.msgError("JAR文件大小不能超过200MB");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!this.uploadForm.jarFile.name.endsWith('.jar')) {
|
||||||
|
this.$modal.msgError("只支持上传.jar文件");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
this.uploadLoading = true;
|
this.uploadLoading = true;
|
||||||
|
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('files', this.uploadForm.file);
|
if (this.uploadForm.asarFile) {
|
||||||
|
formData.append('files', this.uploadForm.asarFile);
|
||||||
|
}
|
||||||
|
if (this.uploadForm.jarFile) {
|
||||||
|
formData.append('files', this.uploadForm.jarFile);
|
||||||
|
}
|
||||||
|
|
||||||
uploadFile(formData).then(response => {
|
uploadFile(formData).then(response => {
|
||||||
if (response && response.data[0]) {
|
if (response && response.data) {
|
||||||
const fileInfo = response.data[0];
|
let asarUrl = null;
|
||||||
const downloadUrl = fileInfo.fileUrl || fileInfo.url;
|
let jarUrl = null;
|
||||||
|
|
||||||
|
// 解析上传结果
|
||||||
|
response.data.forEach(fileInfo => {
|
||||||
|
const url = fileInfo.fileUrl || fileInfo.url;
|
||||||
|
if (fileInfo.fileName && fileInfo.fileName.endsWith('.asar')) {
|
||||||
|
asarUrl = url;
|
||||||
|
} else if (fileInfo.fileName && fileInfo.fileName.endsWith('.jar')) {
|
||||||
|
jarUrl = url;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
updateVersion({
|
updateVersion({
|
||||||
version: this.uploadForm.version,
|
version: this.uploadForm.version,
|
||||||
downloadUrl: downloadUrl
|
asarUrl: asarUrl,
|
||||||
|
jarUrl: jarUrl
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
this.$modal.msgSuccess("版本文件上传成功");
|
this.$modal.msgSuccess("版本文件上传成功");
|
||||||
this.uploadVisible = false;
|
this.uploadVisible = false;
|
||||||
|
|||||||
Reference in New Issue
Block a user