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