This commit is contained in:
2025-09-26 16:27:27 +08:00
parent 1d0bab7804
commit fcc5755dad
11 changed files with 403 additions and 745 deletions

View File

@@ -200,7 +200,8 @@
"Bash(./start-desktop-app.bat)", "Bash(./start-desktop-app.bat)",
"Bash(cnpm install:*)", "Bash(cnpm install:*)",
"Bash(cnpm uninstall:*)", "Bash(cnpm uninstall:*)",
"WebFetch(domain:www.electronjs.org)" "WebFetch(domain:www.electronjs.org)",
"Bash(test:*)"
], ],
"deny": [], "deny": [],
"ask": [], "ask": [],

View File

@@ -1,6 +1,7 @@
{ {
"appId": "com.erp.client", "appId": "com.erp.client",
"productName": "ERP客户端", "productName": "erpClient",
"asar": true,
"directories": { "directories": {
"output": "dist" "output": "dist"
}, },
@@ -12,7 +13,7 @@
"oneClick": false, "oneClick": false,
"perMachine": false, "perMachine": false,
"allowToChangeInstallationDirectory": true, "allowToChangeInstallationDirectory": true,
"shortcutName": "ERP客户端" "shortcutName": "erpClient"
}, },
"win": { "win": {
"target": "nsis", "target": "nsis",
@@ -40,5 +41,11 @@
"!build", "!build",
"!dist", "!dist",
"!scripts" "!scripts"
],
"extraResources": [
{
"from": "update-helper.bat",
"to": "../update-helper.bat"
}
] ]
} }

View File

@@ -1,16 +1,19 @@
// 主进程:创建窗口、启动后端 JAR、隐藏菜单栏 import {app, BrowserWindow, ipcMain, Menu, screen} from 'electron';
import {app, BrowserWindow, ipcMain, session, Menu, screen} from 'electron'; import { existsSync, createWriteStream, promises as fs, statSync } from 'fs';
import { Socket } from 'net';
import { existsSync } from 'fs';
import {join, dirname} from 'path'; import {join, dirname} from 'path';
import {spawn, ChildProcessWithoutNullStreams} from 'child_process'; import {spawn, ChildProcessWithoutNullStreams} from 'child_process';
import * as https from 'https';
import * as http from 'http';
// 保存后端进程与窗口引用,便于退出时清理
let springProcess: ChildProcessWithoutNullStreams | null = null; let springProcess: ChildProcessWithoutNullStreams | null = null;
let mainWindow: BrowserWindow | null = null; let mainWindow: BrowserWindow | null = null;
let splashWindow: BrowserWindow | null = null; let splashWindow: BrowserWindow | null = null;
let appOpened = false; let appOpened = false;
let downloadProgress = { percentage: 0, current: '0 MB', total: '0 MB', speed: '' };
let isDownloading = false;
let downloadedFilePath: string | null = null;
function openAppIfNotOpened() { function openAppIfNotOpened() {
if (appOpened) return; if (appOpened) return;
appOpened = true; appOpened = true;
@@ -18,10 +21,12 @@ function openAppIfNotOpened() {
mainWindow.show(); mainWindow.show();
mainWindow.focus(); mainWindow.focus();
} }
if (splashWindow) { splashWindow.close(); splashWindow = null; } if (splashWindow) {
splashWindow.close();
splashWindow = null;
}
} }
// 启动后端 Spring Boot使用你提供的绝对路径
function startSpringBoot() { function startSpringBoot() {
const jarPath = 'C:/Users/ZiJIe/Desktop/wox/RuoYi-Vue/ruoyi-admin/target/ruoyi-admin.jar'; const jarPath = 'C:/Users/ZiJIe/Desktop/wox/RuoYi-Vue/ruoyi-admin/target/ruoyi-admin.jar';
@@ -30,61 +35,44 @@ function startSpringBoot() {
detached: false detached: false
}); });
// 打印后端日志,监听启动成功标志
springProcess.stdout.on('data', (data) => { springProcess.stdout.on('data', (data) => {
console.log(`SpringBoot: ${data}`); console.log(`SpringBoot: ${data}`);
// 检测到启动成功日志立即进入主界面
if (data.toString().includes('Started RuoYiApplication')) { if (data.toString().includes('Started RuoYiApplication')) {
openAppIfNotOpened(); openAppIfNotOpened();
} }
}); });
// 打印后端错误,检测启动失败
springProcess.stderr.on('data', (data) => { springProcess.stderr.on('data', (data) => {
console.error(`SpringBoot ERROR: ${data}`); console.error(`SpringBoot ERROR: ${data}`);
const errorStr = data.toString(); const errorStr = data.toString();
// 检测到关键错误信息,直接退出
if (errorStr.includes('APPLICATION FAILED TO START') || if (errorStr.includes('APPLICATION FAILED TO START') ||
errorStr.includes('Port') && errorStr.includes('already in use') || errorStr.includes('Port') && errorStr.includes('already in use') ||
errorStr.includes('Unable to start embedded Tomcat')) { errorStr.includes('Unable to start embedded Tomcat')) {
console.error('后端启动失败,程序即将退出');
app.quit(); app.quit();
} }
}); });
// 后端退出时,前端同步退出
springProcess.on('close', (code) => { springProcess.on('close', (code) => {
console.log(`SpringBoot exited with code ${code}`); console.log(`SpringBoot exited with code ${code}`);
if (mainWindow) { mainWindow ? mainWindow.close() : app.quit();
mainWindow.close();
} else {
app.quit();
}
}); });
} }
// 关闭后端进程Windows 使用 taskkill 结束整个进程树)
function stopSpringBoot() { function stopSpringBoot() {
if (!springProcess) return; if (!springProcess) return;
try { try {
if (process.platform === 'win32') { if (process.platform === 'win32') {
// Force kill the whole process tree on Windows
try {
const pid = springProcess.pid; const pid = springProcess.pid;
if (pid !== undefined && pid !== null) { if (pid) {
spawn('taskkill', ['/pid', String(pid), '/f', '/t']); spawn('taskkill', ['/pid', String(pid), '/f', '/t']);
} else { } else {
springProcess.kill(); springProcess.kill();
} }
} catch (e) {
// Fallback
springProcess.kill();
}
} else { } else {
springProcess.kill('SIGTERM'); springProcess.kill('SIGTERM');
} }
} catch (e) { } catch (e) {
console.error('Failed to stop Spring Boot process:', e); console.error('Failed to stop Spring Boot:', e);
} finally { } finally {
springProcess = null; springProcess = null;
} }
@@ -96,7 +84,7 @@ function createWindow () {
height: 800, height: 800,
show: false, show: false,
autoHideMenuBar: true, autoHideMenuBar: true,
icon: join(__dirname, '../renderer/icon/icon.png'), // 添加窗口图标 icon: join(__dirname, '../renderer/icon/icon.png'),
webPreferences: { webPreferences: {
preload: join(__dirname, 'preload.js'), preload: join(__dirname, 'preload.js'),
nodeIntegration: false, nodeIntegration: false,
@@ -104,16 +92,14 @@ function createWindow () {
} }
}); });
// 彻底隐藏原生菜单栏 mainWindow.webContents.openDevTools();
try {
Menu.setApplicationMenu(null); Menu.setApplicationMenu(null);
mainWindow.setMenuBarVisibility(false); mainWindow.setMenuBarVisibility(false);
if (typeof (mainWindow as any).setMenu === 'function') {
(mainWindow as any).setMenu(null);
}
} catch {}
// 生产环境加载本地文件 mainWindow.webContents.once('did-finish-load', () => {
setTimeout(() => checkPendingUpdate(), 500);
});
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
const rendererPort = process.argv[2] || 8083; const rendererPort = process.argv[2] || 8083;
mainWindow.loadURL(`http://localhost:${rendererPort}`); mainWindow.loadURL(`http://localhost:${rendererPort}`);
@@ -123,16 +109,12 @@ function createWindow () {
} }
app.whenReady().then(() => { app.whenReady().then(() => {
// 预创建主窗口(隐藏)
createWindow(); createWindow();
// 显示启动页
const { width: sw, height: sh } = screen.getPrimaryDisplay().workAreaSize; const { width: sw, height: sh } = screen.getPrimaryDisplay().workAreaSize;
const splashW = Math.min(Math.floor(sw * 0.8), 1800);
const splashH = Math.min(Math.floor(sh * 0.8), 1200);
splashWindow = new BrowserWindow({ splashWindow = new BrowserWindow({
width: splashW, width: Math.min(Math.floor(sw * 0.8), 1800),
height: splashH, height: Math.min(Math.floor(sh * 0.8), 1200),
frame: false, frame: false,
transparent: false, transparent: false,
resizable: false, resizable: false,
@@ -141,37 +123,23 @@ app.whenReady().then(() => {
center: true, center: true,
}); });
const candidateSplashPaths = [ const splashPath = join(__dirname, '../../public', 'splash.html');
join(__dirname, '../../public', 'splash.html'), if (existsSync(splashPath)) {
]; splashWindow.loadFile(splashPath);
const foundSplash = candidateSplashPaths.find(p => existsSync(p));
if (foundSplash) {
splashWindow.loadFile(foundSplash);
} }
// 注释掉后端启动,便于快速调试前端 setTimeout(() => openAppIfNotOpened(), 1000);
// startSpringBoot();
// 快速调试模式 - 直接打开主窗口 app.on('activate', () => {
setTimeout(() => {
openAppIfNotOpened();
}, 1000);
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) { if (BrowserWindow.getAllWindows().length === 0) {
createWindow(); createWindow();
} }
}); });
}); });
app.on('window-all-closed', function () { app.on('window-all-closed', () => {
stopSpringBoot(); stopSpringBoot();
if (process.platform !== 'darwin') app.quit() if (process.platform !== 'darwin') app.quit();
}); });
app.on('before-quit', () => { app.on('before-quit', () => {
@@ -180,5 +148,199 @@ app.on('before-quit', () => {
ipcMain.on('message', (event, message) => { ipcMain.on('message', (event, message) => {
console.log(message); console.log(message);
}) });
function checkPendingUpdate() {
try {
const updateFilePath = join(process.resourcesPath, 'app.asar.update');
const appAsarPath = join(process.resourcesPath, 'app.asar');
if (!existsSync(updateFilePath)) return;
const appDir = dirname(process.execPath);
const helperPath = join(appDir, 'update-helper.bat');
if (!existsSync(helperPath)) {
console.error('[UPDATE] 更新助手不存在:', helperPath);
return;
}
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`;
require('fs').writeFileSync(vbsPath, vbsContent);
spawn('wscript.exe', [vbsPath], {
detached: true,
stdio: 'ignore',
shell: false
});
setTimeout(() => app.quit(), 1000);
} catch (error) {
console.error('[UPDATE] 更新失败:', error);
}
}
ipcMain.handle('download-update', async (event, downloadUrl: string) => {
if (isDownloading) return { success: false, error: '正在下载中' };
if (downloadedFilePath === 'completed') return { success: true, filePath: 'already-completed' };
isDownloading = true;
try {
const isRealDev = process.env.NODE_ENV === 'development' && !app.isPackaged;
if (isRealDev) {
for (let i = 0; i <= 100; i += 10) {
setTimeout(() => {
downloadProgress = {
percentage: i,
current: (i * 0.5).toFixed(1) + ' MB',
total: '50.0 MB',
speed: '2.5 MB/s'
};
if (mainWindow) {
mainWindow.webContents.send('download-progress', downloadProgress);
}
}, i * 100);
}
setTimeout(() => {
downloadedFilePath = 'completed';
isDownloading = false;
}, 1100);
return { success: true, filePath: 'dev-mode-simulated', dev: true };
}
const tempPath = join(app.getPath('temp'), 'app.asar.new');
await downloadFile(downloadUrl, tempPath, (progress) => {
downloadProgress = progress;
if (mainWindow) {
mainWindow.webContents.send('download-progress', progress);
}
});
if (!existsSync(tempPath)) {
throw new Error('下载文件不存在');
}
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('更新文件保存失败');
}
downloadedFilePath = 'completed';
isDownloading = false;
return { success: true, filePath: updateFilePath };
} catch (error) {
isDownloading = false;
downloadedFilePath = null;
const tempPath = join(app.getPath('temp'), 'app.asar.new');
if (existsSync(tempPath)) {
fs.unlink(tempPath).catch(() => {});
}
return { success: false, error: error instanceof Error ? error.message : '下载失败' };
}
});
ipcMain.handle('get-download-progress', () => {
return { ...downloadProgress, isDownloading };
});
ipcMain.handle('install-update', async () => {
try {
const isRealDev = process.env.NODE_ENV === 'development' && !app.isPackaged;
if (isRealDev) {
downloadedFilePath = null;
return { success: true, message: '开发环境模拟重启' };
}
const updateFilePath = join(process.resourcesPath, 'app.asar.update');
const hasUpdateFile = existsSync(updateFilePath);
if (!downloadedFilePath || (downloadedFilePath !== 'completed' && !hasUpdateFile)) {
return { success: false, error: '更新文件不存在' };
}
setTimeout(() => {
downloadedFilePath = null;
app.quit();
}, 500);
return { success: true };
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : '重启失败' };
}
});
ipcMain.handle('cancel-download', () => {
isDownloading = false;
downloadProgress = { percentage: 0, current: '0 MB', total: '0 MB', speed: '' };
downloadedFilePath = null;
return { success: true };
});
ipcMain.handle('get-update-status', () => {
const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged || process.defaultApp;
return { downloadedFilePath, isDownloading, downloadProgress, isPackaged: app.isPackaged, isDev };
});
async function downloadFile(url: string, filePath: string, onProgress: (progress: any) => void): Promise<void> {
return new Promise((resolve, reject) => {
const protocol = url.startsWith('https') ? https : http;
protocol.get(url, (response) => {
if (response.statusCode !== 200) {
reject(new Error(`HTTP ${response.statusCode}`));
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 });
});
response.pipe(fileStream);
fileStream.on('finish', () => {
fileStream.close();
resolve();
});
fileStream.on('error', (error) => {
fs.unlink(filePath).catch(() => {});
reject(error);
});
}).on('error', reject);
});
}

View File

@@ -0,0 +1,22 @@
import { contextBridge, ipcRenderer } from 'electron'
const electronAPI = {
sendMessage: (message: string) => ipcRenderer.send('message', message),
downloadUpdate: (downloadUrl: string) => ipcRenderer.invoke('download-update', downloadUrl),
getDownloadProgress: () => ipcRenderer.invoke('get-download-progress'),
installUpdate: () => ipcRenderer.invoke('install-update'),
cancelDownload: () => ipcRenderer.invoke('cancel-download'),
getUpdateStatus: () => ipcRenderer.invoke('get-update-status'),
onDownloadProgress: (callback: (progress: any) => void) => {
ipcRenderer.on('download-progress', (event, progress) => callback(progress))
},
removeDownloadProgressListener: () => {
ipcRenderer.removeAllListeners('download-progress')
}
}
contextBridge.exposeInMainWorld('electronAPI', electronAPI)
export type ElectronApi = typeof electronAPI

View File

@@ -416,25 +416,14 @@ async function confirmRemoveDevice(row: DeviceItem & { isCurrent?: boolean }) {
} }
} }
// 启动时检查更新
async function checkForUpdates() {
// 延迟3秒后自动检查更新
setTimeout(() => {
showUpdateDialog.value = true
}, 3000)
}
onMounted(async () => { onMounted(async () => {
showContent() showContent()
await checkAuth() await checkAuth()
})
// 启动时检查更新 onUnmounted(() => {
await checkForUpdates()
// 监听页面关闭断开SSE连接会自动设置离线
window.addEventListener('beforeunload', () => {
SSEManager.disconnect() SSEManager.disconnect()
})
}) })
</script> </script>
@@ -445,7 +434,6 @@ onMounted(async () => {
<div class="loading-container" id="loading"> <div class="loading-container" id="loading">
<div class="loading-spinner"></div> <div class="loading-spinner"></div>
</div> </div>
<div class="erp-container"> <div class="erp-container">
<div class="sidebar"> <div class="sidebar">
<div class="user-avatar"> <div class="user-avatar">

View File

@@ -2,19 +2,15 @@
<div> <div>
<div class="version-info" @click="autoCheck">v{{ version || '-' }}</div> <div class="version-info" @click="autoCheck">v{{ version || '-' }}</div>
<el-dialog v-model="show" width="522px" :close-on-click-modal="false" align-center class="update-dialog" title="软件更新" <el-dialog v-model="show" width="522px" :close-on-click-modal="false" align-center class="update-dialog" title="软件更新">
:show-close="true"
custom-class="update-dialog">
<!-- 状态检查更新 -->
<div v-if="stage === 'check'" class="update-content"> <div v-if="stage === 'check'" class="update-content">
<div class="update-layout"> <div class="update-layout">
<div class="left-pane"> <div class="left-pane">
<img src="/icon/icon.png" class="app-icon app-icon-large" alt="App Icon" /> <img src="/icon/icon.png" class="app-icon app-icon-large" alt="App Icon" />
</div> </div>
<div class="right-pane"> <div class="right-pane">
<p class="announce">新版本的"{{ appName || 'App Name' }}"已经发布</p> <p class="announce">新版本的"{{ appName }}"已经发布</p>
<p class="desc">{{ (appName || 'App Name') }} {{ info.latestVersion || '-' }} 可供下载您现在的版本是 {{ version || '-' }}要现在下载吗?</p> <p class="desc">{{ appName }} {{ info.latestVersion }} 可供安装您现在的版本是 {{ version }}要现在安装吗</p>
<div class="update-details form"> <div class="update-details form">
<h4>更新信息</h4> <h4>更新信息</h4>
@@ -24,21 +20,17 @@
class="notes-box" class="notes-box"
:rows="6" :rows="6"
readonly readonly
resize="none" resize="none" />
placeholder="• 优化了用户界面体验&#10;• 修复了已知问题&#10;• 提升了系统稳定性&#10;• 增加了新的功能模块&#10;• 优化了数据处理性能" />
</div> </div>
<div class="update-actions row"> <div class="update-actions row">
<div class="auto-update-section">
<el-checkbox v-model="autoUpdateSelected">以后自动下载并安装更新</el-checkbox>
</div>
<div class="update-buttons"> <div class="update-buttons">
<div class="left-actions"> <div class="left-actions">
<el-button size="small" @click="show=false">跳过这个版本</el-button> <el-button size="small" @click="show=false">跳过这个版本</el-button>
</div> </div>
<div class="right-actions"> <div class="right-actions">
<el-button size="small" @click="show=false">稍后提醒</el-button> <el-button size="small" @click="show=false">稍后提醒</el-button>
<el-button size="small" type="primary" @click="start">安装更新</el-button> <el-button size="small" type="primary" @click="start">下载更新</el-button>
</div> </div>
</div> </div>
</div> </div>
@@ -46,12 +38,11 @@
</div> </div>
</div> </div>
<!-- 状态正在下载 -->
<div v-else-if="stage === 'downloading'" class="update-content"> <div v-else-if="stage === 'downloading'" class="update-content">
<div class="update-header text-center"> <div class="update-header text-center">
<img src="/icon/icon.png" class="app-icon" alt="App Icon" /> <img src="/icon/icon.png" class="app-icon" alt="App Icon" />
<h3>正在更新 {{ appName || 'erp' }}</h3> <h3>正在更新 {{ appName }}</h3>
<p>正在下载新版...</p> <p>正在下载更新文件...</p>
</div> </div>
<div class="download-progress"> <div class="download-progress">
@@ -68,19 +59,22 @@
<span v-if="prog.speed">{{ prog.speed }}</span> <span v-if="prog.speed">{{ prog.speed }}</span>
</div> </div>
</div> </div>
<div class="update-buttons">
<el-button @click="cancelDownload">取消下载</el-button>
</div>
</div> </div>
<!-- 状态下载完成 -->
<div v-else-if="stage === 'completed'" class="update-content"> <div v-else-if="stage === 'completed'" class="update-content">
<div class="update-header text-center"> <div class="update-header text-center">
<img src="/icon/icon.png" class="app-icon" alt="App Icon" /> <img src="/icon/icon.png" class="app-icon" alt="App Icon" />
<h3>正在更新 {{ appName || '我了个电商' }}</h3> <h3>更新完成</h3>
<p>可以开始安装了</p> <p>更新文件已下载将在重启后自动应用</p>
</div> </div>
<div class="download-progress"> <div class="download-progress">
<div class="progress-info"> <div class="progress-info">
<span>{{ prog.current }} /{{ prog.total }}</span> <span>{{ prog.current }} / {{ prog.total }}</span>
</div> </div>
<el-progress <el-progress
:percentage="100" :percentage="100"
@@ -91,7 +85,7 @@
<div class="update-buttons"> <div class="update-buttons">
<el-button @click="cancelDownload">稍后更新</el-button> <el-button @click="cancelDownload">稍后更新</el-button>
<el-button type="primary" @click="installUpdate">安装并重新启动</el-button> <el-button type="primary" @click="installUpdate">重启应用新版本</el-button>
</div> </div>
</div> </div>
</el-dialog> </el-dialog>
@@ -99,16 +93,12 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue' import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { updateApi } from '../../api/update'
const props = defineProps<{ const props = defineProps<{ modelValue: boolean }>()
modelValue: boolean const emit = defineEmits<{ 'update:modelValue': [value: boolean] }>()
}>()
const emit = defineEmits<{
'update:modelValue': [value: boolean]
}>()
const show = computed({ const show = computed({
get: () => props.modelValue, get: () => props.modelValue,
@@ -118,154 +108,142 @@ const show = computed({
type Stage = 'check' | 'downloading' | 'completed' type Stage = 'check' | 'downloading' | 'completed'
const stage = ref<Stage>('check') const stage = ref<Stage>('check')
const appName = ref('ERP客户端') const appName = ref('ERP客户端')
const autoUpdateSelected = ref(false) const version = ref('2.0.0')
const prog = ref({ percentage: 0, current: '0 MB', total: '0 MB', speed: '' }) const prog = ref({ percentage: 0, current: '0 MB', total: '0 MB', speed: '' as string | undefined })
const version = ref('2.0.0') // 当前版本号
const downloadedFilePath = ref('') // 下载文件路径
const info = ref({ const info = ref({
latestVersion: '2.4.8', latestVersion: '2.4.8',
downloadUrl: 'https://qiniu.pxdj.tashowz.com/2025/09/f492725041ba43fb8ded9344ec08d646.exe', downloadUrl: '',
updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性\n• 增加了新的功能模块\n• 优化了数据处理性能' updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性\n• 增加了新的功能模块\n• 优化了数据处理性能'
}) })
// 自动检查更新
async function autoCheck() { async function autoCheck() {
try { try {
ElMessage.info('正在检查更新...') ElMessage({ message: '正在检查更新...', type: 'info' })
console.log('手动检查更新...')
try {
version.value = await updateApi.getVersion()
} catch (error) {
console.error('获取版本失败:', error)
version.value = '2.0.0'
}
info.value = {
currentVersion: version.value,
latestVersion: '2.4.9',
downloadUrl: 'https://qiniu.pxdj.tashowz.com/2025/09/becac13811214c909d11162d2ff2c863.asar',
updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性\n• 轻量级更新仅替换app.asar',
hasUpdate: true
}
if (window.electronAPI?.checkForUpdates) {
await window.electronAPI.checkForUpdates()
} else {
// 如果没有 API直接显示更新对话框
setTimeout(() => {
show.value = true show.value = true
stage.value = 'check' stage.value = 'check'
}, 500) ElMessage({ message: '发现新版本', type: 'success' })
}
} catch (error) { } catch (error) {
console.error('检查更新失败:', error) console.error('检查更新失败:', error)
ElMessage.error('检查更新失败') ElMessage({ message: '检查更新失败', type: 'error' })
} }
} }
// 开始安装更新
async function start() { async function start() {
if (!info.value.downloadUrl) {
ElMessage({ message: '下载链接不可用', type: 'error' })
return
}
if (!window.electronAPI) {
ElMessage({ message: '更新功能不可用', type: 'error' })
return
}
stage.value = 'downloading' stage.value = 'downloading'
prog.value = { percentage: 0, current: '0 MB', total: '0 MB', speed: '' } prog.value = { percentage: 0, current: '0 MB', total: '0 MB', speed: '' }
try { window.electronAPI.onDownloadProgress((progress) => {
if (info.value.downloadUrl && window.electronAPI?.downloadUpdate) { prog.value = {
console.log('开始下载:', info.value.downloadUrl) percentage: progress.percentage || 0,
current: progress.current || '0 MB',
// 直接打开浏览器下载,不模拟进度 total: progress.total || '0 MB',
const result = await window.electronAPI.downloadUpdate(info.value.downloadUrl) speed: progress.speed || ''
if (result.success) {
ElMessage.success('下载链接已在浏览器中打开,请等待下载完成后手动安装')
show.value = false
} else {
throw new Error(result.error)
} }
})
try {
const response = await window.electronAPI.downloadUpdate(info.value.downloadUrl)
if (response.success) {
stage.value = 'completed'
prog.value.percentage = 100
ElMessage({ message: '下载完成', type: 'success' })
} else { } else {
ElMessage.error('下载链接不可用') ElMessage({ message: '下载失败: ' + (response.error || '未知错误'), type: 'error' })
show.value = false stage.value = 'check'
} }
} catch (error) { } catch (error) {
console.error('下载失败:', error) console.error('下载失败:', error)
ElMessage.error('下载失败: ' + error) ElMessage({ message: '下载失败', type: 'error' })
show.value = false stage.value = 'check'
} }
} }
// 取消下载 async function cancelDownload() {
function cancelDownload() { try {
if (window.electronAPI) {
window.electronAPI.removeDownloadProgressListener()
await window.electronAPI.cancelDownload()
}
show.value = false show.value = false
stage.value = 'check' stage.value = 'check'
} catch (error) {
console.error('取消下载失败:', error)
show.value = false
stage.value = 'check'
}
} }
// 安装更新
async function installUpdate() { async function installUpdate() {
try { try {
ElMessage.success('正在安装更新,程序将自动重启...') await ElMessageBox.confirm(
console.log('准备安装更新') '安装过程中程序将自动重启,请确保已保存所有工作。确定要立即安装更新吗?',
'确认安装',
{
confirmButtonText: '立即安装',
cancelButtonText: '取消',
type: 'warning'
}
)
// 通过 IPC 重启应用 if (!window.electronAPI) {
if (window.electronAPI?.restartApp) { ElMessage({ message: '更新功能不可用', type: 'error' })
setTimeout(async () => { return
await window.electronAPI.restartApp() }
}, 1000) // 延迟1秒重启
const response = await window.electronAPI.installUpdate()
if (response.success) {
ElMessage({ message: '应用即将重启', type: 'success' })
setTimeout(() => show.value = false, 1000)
} else { } else {
// 如果没有重启API手动关闭窗口 ElMessage({ message: '重启失败: ' + (response.error || '未知错误'), type: 'error' })
setTimeout(() => { stage.value = 'check'
window.close()
}, 1000)
} }
show.value = false
} catch (error) { } catch (error) {
console.error('重启失败:', error) if (error !== 'cancel') {
ElMessage.error('重启失败,请手动重启应用') console.error('安装失败:', error)
ElMessage({ message: '安装失败', type: 'error' })
}
} }
} }
// 监听对话框显示 onMounted(async () => {
watch(show, async (visible) => {
if (visible) {
await fetchUpdateInfo()
stage.value = 'check'
}
})
async function fetchUpdateInfo() {
try { try {
// 获取当前版本 version.value = await updateApi.getVersion()
if (window.electronAPI?.getVersion) {
const currentVersion = await window.electronAPI.getVersion()
version.value = currentVersion
}
} catch (error) { } catch (error) {
console.error('获取更新信息失败:', error) console.error('获取版本失败:', error)
} }
}
// 监听主进程的更新通知
onMounted(() => {
if (window.electronAPI?.onShowUpdateDialog) {
window.electronAPI.onShowUpdateDialog((updateData) => {
console.log('收到更新通知:', updateData)
// 更新信息
if (updateData.currentVersion) {
version.value = updateData.currentVersion
}
if (updateData.latestVersion) {
info.value.latestVersion = updateData.latestVersion
}
if (updateData.downloadUrl) {
info.value.downloadUrl = updateData.downloadUrl
}
if (updateData.updateNotes) {
info.value.updateNotes = updateData.updateNotes
}
// 显示对话框
show.value = true
stage.value = 'check'
})
}
// 初始化获取版本信息
fetchUpdateInfo()
}) })
// 暴露方法供父组件调用 onUnmounted(() => {
defineExpose({ if (window.electronAPI) {
showUpdate: (updateData: any) => { window.electronAPI.removeDownloadProgressListener()
if (updateData.currentVersion) version.value = updateData.currentVersion
if (updateData.latestVersion) info.value.latestVersion = updateData.latestVersion
if (updateData.updateNotes) info.value.updateNotes = updateData.updateNotes
if (updateData.downloadUrl) info.value.downloadUrl = updateData.downloadUrl
show.value = true
} }
}) })
</script> </script>
@@ -285,7 +263,6 @@ defineExpose({
user-select: none; user-select: none;
} }
/* 更新对话框整体样式 */
:deep(.update-dialog .el-dialog) { :deep(.update-dialog .el-dialog) {
border-radius: 16px; border-radius: 16px;
box-shadow: 0 24px 48px rgba(0, 0, 0, 0.15); box-shadow: 0 24px 48px rgba(0, 0, 0, 0.15);
@@ -296,29 +273,6 @@ defineExpose({
text-align: left; text-align: left;
} }
:deep(.update-dialog .el-dialog__headerbtn) {
top: 12px;
right: 20px;
width: 32px;
height: 32px;
font-size: 18px;
border-radius: 50%;
background-color: transparent;
}
:deep(.update-dialog .el-dialog__headerbtn:hover) {
background-color: #f5f5f5;
}
:deep(.update-dialog .el-dialog__close) {
color: #909399;
font-weight: 400;
}
:deep(.update-dialog .el-dialog__close:hover) {
color: #409EFF;
}
:deep(.update-dialog .el-dialog__body) { :deep(.update-dialog .el-dialog__body) {
padding: 0; padding: 0;
} }
@@ -365,11 +319,6 @@ defineExpose({
margin-bottom: 16px; margin-bottom: 16px;
} }
.update-header-content {
flex: 1;
min-width: 0;
}
.update-header h3 { .update-header h3 {
font-size: 20px; font-size: 20px;
font-weight: 600; font-weight: 600;
@@ -400,28 +349,6 @@ defineExpose({
margin: 0 0 8px 0; margin: 0 0 8px 0;
} }
.update-details p {
font-size: 13px;
color: #6b7280;
line-height: 1.6;
margin: 0 0 16px 0;
white-space: pre-wrap;
}
.update-details p:last-child {
margin-bottom: 0;
}
.auto-update-section {
margin: 0;
}
:deep(.auto-update-section .el-checkbox) {
color: #374151;
font-size: 14px;
}
.update-actions.row { .update-actions.row {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -435,16 +362,10 @@ defineExpose({
gap: 12px; gap: 12px;
} }
/* 检查更新页:按钮单独一行并靠右,不拉伸 */
.update-actions.row .update-buttons { justify-content: space-between; } .update-actions.row .update-buttons { justify-content: space-between; }
:deep(.update-actions.row .update-buttons .el-button) { flex: none; min-width: 100px; } :deep(.update-actions.row .update-buttons .el-button) { flex: none; min-width: 100px; }
.left-actions { display: flex; gap: 12px; } .left-actions { display: flex; gap: 12px; }
.right-actions { display: flex; } .right-actions { display: flex; gap: 8px; }
.update-buttons.text-center {
justify-content: center;
}
:deep(.update-buttons .el-button) { :deep(.update-buttons .el-button) {
flex: 1; flex: 1;
@@ -453,12 +374,6 @@ defineExpose({
border-radius: 8px; border-radius: 8px;
} }
:deep(.update-buttons.text-center .el-button) {
flex: none;
min-width: 140px;
}
/* 下载进度区域 */
.download-progress { .download-progress {
margin: 24px 0; margin: 24px 0;
} }
@@ -480,7 +395,6 @@ defineExpose({
justify-content: space-between; justify-content: space-between;
} }
/* 进度条自定义样式 */
:deep(.el-progress-bar__outer) { :deep(.el-progress-bar__outer) {
border-radius: 4px; border-radius: 4px;
background-color: #e5e7eb; background-color: #e5e7eb;
@@ -491,7 +405,6 @@ defineExpose({
transition: width 0.3s ease; transition: width 0.3s ease;
} }
/* 按钮样式调整 */
:deep(.update-buttons .el-button--primary) { :deep(.update-buttons .el-button--primary) {
background-color: #2563eb; background-color: #2563eb;
border-color: #2563eb; border-color: #2563eb;
@@ -514,19 +427,4 @@ defineExpose({
background-color: #e5e7eb; background-color: #e5e7eb;
border-color: #9ca3af; border-color: #9ca3af;
} }
/* 响应式调整 */
@media (max-width: 480px) {
.update-content {
padding: 24px 16px;
}
.update-buttons {
flex-direction: column;
}
:deep(.update-buttons .el-button) {
flex: none;
}
}
</style> </style>

View File

@@ -3,6 +3,15 @@
*/ */
export default interface ElectronApi { export default interface ElectronApi {
sendMessage: (message: string) => void sendMessage: (message: string) => void
downloadUpdate: (downloadUrl: string) => Promise<{ success: boolean; filePath?: string; error?: string }>
getDownloadProgress: () => Promise<{ percentage: number; current: string; total: string; speed: string; isDownloading: boolean }>
installUpdate: () => Promise<{ success: boolean; error?: string }>
cancelDownload: () => Promise<{ success: boolean }>
onDownloadProgress: (callback: (progress: any) => void) => void
removeDownloadProgressListener: () => void
getUpdateStatus: () => Promise<{ downloadedFilePath: string | null; isDownloading: boolean; downloadProgress: any; isPackaged: boolean }>
onUpdateLog: (callback: (log: string) => void) => void
removeUpdateLogListener: () => void
} }
declare global { declare global {

View File

@@ -1,19 +1,11 @@
package com.tashow.erp.controller; package com.tashow.erp.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* Web版本更新控制器 * Web版本信息控制器
* *
* @author Claude * @author Claude
*/ */
@@ -24,16 +16,6 @@ public class UpdateController {
private String currentVersion; private String currentVersion;
@Value("${project.build.time:}") @Value("${project.build.time:}")
private String buildTime; private String buildTime;
// 简化:移除与鉴权/版本转发/SQLite 存储相关的依赖
// 下载进度跟踪
private volatile int downloadProgress = 0;
private volatile long downloadedBytes = 0;
private volatile long totalBytes = 0;
private volatile String downloadStatus = "ready"; // ready, downloading, completed, failed, cancelled
private volatile String downloadSpeed = "0 KB/s";
private volatile long downloadStartTime = 0;
private volatile boolean downloadCancelled = false;
/** /**
* 获取当前版本号 * 获取当前版本号
@@ -48,415 +30,4 @@ public class UpdateController {
result.put("buildTime", buildTime); result.put("buildTime", buildTime);
return result; return result;
} }
/**
* 获取下载进度
*
* @return 下载进度信息
*/
@GetMapping("/progress")
public Map<String, Object> getDownloadProgress() {
Map<String, Object> result = new HashMap<>();
result.put("success", true);
result.put("progress", downloadProgress);
result.put("status", downloadStatus);
result.put("downloadedBytes", downloadedBytes);
result.put("totalBytes", totalBytes);
result.put("downloadSpeed", downloadSpeed);
result.put("downloadedMB", String.format("%.1f", downloadedBytes / 1024.0 / 1024.0));
result.put("totalMB", String.format("%.1f", totalBytes / 1024.0 / 1024.0));
return result;
}
/**
* 重置下载状态
*
* @return 重置结果
*/
@PostMapping("/reset")
public Map<String, Object> resetDownloadStatus() {
Map<String, Object> result = new HashMap<>();
downloadProgress = 0;
downloadedBytes = 0;
totalBytes = 0;
downloadStatus = "ready";
downloadSpeed = "0 KB/s";
downloadStartTime = 0;
downloadCancelled = false;
tempUpdateFilePath = null;
result.put("success", true);
result.put("message", "下载状态已重置");
return result;
}
/**
* 取消下载
*
* @return 取消结果
*/
@PostMapping("/cancel")
public Map<String, Object> cancelDownload() {
Map<String, Object> result = new HashMap<>();
if ("downloading".equals(downloadStatus)) {
downloadCancelled = true;
downloadStatus = "cancelled";
downloadSpeed = "已取消";
result.put("success", true);
result.put("message", "下载已取消");
} else if ("completed".equals(downloadStatus)) {
// 下载完成后“稍后更新”:仅关闭弹窗,不触发安装,不改变文件
result.put("success", true);
result.put("message", "已设置为稍后更新");
} else {
result.put("success", false);
result.put("message", "无效的操作状态");
}
return result;
}
/**
* 完全清除更新文件和状态
*
* @return 清除结果
*/
@PostMapping("/clear")
public Map<String, Object> clearUpdateFiles() {
Map<String, Object> result = new HashMap<>();
if (tempUpdateFilePath != null) {
try {
java.io.File tempFile = new java.io.File(tempUpdateFilePath);
if (tempFile.exists()) {
tempFile.delete();
System.out.println("已删除更新文件: " + tempUpdateFilePath);
}
} catch (Exception e) {
System.err.println("删除临时文件失败: " + e.getMessage());
}
}
// 重置状态
downloadProgress = 0;
downloadedBytes = 0;
totalBytes = 0;
downloadStatus = "ready";
downloadSpeed = "0 KB/s";
downloadCancelled = false;
tempUpdateFilePath = null;
result.put("success", true);
result.put("message", "更新文件和状态已清除");
return result;
}
/**
* 验证更新文件是否存在
*
* @return 验证结果
*/
@GetMapping("/verify-file")
public Map<String, Object> verifyUpdateFile() {
Map<String, Object> result = new HashMap<>();
try {
boolean fileExists = false;
String filePath = "";
if (tempUpdateFilePath != null) {
java.io.File updateFile = new java.io.File(tempUpdateFilePath);
fileExists = updateFile.exists();
filePath = tempUpdateFilePath;
if (fileExists) {
result.put("fileSize", updateFile.length());
result.put("lastModified", new java.util.Date(updateFile.lastModified()));
}
}
result.put("success", true);
result.put("fileExists", fileExists);
result.put("filePath", filePath);
result.put("downloadStatus", downloadStatus);
System.out.println("验证更新文件: " + filePath + ", 存在: " + fileExists);
} catch (Exception e) {
result.put("success", false);
result.put("message", "验证文件失败:" + e.getMessage());
result.put("fileExists", false);
}
return result;
}
/**
* 用户确认后执行安装
*
* @return 安装结果
*/
@PostMapping("/install")
public Map<String, Object> installUpdate() {
Map<String, Object> result = new HashMap<>();
if (tempUpdateFilePath == null || !new java.io.File(tempUpdateFilePath).exists()) {
result.put("success", false);
result.put("message", "更新文件不存在,请重新下载");
return result;
}
try {
result.put("success", true);
result.put("message", "开始安装更新...");
// 异步执行安装,避免阻塞响应
new Thread(() -> {
String updateScript = createUpdateScript(null, tempUpdateFilePath);
if (updateScript != null) {
executeUpdateAndExit(updateScript);
}
}).start();
} catch (Exception e) {
result.put("success", false);
result.put("message", "启动安装失败:" + e.getMessage());
}
return result;
}
/**
* 自动更新:下载、替换、重启
*
* @return 更新结果
*/
@PostMapping("/auto-update")
public Map<String, Object> autoUpdate(@RequestBody Map<String, String> request) {
Map<String, Object> result = new HashMap<>();
try {
String downloadUrl = request.get("downloadUrl");
result.put("success", true);
result.put("message", "开始自动更新...");
result.put("downloadUrl", downloadUrl);
String finalDownloadUrl = downloadUrl;
new Thread(() -> {
performUpdate(finalDownloadUrl);
}).start();
} catch (Exception e) {
result.put("success", false);
result.put("message", "启动更新失败:" + e.getMessage());
}
return result;
}
/**
* 执行更新过程
*/
private void performUpdate(String downloadUrl) {
String tempUpdateFile = downloadUpdate(downloadUrl);
if (tempUpdateFile == null) {
downloadStatus = "failed";
return;
}
// 下载完成后不自动重启,等待用户确认
downloadStatus = "completed";
System.out.println("下载完成,等待用户确认安装...");
// 将下载文件路径保存,供后续安装使用
this.tempUpdateFilePath = tempUpdateFile;
}
private String tempUpdateFilePath = null;
/**
* 下载更新文件
*/
private String downloadUpdate(String downloadUrl) {
try {
downloadStatus = "downloading";
downloadProgress = 0;
downloadedBytes = 0;
downloadStartTime = System.currentTimeMillis();
URL url = new URL(downloadUrl);
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
connection.setConnectTimeout(10000);
connection.setReadTimeout(30000);
// 获取文件大小
totalBytes = connection.getContentLength();
if (totalBytes <= 0) {
totalBytes = 70 * 1024 * 1024; // 默认70MB
}
String tempDir = System.getProperty("java.io.tmpdir");
String updateFileName = "erp_update_" + System.currentTimeMillis() + ".exe";
String tempUpdatePath = Paths.get(tempDir, updateFileName).toString();
System.out.println("开始下载更新文件,大小: " + (totalBytes / 1024 / 1024) + "MB");
try (InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(tempUpdatePath)) {
byte[] buffer = new byte[8192];
int bytesRead;
long lastSpeedUpdate = System.currentTimeMillis();
long lastDownloadedBytes = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
if (downloadCancelled) {
System.out.println("下载已取消,停止下载进程");
downloadStatus = "cancelled";
downloadSpeed = "已取消";
outputStream.close();
try {
java.io.File partialFile = new java.io.File(tempUpdatePath);
if (partialFile.exists()) {
partialFile.delete();
}
} catch (Exception e) {
System.err.println("删除部分下载文件失败: " + e.getMessage());
}
return null;
}
outputStream.write(buffer, 0, bytesRead);
downloadedBytes += bytesRead;
// 计算下载进度
downloadProgress = (int) ((downloadedBytes * 100) / totalBytes);
// 每秒计算一次下载速度
long currentTime = System.currentTimeMillis();
if (currentTime - lastSpeedUpdate >= 1000) {
long speedBytes = downloadedBytes - lastDownloadedBytes;
double speedKB = speedBytes / 1024.0;
if (speedKB >= 1024) {
downloadSpeed = String.format("%.1f MB/s", speedKB / 1024.0);
} else {
downloadSpeed = String.format("%.1f KB/s", speedKB);
}
lastSpeedUpdate = currentTime;
lastDownloadedBytes = downloadedBytes;
System.out.println(String.format("下载进度: %d%% (%d/%d MB) 速度: %s",
downloadProgress,
downloadedBytes / 1024 / 1024,
totalBytes / 1024 / 1024,
downloadSpeed));
}
// 防止阻塞UI线程
if (downloadedBytes % (1024 * 1024) == 0) { // 每MB休息一下
Thread.sleep(10);
}
}
downloadStatus = "completed";
downloadProgress = 100;
downloadSpeed = "完成";
System.out.println("下载完成: " + (downloadedBytes / 1024 / 1024) + "MB");
}
return tempUpdatePath;
} catch (Exception e) {
downloadStatus = "failed";
downloadSpeed = "失败";
System.err.println("下载失败: " + e.getMessage());
e.printStackTrace();
return null;
}
}
/**
* 创建更新脚本
*/
private String createUpdateScript(String currentExePath, String tempUpdateFile) {
try {
String tempDir = System.getProperty("java.io.tmpdir");
String scriptPath = Paths.get(tempDir, "update_erp.bat").toString();
File currentDir = new File(System.getProperty("user.dir"));
File targetExe = new File(currentDir, "erpClient.exe");
String targetPath = targetExe.getAbsolutePath();
StringBuilder script = new StringBuilder();
script.append("@echo off\r\n");
script.append("chcp 65001 > nul\r\n");
script.append("echo 正在等待程序完全退出...\r\n");
script.append("timeout /t 1 /nobreak > nul\r\n");
script.append("echo 开始更新程序文件...\r\n");
script.append("if exist \"").append(targetPath).append("\" (");
script.append(" move \"").append(targetPath).append("\" \"").append(targetPath).append(".backup\"");
script.append(" )\r\n");
script.append("move \"").append(tempUpdateFile).append("\" \"").append(targetPath).append("\"\r\n");
script.append("if exist \"").append(targetPath).append("\" (\r\n");
script.append(" echo 更新成功程序将在1秒后重新启动...\r\n");
script.append(" timeout /t 1 /nobreak > nul\r\n");
script.append(" start \"\" \"").append(targetPath).append("\"\r\n");
script.append(" if exist \"").append(targetPath).append(".backup\" del \"").append(targetPath).append(".backup\"\r\n");
script.append(") else (\r\n");
script.append(" echo 更新失败!正在恢复原版本...\r\n");
script.append(" if exist \"").append(targetPath).append(".backup\" (\r\n");
script.append(" move \"").append(targetPath).append(".backup\" \"").append(targetPath).append("\"\r\n");
script.append(" echo 已恢复原版本程序将在1秒后重新启动...\r\n");
script.append(" timeout /t 1 /nobreak > nul\r\n");
script.append(" start \"\" \"").append(targetPath).append("\"\r\n");
script.append(" )\r\n");
script.append(")\r\n");
script.append("echo 更新操作完成!\r\n");
script.append("timeout /t 1 /nobreak > nul\r\n");
script.append("(goto) 2>nul & del \"%~f0\" & exit\r\n");
Files.write(Paths.get(scriptPath), script.toString().getBytes("GBK"));
return scriptPath;
} catch (Exception e) {
return null;
}
}
/**
* 执行更新脚本并退出程序
*/
private void executeUpdateAndExit(String scriptPath) {
try {
System.out.println("下载完成!正在准备更新...");
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", scriptPath);
pb.redirectOutput(ProcessBuilder.Redirect.DISCARD);
pb.redirectError(ProcessBuilder.Redirect.DISCARD);
pb.start();
System.out.println("更新程序已启动,当前程序即将退出...");
Thread.sleep(1000);
Runtime.getRuntime().halt(0);
} catch (Exception e) {
Runtime.getRuntime().halt(1);
}
}
// /**
// * 保存跳过的版本
// */
// @PostMapping("/skip-version")
// public Map<String, Object> saveSkippedVersion(@RequestBody Map<String, String> request) {
// Map<String, Object> result = new HashMap<>();
// try {
// saveUpdateInfo("skippedUpdateVersion", request.get("version"));
// result.put("success", true);
// } catch (Exception e) {
// result.put("success", false);
// }
// return result;
// }
} }

View File

@@ -36,11 +36,6 @@ public class VersionController extends BaseController {
try { try {
// 从Redis获取最新版本信息 // 从Redis获取最新版本信息
String latestVersion = redisTemplate.opsForValue().get(VERSION_REDIS_KEY); String latestVersion = redisTemplate.opsForValue().get(VERSION_REDIS_KEY);
if (StringUtils.isEmpty(latestVersion)) {
latestVersion = "2.0.0"; // 默认版本
}
// 比较版本号 // 比较版本号
boolean needUpdate = compareVersions(currentVersion, latestVersion) < 0; boolean needUpdate = compareVersions(currentVersion, latestVersion) < 0;

View File

@@ -13,6 +13,7 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.IOException; import java.io.IOException;
@@ -40,7 +41,11 @@ public class FileController {
private final Auth auth; private final Auth auth;
@PostMapping("/uploads") @PostMapping("/uploads")
public AjaxResult uploadFiles(List<MultipartFile> files) { public AjaxResult uploadFiles(@RequestParam("files") List<MultipartFile> files) {
if (files == null || files.isEmpty()) {
return AjaxResult.error("没有选择文件");
}
List<FileDto> fileDtoS = new ArrayList<>(); List<FileDto> fileDtoS = new ArrayList<>();
for (MultipartFile file : files) { for (MultipartFile file : files) {
String extName = FileUtil.extName(file.getOriginalFilename()); String extName = FileUtil.extName(file.getOriginalFilename());
@@ -59,7 +64,7 @@ public class FileController {
e.printStackTrace(); e.printStackTrace();
} }
} }
return AjaxResult.success(fileDtoS) ; return AjaxResult.success(fileDtoS);
} }
} }

View File

@@ -137,6 +137,6 @@ xss:
# 过滤开关 # 过滤开关
enabled: true enabled: true
# 排除链接(多个用逗号分隔) # 排除链接(多个用逗号分隔)
excludes: /system/notice,/tool/webmagic excludes: /system/notice,/tool/webmagic,/file/*
# 匹配链接 # 匹配链接
urlPatterns: /system/*,/monitor/*,/tool/* urlPatterns: /system/*,/monitor/*,/tool/*