- 退件拆包: 参照散单 Web returnUnpackwork 移植(returnUnpack.*/stock.warehouse.search/order.detail 反查对照), 扫码指令条码(jsbarcode renderjs)、快扫串行队列+乐观累加、明细扫描行置顶、左右分栏原单对照汇总(未退回/一致/差异)、备注下拉选项本地持久化 - 摄像头: camera.ts(camera.list/setOsd、camera_server.*、getLiveStreamUrl 本地 MJPEG 代理), 设置弹窗+浮动预览窗(拖拽/全屏/最小化胶囊)、OSD 单号条码推送、fetch 探测 502 内网->公网回退 - exe 内置海康取流服务 electron/hikvision-live.js: 监听 127.0.0.1:17320(与 printServer 17311 隔离), ISAPI digest 登录+快照轮询 multipart MJPEG(~5fps, 零 npm 依赖); 端口候选回退 httpPort->port->80(NVR port 常为 RTSP 554); 通道号映射 0/1->主码流 101/2->子 102(100 无效通道 NVR 返回 503); writeHead 后 flushHeaders(否则首帧前响应头不 flush); 登录限时 3.5s; 登录失败 502 兜底图与 printServer 行为一致 - 全局 401 处理: 非 skipAuth 请求 code/status=401 清 token 回登录(3s 去抖), 工作台 token 请求由 packaging 页自处理 - 菜单路径别名: menuRouteMap 兼容后端短路径(/order)与完整路径(/pages/xxx/index); index 页 rawPath 未定义引用修复; 布局样式微调 - 已验证: 17320 起服务/config 200/真实 NVR(192.168.8.241 ch2, port=554)回退 80 出流 7 帧/端口占用 blocked; 通道1 Device Busy 为车间占流非代码问题
354 lines
9.6 KiB
JavaScript
354 lines
9.6 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 { startHikvisionLiveServer, stopHikvisionLiveServer } = require('./hikvision-live')
|
|
|
|
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)
|
|
|
|
// 内置海康取流服务(127.0.0.1:17320, HTTP 快照模式):端口空闲时自起,与 printServer(17311) 隔离
|
|
startHikvisionLiveServer()
|
|
.then((r) => console.log('[main] 海康取流服务状态:', JSON.stringify(r)))
|
|
.catch((e) => console.error('[main] 海康取流服务启动失败:', e))
|
|
|
|
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
|
|
stopHikvisionLiveServer()
|
|
})
|
|
|
|
app.on('window-all-closed', () => {
|
|
if (process.platform !== 'darwin') {
|
|
app.quit()
|
|
}
|
|
})
|
|
}
|