diff --git a/.env.example b/.env.example index f95d9fb..6d798c9 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,5 @@ # 环境变量模板:复制本文件为 .env.local 并填写真实值(.env.local 不提交 git) # 详见 config/README.md +# 仅开发环境生效:生产构建(electron/Android 打包)固定使用 https://qimen.wms.gztbyc.com,见 env.js VITE_API_BASE_URL=http://your-server-ip:6060 VITE_IMG_URL=https://your-img-domain.com diff --git a/.gitignore b/.gitignore index 6a47656..6f01ef0 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ dist # build artifacts (exe under release/windows, apk under release/android) release +build/.icon-ico # Android offline packaging # keystore files and local config (contains secrets) are NOT tracked. @@ -21,6 +22,7 @@ release # See config/README.md for all config conventions. android-offline/keystore/ config/android.json +config/deploy.json # Android SDK project: sources are tracked (ensure consistent build base), # only local build outputs are excluded. diff --git a/android-offline/pack.ps1 b/android-offline/pack.ps1 index d14c76e..057dfc6 100644 --- a/android-offline/pack.ps1 +++ b/android-offline/pack.ps1 @@ -8,11 +8,13 @@ # .\pack.ps1 -VersionName "1.0.2" # override version (written back to package.json; versionCode auto-derived) # .\pack.ps1 -VersionCode 10002 # manually set versionCode (rarely needed) # .\pack.ps1 -NoInject # skip prepare.cjs injection (already injected) +# .\pack.ps1 -NoUpload # package only, skip publish upload (scp + latest.json) # .\pack.ps1 -JavaHome '...' -AndroidSdk '...' param( [switch]$Clean, [switch]$Timestamp, [switch]$NoInject, + [switch]$NoUpload, [string]$VersionName = "", [string]$VersionCode = "", [string]$JavaHome = "", @@ -221,4 +223,80 @@ Write-Host " size : ${apkSize} MB" Write-Host " version : $verName ($verCode)" Write-Host "===================================================" -ForegroundColor Green +# ============ publish upload (scp + latest.json, same flow as sandan project) ============ +$deployCfgPath = Join-Path $projRoot 'config\deploy.json' +if ($NoUpload) { + Write-Host "" + Write-Host "[hint] -NoUpload specified, skip publish upload" -ForegroundColor DarkGray +} elseif (-not (Test-Path $deployCfgPath)) { + Write-Host "" + Write-Host "[hint] config/deploy.json not found, skip publish upload (copy config/deploy.example.json and fill real values)" -ForegroundColor DarkGray +} else { + $dcfg = Get-Content $deployCfgPath -Raw -Encoding UTF8 | ConvertFrom-Json + $dcfg = $dcfg.android + if (-not $dcfg) { + Write-Host "[error] config/deploy.json missing android section" -ForegroundColor Red + exit 1 + } + $dHost = [string]$dcfg.host + $dUser = [string]$dcfg.user + $dKey = [string]$dcfg.keyPath + $dRemDir = ([string]$dcfg.remoteDir).TrimEnd('/') + $dUrlPre = [string]$dcfg.downloadUrlPrefix + $dPort = 22 + if ($dcfg.port) { $dPort = [int]$dcfg.port } + $dLatest = 'latest.json' + if ($dcfg.latestJsonName) { $dLatest = [string]$dcfg.latestJsonName } + if ($dUrlPre -and -not $dUrlPre.EndsWith('/')) { $dUrlPre = $dUrlPre + '/' } + + $missing = @() + if (-not $dHost) { $missing += 'host' } + if (-not $dUser) { $missing += 'user' } + if (-not $dRemDir) { $missing += 'remoteDir' } + if (-not $dUrlPre) { $missing += 'downloadUrlPrefix' } + if ($missing.Count -gt 0) { + Write-Host "[error] config/deploy.json missing fields: $($missing -join ', ')" -ForegroundColor Red + exit 1 + } + if ($dKey -and -not (Test-Path $dKey)) { + Write-Host "[error] SSH key not found: $dKey" -ForegroundColor Red + exit 1 + } + + # generate latest.json (same directory as the APK) + $sha256 = (Get-FileHash -Path $apkDest -Algorithm SHA256).Hash + $dlUrl = "$dUrlPre$apkName" + $publishedAt = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + $latest = [ordered]@{ + version = $verName + file = $apkName + url = $dlUrl + sha256 = $sha256 + publishedAtUtc = $publishedAt + } + $latestPath = Join-Path $distDir $dLatest + [System.IO.File]::WriteAllText($latestPath, ($latest | ConvertTo-Json), (New-Object System.Text.UTF8Encoding($false))) + + Write-Host "" + Write-Host "[publish] upload to ${dUser}@${dHost}:${dRemDir}/ ..." -ForegroundColor Yellow + $scpArgs = @('-i', $dKey, '-P', "$dPort", '-o', 'StrictHostKeyChecking=accept-new') + & scp @scpArgs $apkDest "${dUser}@${dHost}:${dRemDir}/" + if ($LASTEXITCODE -ne 0) { + Write-Host "[error] APK upload failed (scp exit code $LASTEXITCODE)" -ForegroundColor Red + exit 1 + } + & scp @scpArgs $latestPath "${dUser}@${dHost}:${dRemDir}/" + if ($LASTEXITCODE -ne 0) { + Write-Host "[error] $dLatest upload failed (scp exit code $LASTEXITCODE)" -ForegroundColor Red + exit 1 + } + + Write-Host "" + Write-Host "================== publish done ==================" -ForegroundColor Green + Write-Host " download : $dlUrl" + Write-Host " sha256 : $sha256" + Write-Host " updated : ${dRemDir}/${dLatest}" + Write-Host "=================================================" -ForegroundColor Green +} + exit 0 diff --git a/config/README.md b/config/README.md index fd9f380..b6acbe0 100644 --- a/config/README.md +++ b/config/README.md @@ -8,16 +8,20 @@ |---|---|---| | `android.json` | Android 离线打包本地配置(包名、签名密码、AppKey 等) | ❌ 不提交(敏感) | | `android.example.json` | 上述配置的模板,首次使用复制为 `android.json` | ✅ 提交 | +| `deploy.json` | 发布配置(服务器 IP/账号/SSH 密钥路径/上传目录,分 android/windows 两段) | ❌ 不提交 | +| `deploy.example.json` | 发布配置模板,首次使用复制为 `deploy.json` | ✅ 提交 | `android.json` 字段说明:appId(uni-app appid)、appKey(dev.dcloud.net.cn 申请)、appName(应用名)、packageName(Android 包名)、abis(CPU 架构)、icon/splash(图标启动图路径,相对项目根)、wwwSource(可选:指定 App 资源目录,留空则自动用 dist/build/app 或 unpackage/resources)、signing(keystore 路径/密码)。 +`deploy.json` 字段说明:android 段(APK 发布,`android:pack` 打包后自动 scp 上传)与 windows 段(exe 发布,`build:exe` 打包后自动 scp 上传),每段含 host(服务器 IP)、port(SSH 端口)、user(SSH 用户)、keyPath(SSH 私钥路径)、remoteDir(服务器上传目录:APK 与散单项目同为 worker_station,exe 为 worker_station_windows)、downloadUrlPrefix(下载 URL 前缀)、latestJsonName(latest.json 文件名)。跳过上传:`-NoUpload`(APK)/ `--no-upload`(exe)。 + ## 根目录其他配置 | 文件 | 说明 | git | |---|---|---| | `.env` / `.env.electron` | Vite 构建目标(web/electron),无敏感信息 | ✅ 提交 | | `.env.example` | 环境变量模板(接口地址等),复制为 `.env.local` 填写 | ✅ 提交 | -| `.env.local` | 本地环境变量(含内网接口地址,勿提交) | ❌ 不提交(匹配 `*.local`) | +| `.env.local` | 本地开发环境变量(含内网测试接口地址,勿提交;**仅 dev 生效**,生产构建固定走 `https://qimen.wms.gztbyc.com`,见 `env.js`) | ❌ 不提交(匹配 `*.local`) | | `env.js` | 前端环境模块(读 Vite 环境变量,不写死敏感地址) | ✅ 提交 | | `electron-builder.config.cjs` | exe 打包配置(无敏感) | ✅ 提交 | @@ -33,6 +37,7 @@ ## 新机器初始化清单 1. `cp config/android.example.json config/android.json` 并填写(签名密钥放入 `android-offline/keystore/`) -2. `cp .env.example .env.local` 并填写接口地址 +2. `cp config/deploy.example.json config/deploy.json` 并填写(仅发布 APK 时需要) +3. `cp .env.example .env.local` 并填写接口地址 3. `npm install` -4. 打包:`npm run build:exe`(Windows)、`npm run android:pack`(Android) +4. 打包:`npm run build:exe`(Windows,发布到 worker_station_windows)、`npm run android:pack`(Android,发布到 worker_station) diff --git a/config/deploy.example.json b/config/deploy.example.json new file mode 100644 index 0000000..06dc795 --- /dev/null +++ b/config/deploy.example.json @@ -0,0 +1,21 @@ +{ + "_comment": "发布配置模板:复制本文件为 config/deploy.json 并填写真实值(deploy.json 已 git 忽略,不提交;本模板不含真实服务器信息)。android 段用于 APK 发布,windows 段用于 exe 发布,各字段含义见 config/README.md。", + "android": { + "host": "your-server-ip", + "port": 22, + "user": "your-ssh-user", + "keyPath": "C:/Users/yourname/.ssh/your_key", + "remoteDir": "/your/www/upload/dir", + "downloadUrlPrefix": "https://your-download-domain/your-project/", + "latestJsonName": "latest.json" + }, + "windows": { + "host": "your-server-ip", + "port": 22, + "user": "your-ssh-user", + "keyPath": "C:/Users/yourname/.ssh/your_key", + "remoteDir": "/your/www/upload/dir", + "downloadUrlPrefix": "https://your-download-domain/your-project/", + "latestJsonName": "latest.json" + } +} diff --git a/electron/icon.png b/electron/icon.png new file mode 100644 index 0000000..85cb8d3 Binary files /dev/null and b/electron/icon.png differ diff --git a/electron/main.js b/electron/main.js index 88ce55a..65d753d 100644 --- a/electron/main.js +++ b/electron/main.js @@ -1,14 +1,97 @@ -const { app, BrowserWindow, session } = require('electron') +const { app, BrowserWindow, session, ipcMain, shell, Tray, Menu, nativeImage } = require('electron') const path = require('path') +const fs = require('fs') +const os = require('os') +const https = require('https') +const http = require('http') const devServerUrl = process.env.ELECTRON_RENDERER_URL const rendererEntry = path.join(__dirname, '..', 'dist', 'build', 'h5', 'index.html') +let tray = null +let isQuitting = false + if (devServerUrl) { app.commandLine.appendSwitch('disable-http-cache') } -function createWindow() { +// ---------- 本地静态服务:history 模式路由需要 http 协议(file:// 下 pushState 被禁用) ---------- +const STATIC_MIME = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.gif': 'image/gif', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.webp': 'image/webp', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.ttf': 'font/ttf', + '.mp3': 'audio/mpeg', + '.map': 'application/json; charset=utf-8', +} + +let staticServer = null +let staticServerPort = 0 + +function serveFile(filePath, res) { + const ext = path.extname(filePath).toLowerCase() + res.writeHead(200, { 'Content-Type': STATIC_MIME[ext] || 'application/octet-stream' }) + fs.createReadStream(filePath).pipe(res) +} + +function startStaticServer() { + if (staticServer) { + return Promise.resolve(staticServerPort) + } + const rootDir = path.dirname(rendererEntry) + const server = http.createServer((req, res) => { + let urlPath = '/' + try { + urlPath = decodeURIComponent(String(req.url || '/').split('?')[0]) + } catch (e) { + urlPath = '/' + } + if (!urlPath || urlPath === '/') { + serveFile(path.join(rootDir, 'index.html'), res) + return + } + // 防目录穿越 + const filePath = path.normalize(path.join(rootDir, urlPath)) + if (!filePath.startsWith(rootDir)) { + res.writeHead(403) + res.end('Forbidden') + return + } + fs.stat(filePath, (err, stat) => { + if (!err && stat.isDirectory()) { + serveFile(path.join(filePath, 'index.html'), res) + return + } + if (err || !stat.isFile()) { + // SPA 回退:history 路由统一返回 index.html + serveFile(path.join(rootDir, 'index.html'), res) + return + } + serveFile(filePath, res) + }) + }) + return new Promise((resolve, reject) => { + server.on('error', reject) + server.listen(0, '127.0.0.1', () => { + staticServer = server + staticServerPort = server.address().port + resolve(staticServerPort) + }) + }) +} + +async function createWindow() { const win = new BrowserWindow({ width: 1200, height: 800, @@ -23,12 +106,170 @@ function createWindow() { win.webContents.session.clearCache().catch(() => {}) win.loadURL(devServerUrl) win.webContents.openDevTools({ mode: 'detach' }) - return + } else { + const port = await startStaticServer() + win.loadURL(`http://127.0.0.1:${port}/`) } - win.loadFile(rendererEntry) + // 不显示窗口标题栏下的菜单 + win.removeMenu() + + // 点关闭按钮时不退出,隐藏到托盘;托盘菜单退出时才真正退出 + win.on('close', (event) => { + if (!isQuitting) { + event.preventDefault() + win.hide() + } + }) + + // 外部链接(更新下载地址等)交给系统浏览器打开 + win.webContents.setWindowOpenHandler(({ url }) => { + if (url && url.startsWith('http')) { + require('electron').shell.openExternal(url) + } + return { action: 'deny' } + }) + return win } +function getTrayIconPath() { + const candidates = [ + path.join(__dirname, 'icon.png'), + path.join(__dirname, '..', 'src', 'static', 'images', '1.png'), + path.join(__dirname, '..', 'dist', 'build', 'h5', 'static', 'images', '1.png'), + ] + return candidates.find((p) => fs.existsSync(p)) || '' +} + +function createTray(mainWindow) { + if (tray) { + return tray + } + + const iconPath = getTrayIconPath() + let image = nativeImage.createEmpty() + if (iconPath) { + const loaded = nativeImage.createFromPath(iconPath) + if (!loaded.isEmpty()) { + image = loaded.resize({ width: 16, height: 16 }) + } + } + + tray = new Tray(image) + tray.setToolTip('WMS工作台') + + const showWindow = () => { + if (!mainWindow || mainWindow.isDestroyed()) { + return + } + mainWindow.show() + if (mainWindow.isMinimized()) { + mainWindow.restore() + } + mainWindow.focus() + } + + tray.on('click', showWindow) + tray.setContextMenu( + Menu.buildFromTemplate([ + { label: '显示主界面', click: showWindow }, + { type: 'separator' }, + { + label: '退出', + click: () => { + isQuitting = true + app.quit() + }, + }, + ]) + ) + return tray +} + +function setupCorsHeaders() { + // 允许渲染进程跨域读取发布服务器上的 latest.json 等文件 + session.defaultSession.webRequest.onHeadersReceived((details, callback) => { + callback({ + responseHeaders: { + ...details.responseHeaders, + 'Access-Control-Allow-Origin': ['*'], + }, + }) + }) +} + +// ---------- 内置更新下载(主进程,支持重定向/重试与进度回传) ---------- +function downloadUpdateFile(url, dest, onProgress) { + return new Promise((resolve, reject) => { + const maxAttempts = 3 + let attempt = 0 + + const tryOnce = () => { + attempt++ + const start = (target, redirects) => { + if (redirects > 5) { + reject(new Error('重定向次数过多')) + return + } + const request = https.get( + target, + { headers: { 'User-Agent': 'wms-worker-station-updater' } }, + (res) => { + if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + res.resume() + start(new URL(res.headers.location, target).toString(), redirects + 1) + return + } + if (res.statusCode !== 200) { + res.resume() + reject(new Error(`HTTP ${res.statusCode}`)) + return + } + const total = Number(res.headers['content-length'] || 0) + let received = 0 + const file = fs.createWriteStream(dest) + res.on('data', (chunk) => { + received += chunk.length + onProgress(received, total) + }) + res.pipe(file) + file.on('finish', () => { + file.close(() => resolve(dest)) + }) + file.on('error', (error) => reject(error)) + } + ) + request.on('error', (error) => { + if (attempt < maxAttempts) { + console.warn(`[updater] 下载失败,重试 ${attempt}/${maxAttempts}: ${error.message}`) + tryOnce() + } else { + reject(error) + } + }) + } + start(url, 0) + } + + tryOnce() + }) +} + +ipcMain.handle('download-update', async (event, url) => { + const tmpPath = path.join(os.tmpdir(), `wms-worker-station-${Date.now()}-setup.exe`) + await downloadUpdateFile(url, tmpPath, (received, total) => { + if (!event.sender.isDestroyed()) { + event.sender.send('download-progress', { received, total }) + } + }) + return tmpPath +}) + +ipcMain.handle('open-installer', async (_event, filePath) => { + const result = await shell.openPath(filePath) + return result +}) + function setupMediaPermissions() { const ses = session.defaultSession if (!ses) { @@ -55,19 +296,51 @@ function setupMediaPermissions() { } } -app.whenReady().then(() => { - setupMediaPermissions() - createWindow() +// ---------- 单实例锁:防止同时打开两个应用实例 ---------- +const gotTheLock = app.requestSingleInstanceLock() - app.on('activate', () => { - if (BrowserWindow.getAllWindows().length === 0) { - createWindow() +if (!gotTheLock) { + app.quit() +} else { + // 用户再次启动应用时,唤起已有实例的窗口 + app.on('second-instance', () => { + const win = BrowserWindow.getAllWindows()[0] + if (win) { + if (win.isMinimized()) { + win.restore() + } + win.show() + win.focus() } }) -}) -app.on('window-all-closed', () => { - if (process.platform !== 'darwin') { - app.quit() - } -}) + app.whenReady().then(async () => { + setupMediaPermissions() + setupCorsHeaders() + const win = await createWindow() + createTray(win) + + app.on('activate', async () => { + const allWindows = BrowserWindow.getAllWindows() + if (allWindows.length === 0) { + try { + await createWindow() + } catch (error) { + console.error('[static-server] 启动失败:', error) + } + } else { + allWindows[0].show() + } + }) + }) + + app.on('before-quit', () => { + isQuitting = true + }) + + app.on('window-all-closed', () => { + if (process.platform !== 'darwin') { + app.quit() + } + }) +} diff --git a/electron/preload.js b/electron/preload.js index fcc8a49..8fe4b74 100644 --- a/electron/preload.js +++ b/electron/preload.js @@ -1,5 +1,15 @@ -const { contextBridge } = require('electron') +const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { platform: process.platform, + // 内置下载更新安装包(主进程下载,返回本地临时文件路径) + downloadUpdate: (url) => ipcRenderer.invoke('download-update', url), + // 监听下载进度,返回取消监听函数 + onDownloadProgress: (callback) => { + const listener = (_event, data) => callback(data) + ipcRenderer.on('download-progress', listener) + return () => ipcRenderer.removeListener('download-progress', listener) + }, + // 打开本地安装包(启动 NSIS 安装向导) + openInstaller: (filePath) => ipcRenderer.invoke('open-installer', filePath), }) diff --git a/env.js b/env.js index 73ec245..8bfea1f 100644 --- a/env.js +++ b/env.js @@ -1,4 +1,10 @@ -// 环境地址统一走 Vite 环境变量(见 .env.example / .env.local,敏感地址勿提交 git) -export const BASE_URL = import.meta.env.VITE_API_BASE_URL || '' // 接口根地址,由 .env.local 注入 +// 生产接口根地址:所有 production 构建(electron 打包 / Android 打包)统一指向生产域名, +// 避免构建机上残留的 .env.local 测试地址被带进生产包 +const PROD_API_BASE = 'https://qimen.wms.gztbyc.com' + +// 开发环境地址走 Vite 环境变量(见 .env.example / .env.local,敏感地址勿提交 git) +export const BASE_URL = import.meta.env.PROD + ? PROD_API_BASE + : import.meta.env.VITE_API_BASE_URL || '' // 接口根地址,开发时由 .env.local 注入 export const API_URL = `${BASE_URL}/system` // 后台接口域名 export const IMG_URL = import.meta.env.VITE_IMG_URL || 'https://ye4s.file.gzxunren.com' // 全局网络图片地址变量,css背景图片地址变量在uni.scss diff --git a/package.json b/package.json index bc11fc5..b098253 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "wms-worker-station", - "version": "1.0.1", + "version": "1.0.18", "description": "WMS仓库工作台桌面端", "author": "tianbao", "main": "electron/main.js", diff --git a/scripts/build-exe.cjs b/scripts/build-exe.cjs index c598fee..cec26df 100644 --- a/scripts/build-exe.cjs +++ b/scripts/build-exe.cjs @@ -1,13 +1,20 @@ /** - * 一键打包 Windows exe: - * 1. 编译前端资源到 dist/build/h5(uni build --mode electron) - * 2. 调用 electron-builder 生成 NSIS 安装包,输出到 release/ + * 一键打包 Windows exe 并发布: + * 1. 编译前端资源(uni build --mode electron) + * 2. electron-builder 生成 NSIS 安装包,输出 release/windows/ + * 3. 可选:读取 config/deploy.json 的 windows 段,scp 上传安装包与 latest.json + * 用法:node scripts/build-exe.cjs [--no-upload] */ const { spawnSync } = require('child_process') +const fs = require('fs') +const path = require('path') +const crypto = require('crypto') +const ROOT = path.resolve(__dirname, '..') const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm' const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx' const useShell = process.platform === 'win32' +const noUpload = process.argv.includes('--no-upload') function run(cmd, args) { const command = `${cmd} ${args.join(' ')}` @@ -22,7 +29,85 @@ function run(cmd, args) { console.log('[1/2] 编译前端资源 -> dist/build/h5') run(npmCmd, ['run', 'build:h5:electron']) -console.log('\n[2/2] electron-builder 打包 exe -> release/') +console.log('\n[2/2] electron-builder 打包 exe -> release/windows/') run(npxCmd, ['electron-builder', '--config', 'electron-builder.config.cjs']) +// ---------- 3. 发布上传(config/deploy.json 的 windows 段) ---------- +if (noUpload) { + console.log('\n[跳过] --no-upload 已指定,跳过发布上传') +} else { + const deployPath = path.join(ROOT, 'config', 'deploy.json') + if (!fs.existsSync(deployPath)) { + console.log('\n[跳过] 未找到 config/deploy.json,跳过发布上传(复制 config/deploy.example.json 并填写)') + } else { + let deploy + try { + deploy = JSON.parse(fs.readFileSync(deployPath, 'utf-8')) + } catch (error) { + console.error(`\n[x] config/deploy.json 解析失败: ${error.message}`) + process.exit(1) + } + const win = deploy.windows + if (!win || !win.host || !win.user || !win.remoteDir || !win.downloadUrlPrefix) { + console.log('\n[跳过] config/deploy.json 缺少 windows 段或字段不全,跳过发布上传') + } else { + const keyPath = win.keyPath || '' + if (keyPath && !fs.existsSync(keyPath)) { + console.error(`\n[x] SSH 密钥不存在: ${keyPath}`) + process.exit(1) + } + const port = String(win.port || 22) + const remoteDir = String(win.remoteDir).replace(/\/$/, '') + const urlPrefix = String(win.downloadUrlPrefix).replace(/\/?$/, '/') + const latestName = win.latestJsonName || 'latest.json' + + // 定位 NSIS 安装包(按当前版本精确匹配,避免目录残留旧包被误选) + const outDir = path.join(ROOT, 'release', 'windows') + const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf-8')) + const version = pkg.version + const productName = 'WMS工作台' + const expectedName = `${productName}-${version}-setup.exe` + const setupExe = fs.existsSync(path.join(outDir, expectedName)) + ? expectedName + : fs.readdirSync(outDir).find( + (file) => file.endsWith('.exe') && file.includes('setup') && !file.includes('__uninstaller') + ) + if (!setupExe) { + console.error('\\n[x] 未在 release/windows 找到安装包') + process.exit(1) + } + const exePath = path.join(outDir, setupExe) + const sha256 = crypto.createHash('sha256').update(fs.readFileSync(exePath)).digest('hex') + const latest = { + version, + file: setupExe, + url: `${urlPrefix}${setupExe}`, + sha256, + publishedAtUtc: new Date().toISOString(), + } + const latestPath = path.join(outDir, latestName) + fs.writeFileSync(latestPath, JSON.stringify(latest, null, 2) + '\n', 'utf-8') + + console.log(`\n[3/3] 发布上传 -> ${win.user}@${win.host}:${remoteDir}/ ...`) + const scpArgs = [ + ...(keyPath ? ['-i', keyPath] : []), + '-P', port, + '-o', 'StrictHostKeyChecking=accept-new', + ] + const target = `${win.user}@${win.host}:${remoteDir}/` + const uploadExe = spawnSync('scp', [...scpArgs, exePath, target], { stdio: 'inherit' }) + if (uploadExe.status !== 0) { + console.error(`\n[x] 安装包上传失败(scp 退出码 ${uploadExe.status})`) + process.exit(uploadExe.status || 1) + } + const uploadLatest = spawnSync('scp', [...scpArgs, latestPath, target], { stdio: 'inherit' }) + if (uploadLatest.status !== 0) { + console.error(`\n[x] ${latestName} 上传失败(scp 退出码 ${uploadLatest.status})`) + process.exit(uploadLatest.status || 1) + } + console.log(`\n[ok] 发布完成: ${urlPrefix}${setupExe}`) + } + } +} + console.log('\n[ok] 打包完成,安装包位于 release/windows/ 目录') diff --git a/scripts/gen-android-assets.ps1 b/scripts/gen-android-assets.ps1 index f5a8b50..d5772d8 100644 --- a/scripts/gen-android-assets.ps1 +++ b/scripts/gen-android-assets.ps1 @@ -137,6 +137,13 @@ function New-Splash([string]$path) { $iconPath = 'd:\wms_worker_station\android-offline\icon\app-icon.png' $splashPath = 'd:\wms_worker_station\android-offline\splash\splash.png' +$buildIconDir = 'd:\wms_worker_station\build' +$buildIconPath = Join-Path $buildIconDir 'icon.png' New-AppIcon $iconPath New-Splash $splashPath + +# Windows exe icon: electron-builder auto-converts build/icon.png (>=256x256) to .ico +if (-not (Test-Path $buildIconDir)) { New-Item -ItemType Directory -Path $buildIconDir -Force | Out-Null } +Copy-Item -Path $iconPath -Destination $buildIconPath -Force +Write-Host "windows icon saved: $buildIconPath" diff --git a/shims-uni.d.ts b/shims-uni.d.ts index ed4adcf..28db357 100644 --- a/shims-uni.d.ts +++ b/shims-uni.d.ts @@ -1,6 +1,10 @@ /// import 'vue' +declare const __APP_BUILD_TARGET__: string +declare const __APP_IS_ELECTRON__: boolean +declare const __APP_VERSION__: string + declare module '@vue/runtime-core' { type Hooks = App.AppInstance & Page.PageInstance; diff --git a/src/App.vue b/src/App.vue index d30fe64..eea6fcc 100644 --- a/src/App.vue +++ b/src/App.vue @@ -1,10 +1,12 @@