liufumingren 0adaaa5bd6 feat: 打包模式工牌扫码上线/下线、多成员管理与30分钟自动登出等
打包模式(pages/packaging):
- 工牌(base64 JSON)扫码识别,经 index.queryUserByToken 查询用户:同用户已在线则下线,否则绑定为在线成员
- 多成员模型 workbenchMembers:弹窗仅展示成员列表+逐个下线;上报打包携带全部在线成员(users)
- 成员列表以服务端 getWorkbenchInfo.members 为准,绑定/下线后静默重拉
- 无在线成员时非工牌码拦截提示需要先登录,不走查询用户
- 带打包台 token 请求 401/403 统一清除工作台状态回登录(请求守卫)
- 30 分钟无新打包任务:结束打包任务+下线全部成员(不退出工作台模式,留在当前页)
- 移除手动退出工作台入口;扫描记录持久化 localStorage(50 条出入栈)
- 操作员列表弹窗重新排版(头像/姓名/下线按钮)

其他:
- 登录页扫码/更新流程、导航守卫与路由封装、Electron 主进程/预加载、发布脚本与配置模板(deploy.example.json)等调整
2026-09-19 01:05:54 +08:00

347 lines
9.2 KiB
JavaScript

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')
}
// ---------- 本地静态服务: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,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
},
})
if (devServerUrl) {
win.webContents.session.clearCache().catch(() => {})
win.loadURL(devServerUrl)
win.webContents.openDevTools({ mode: 'detach' })
} else {
const port = await startStaticServer()
win.loadURL(`http://127.0.0.1:${port}/`)
}
// 不显示窗口标题栏下的菜单
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) {
return
}
const mediaPermissions = new Set(['media', 'videoCapture', 'audioCapture', 'camera', 'microphone'])
ses.setPermissionCheckHandler((webContents, permission) => {
if (mediaPermissions.has(permission)) {
return true
}
return false
})
ses.setPermissionRequestHandler((webContents, permission, callback) => {
callback(mediaPermissions.has(permission))
})
if (typeof ses.setDevicePermissionHandler === 'function') {
ses.setDevicePermissionHandler((details) => {
return details.deviceType === 'videoCapture' || details.deviceType === 'audioCapture'
})
}
}
// ---------- 单实例锁:防止同时打开两个应用实例 ----------
const gotTheLock = app.requestSingleInstanceLock()
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.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()
}
})
}