diff --git a/build.ps1 b/build.ps1 index fbee9c2..35193e2 100644 --- a/build.ps1 +++ b/build.ps1 @@ -354,7 +354,7 @@ function Ensure-PackagedResources() { Copy-Item -Path $iconSourcePath -Destination $iconTargetPath -Force } - foreach ($dirName in @('daemon')) { + foreach ($dirName in @('daemon', 'frpc')) { $sourcePath = Join-Path $root $dirName $targetPath = Join-Path $resourcesDir $dirName diff --git a/config.json b/config.json index 0b7949e..59e1dae 100644 --- a/config.json +++ b/config.json @@ -1,6 +1,16 @@ { - "port": 3000, - "wsPort": 3001, + "wsPort": 17301, + "wsPorts": [ + 17301, + 17302, + 17303 + ], + "httpPort": 17311, + "httpPorts": [ + 17311, + 17312, + 17313 + ], "logLevel": "info", "printerDefault": "", "maxPrintJobs": 10, @@ -9,8 +19,14 @@ "url": "ws://printer.wms.gztbyc.com/ws", "reconnectInterval": 3000 }, + "hikvision": { + "downloadDir": "G:/gameauto/recordings", + "maxStorage": "50GB", + "circularRecording": true + }, "refreshTokenExpireTime": 0, - "tokenExpireTime": 1780684406126, - "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3YXJlaG91c2UiOiIxMDAwMDAiLCJjb21wdXRlcklkIjoiMjgiLCJpYXQiOjE3ODA2ODA4MDYsImV4cCI6MTc4MDY4NDQwNn0.O3Kzn4dVqkzSY8YT6nN_RpulznGPq4_LY6SY6o30cGk", - "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3YXJlaG91c2UiOiIxMDAwMDAiLCJjb21wdXRlcklkIjoiMjgiLCJpYXQiOjE3Nzg2MTAwNDMsImV4cCI6NDkzNDM3MDA0M30.JkOtPdc6VA5IDxy6E6Pqk5nffmE5VagoXtXYr7cNLZc" + "tokenExpireTime": 1784925603819, + "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3YXJlaG91c2UiOiIxMDAwMDAiLCJjb21wdXRlcklkIjoiMjgiLCJpYXQiOjE3ODQ5MjIwMDMsImV4cCI6MTc4NDkyNTYwM30.lpXdfZaIgoJhW0neOT6tzg7JhqFqfmVytWgkwgQlmc8", + "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3YXJlaG91c2UiOiIxMDAwMDAiLCJjb21wdXRlcklkIjoiMjgiLCJpYXQiOjE3Nzg2MTAwNDMsImV4cCI6NDkzNDM3MDA0M30.JkOtPdc6VA5IDxy6E6Pqk5nffmE5VagoXtXYr7cNLZc", + "name": "" } \ No newline at end of file diff --git a/config.packaged.json b/config.packaged.json index dc0585e..9de4351 100644 --- a/config.packaged.json +++ b/config.packaged.json @@ -1,6 +1,8 @@ { - "port": 3000, - "wsPort": 3001, + "wsPort": 17301, + "wsPorts": [17301, 17302, 17303], + "httpPort": 17311, + "httpPorts": [17311, 17312, 17313], "logLevel": "info", "printerDefault": "", "maxPrintJobs": 10, @@ -9,6 +11,11 @@ "url": "ws://printer.wms.gztbyc.com/ws", "reconnectInterval": 3000 }, + "hikvision": { + "downloadDir": "G:/gameauto/recordings", + "maxStorage": "50GB", + "circularRecording": true + }, "update": { "feedUrl": "https://dl.wms.gztbyc.com/printServer/latest.json", "downloadBaseUrl": "https://dl.wms.gztbyc.com/printServer" diff --git a/core/main.js b/core/main.js index 106db13..d30a6ba 100644 --- a/core/main.js +++ b/core/main.js @@ -7,7 +7,9 @@ import fs from 'fs'; import { pathToFileURL } from 'url'; import path from 'path'; import EventEmitter from 'events'; -import { getResourcePath } from '../utils/runtime.js'; +import { getResourcePath, getProjectRoot, extractPortCandidates, writeRuntimeState, isRecordingMode, getRunMode } from '../utils/runtime.js'; +import db from '../utils/db.js'; +import http from 'http'; function hasProcessArg(flag) { return process.argv.includes(flag); @@ -21,18 +23,36 @@ class Main extends EventEmitter { return Main.instance; } this.config = configUtil.read(); + this.db = db; // SQLite 通用存储 + + // 运行模式判定(Linux 强制录制模式,Windows 按配置) + this._runMode = getRunMode(this.config); + this._isRecording = isRecordingMode(this.config); + console.log('[Main] 运行模式: %s (platform=%s, config.mode=%s)', + this._runMode, process.platform, this.config.mode || 'full'); + + // 执行 init.sql 建表 + this._initDbSchema(); this.app = this; this.info = null; this.isBind = false; // 绑定状态 this.ctx = {}; this.services = {}; - this.printerComponents = new PrinterComponentCore(this); - this.printerComponents.initAll(); - // 初始化打印组件消息处理对象 - this.printerComponentMessageHandler = new PrinterComponentMessageHandler(this, this.printerComponents); - this.printerComponentMessageHandler.init(); - // 监听 WMI 打印机状态变化 + this._hikTasks = new Map(); // 海康下载任务进度全局 store + + // 打印机组件仅在非录制模式下初始化 + if (!this._isRecording) { + this.printerComponents = new PrinterComponentCore(this); + this.printerComponents.initAll(); + // 初始化打印组件消息处理对象 + this.printerComponentMessageHandler = new PrinterComponentMessageHandler(this, this.printerComponents); + this.printerComponentMessageHandler.init(); + } else { + this.printerComponents = null; + this.printerComponentMessageHandler = null; + } + //console.log(`ws服务器已启动,监听端口: ${this.config.wsPort}`); this.init().then(() => { //console.log('框架初始化完成'); @@ -40,18 +60,28 @@ class Main extends EventEmitter { this.wsClient = new WSClient(this.config.remoteWs.url, { reconnectInterval: this.config.remoteWs.reconnectInterval || 3000 }, this); - this.wsServer = new WSServer(this.config.wsPort, this); - console.log('[Main] 本地 WS 服务已启动,端口:', this.config.wsPort); - this._initWmiPrinterMonitor(); - this.app.on('printerWmiStatusChange', (data) => { - //console.log('打印机状态变化事件触发,数据:', data); - this.services.printer.getWindowsPrinters(); - }); + const wsPorts = extractPortCandidates(this.config, 'wsPorts', 'wsPort', [17301, 17302, 17303]); + this.wsServer = new WSServer(wsPorts, this); + console.log('[Main] 本地 WS 服务已启动(候选端口: %s)', wsPorts.join(', ')); + this.app.on('wsServerReady', () => this._flushRuntimeState()); + this._startHikScheduler(); + // 录制模式下跳过 WMI 打印机监控 + if (!this._isRecording) { + this._initWmiPrinterMonitor(); + this.app.on('printerWmiStatusChange', (data) => { + this.services.printer.getWindowsPrinters(); + }); + } }); - this.app.on("kuaishouMessage", (data) => { - console.log("收到快手打印组件消息,数据:", data); - }); + // 初始化 HTTP 服务器(用于海康 NVR 下载等 HTTP 出口) + this._initHttpServer(); + + if (!this._isRecording) { + this.app.on("kuaishouMessage", (data) => { + console.log("收到快手打印组件消息,数据:", data); + }); + } Main.instance = this; return this; } @@ -113,8 +143,1627 @@ class Main extends EventEmitter { await this._loadServices(); } + /** + * 初始化 HTTP 服务器,用于对外暴露 REST 接口(支持端口数组 fallback) + */ + _initHttpServer() { + const httpPorts = extractPortCandidates(this.config, 'httpPorts', 'httpPort', [17311, 17312, 17313]); + this._httpPort = null; + + const tryListen = (index) => { + if (index >= httpPorts.length) { + console.error('[Main] HTTP 所有端口均被占用:', httpPorts); + return; + } + const candidate = httpPorts[index]; + this.httpServer = http.createServer((req, res) => { + this._handleHttpRequest(req, res); + }); + + this.httpServer.on('error', (err) => { + if (err.code === 'EADDRINUSE') { + console.warn('[Main] HTTP 端口 %d 被占用,尝试下一个', candidate); + tryListen(index + 1); + return; + } + console.error('[Main] HTTP 端口 %d 启动失败:', candidate, err.message); + tryListen(index + 1); + }); + + this.httpServer.listen(candidate, () => { + this._httpPort = candidate; + console.log('[Main] HTTP 服务已启动,端口:', candidate); + this._flushRuntimeState(); + }); + }; + + tryListen(0); + } + + /** + * 将实际监听的端口写入 runtime.json,供 Electron 主进程读取 + */ + _flushRuntimeState() { + if (this._httpPort == null && (this.wsServer == null || this.wsServer.port == null)) { + return; // 两边都还没就绪 + } + // 尝试几次,等 WS server 也就绪 + if (this.wsServer == null || this.wsServer.port == null || this._httpPort == null) { + setTimeout(() => this._flushRuntimeState(), 200); + return; + } + writeRuntimeState({ + wsPort: this.wsServer.port, + httpPort: this._httpPort, + startedAt: new Date().toISOString() + }); + console.log('[Main] runtime.json 已写入,wsPort=%d, httpPort=%d', this.wsServer.port, this._httpPort); + } + + /** + * HTTP 请求路由处理 + */ + async _handleHttpRequest(req, res) { + // CORS 头 + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); + res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); + // 禁用 keep-alive,避免 HTTP 连接堆积 + res.setHeader('Connection', 'close'); + + if (req.method === 'OPTIONS') { + res.writeHead(204); + res.end(); + return; + } + + const url = new URL(req.url, `http://${req.headers.host}`); + const pathname = url.pathname; + + // 解析 JSON body + let body = null; + if (req.method === 'POST' && req.headers['content-type']?.includes('application/json')) { + body = await this._readRequestBody(req); + } + + try { + // 路由分发 + if (pathname === '/api/hikvision/download' && req.method === 'POST') { + await this._handleHikvisionDownload(res, body); + } else if (pathname === '/api/hikvision/channels' && req.method === 'POST') { + await this._handleHikvisionChannels(res, body); + } else if (pathname === '/api/hikvision/live-url' && req.method === 'POST') { + await this._handleHikvisionLiveUrl(res, body); + } else if (pathname === '/api/hikvision/live-stream' && req.method === 'GET') { + await this._handleHikvisionLiveStream(res, url.searchParams); + } else if (pathname === '/api/hikvision/file' && req.method === 'GET') { + this._handleHikvisionFileDownload(res, req); + } else if (pathname === '/api/hikvision/status' && req.method === 'GET') { + await this._handleHikvisionStatus(res, url.searchParams); + } else if (pathname === '/api/hikvision/files' && req.method === 'GET') { + this._handleHikvisionFiles(res, url.searchParams); + } else if (pathname === '/api/hikvision/config' && req.method === 'POST') { + await this._handleHikvisionConfig(res, body); + } else if (pathname === '/api/hikvision/config' && req.method === 'GET') { + this._sendJson(res, 200, { success: true, hikvision: this.config.hikvision || {} }); + } else if (pathname === '/api/hikvision/tasks' && req.method === 'GET') { + this._handleHikvisionTasks(res, url.searchParams); + } else if (pathname === '/api/hikvision/retry' && req.method === 'POST') { + await this._handleHikvisionRetry(res, body); + } else if (pathname.startsWith('/recordings/') && req.method === 'GET') { + this._handleRecordingsFile(res, req, pathname); + } else if (pathname === '/api/health' && req.method === 'GET') { + this._sendJson(res, 200, { success: true, message: 'OK', uptime: process.uptime() }); + } else if (req.method === 'GET' && !pathname.startsWith('/api/')) { + // 静态页面 fallback(开发调试用) + this._serveStaticFile(res, pathname); + } else { + this._sendJson(res, 404, { success: false, message: 'Not Found' }); + } + } catch (err) { + console.error('[Main] HTTP 请求处理异常:', err); + this._sendJson(res, 500, { success: false, message: err.message }); + } + } + + /** + * 读取 POST 请求 body + */ + _readRequestBody(req) { + return new Promise((resolve, reject) => { + const chunks = []; + req.on('data', (chunk) => chunks.push(chunk)); + req.on('end', () => { + try { + resolve(JSON.parse(Buffer.concat(chunks).toString('utf-8'))); + } catch (e) { + reject(new Error('JSON 解析失败')); + } + }); + req.on('error', reject); + }); + } + + /** + * 发送 JSON 响应 + */ + _sendJson(res, statusCode, data) { + res.writeHead(statusCode, { 'Content-Type': 'application/json; charset=utf-8' }); + res.end(JSON.stringify(data)); + } + + /** + * 静态文件服务(开发调试用) + */ + _serveStaticFile(res, pathname) { + if (pathname === '/') pathname = '/views/index.html'; + const filePath = path.join(getProjectRoot(), pathname.replace(/^\//, '')); + if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) { + this._sendJson(res, 404, { success: false, message: 'Not Found' }); + return; + } + const ext = path.extname(filePath).toLowerCase(); + const mime = { + '.html': 'text/html; charset=utf-8', + '.css': 'text/css', + '.js': 'application/javascript', + '.json': 'application/json', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon' + }[ext] || 'application/octet-stream'; + res.writeHead(200, { 'Content-Type': mime }); + res.end(fs.readFileSync(filePath)); + } + + /** + * 发送错误提示 JPEG 图片(用于 标签直连时显示错误信息) + */ + async _sendErrorImage(res, msg, ffmpegPath) { + let outBuf = Buffer.from( + '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBAUEBAYFBQUGBgYHCQ4JCQgICRINDgoOFREWG' + + 'BEXFBUWFhcbHR8lJx4eHiAhIyUoKSkrLC0tHyE3NTcoNSooKSv/2wBDAQcHBwkJCRYJCQ0XFh' + + 'UWFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxf/wAARCA' + + 'ABAAEDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACf/EABQQAQAAAAAAAAAAAAAAAA' + + 'AAAAD/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQ' + + 'ACEQMRAD8AKwA//9k=', + 'base64' + ); + try { + const { execSync } = await import('child_process'); + const safeMsg = msg.replace(/'/g, "'\\''"); + const buf = execSync( + `"${ffmpegPath}" -f lavfi -i "color=c=0x333333:s=640x360:d=0.1,drawtext=text='${safeMsg}':fontsize=22:fontcolor=0xff6666:x=(w-text_w)/2:y=(h-text_h)/2" -vframes 1 -f image2pipe -c:v mjpeg -q:v 3 pipe:1`, + { timeout: 5000, encoding: 'buffer', stdio: ['pipe', 'pipe', 'pipe'] } + ); + if (buf && buf.length > 2000) outBuf = buf; + } catch {} + res.writeHead(502, { 'Content-Type': 'image/jpeg', 'Content-Length': outBuf.length }); + res.end(outBuf); + } + + /** + * 海康威视 NVR 下载 HTTP 出口(任务池模式) + * POST /api/hikvision/download + */ + async _handleHikvisionDownload(res, body) { + if (!body || !body.ip || !body.user || !body.pass || !body.start || !body.end) { + this._sendJson(res, 400, { success: false, message: '缺少必要参数: ip, user, pass, start, end' }); + return; + } + const hikvisionService = this.services.hikvision; + if (!hikvisionService || typeof hikvisionService.startDownload !== 'function') { + this._sendJson(res, 503, { success: false, message: '海康服务未就绪' }); + return; + } + try { + const taskId = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + const prefix = body.outputPrefix || 'hik'; + + // 录制目录:baseDir/{YYYY}/{MM}/{DD}/ 按日期分子目录 + const hikCfg = this.config.hikvision || {}; + const baseDir = this._getRecordingBaseDir(); + const now = new Date(); + const dateDir = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(2, '0')}`; + const relOutput = body.output ? this._relativizePath(body.output) : `/${dateDir}/${prefix}_${taskId.slice(-12)}.mp4`; + const output = this._resolvePath(relOutput); // 绝对路径用于实际文件操作 + const videoTime = Math.ceil((new Date(body.end) - new Date(body.start)) / 1000); + + // 下载前:检查存储配额 + this.checkHikStorageQuota().catch(e => console.error('[Hikvision] 预下载配额检查失败:', e.message)); + + // 写入任务池(保存相对路径) + this.db.table('hik_tasks').insert({ + task_id: taskId, + task_params: JSON.stringify({ + ip: body.ip, port: body.port || 7681, httpPort: body.httpPort || 80, + user: body.user, pass: body.pass, + channel: body.channel || 33, start: body.start, end: body.end, + speed: body.speed || 4, output: relOutput, videoTime + }), + status: 'pending', + retry: 0, + timeout: videoTime + 60, + tmp_file_path: relOutput + }); + + // 有新任务 → 重置空闲计时,触发调度 + this._lastFetchTime = null; + this._scheduleHikTasks(); + + this._sendJson(res, 202, { success: true, taskId, message: '下载任务已创建', status: 'pending' }); + } catch (err) { + this._sendJson(res, 500, { success: false, message: err.message }); + } + } + + /** + * 海康任务状态查询 GET /api/hikvision/status?taskId=xxx + */ + _handleHikvisionStatus(res, params) { + const taskId = params.get('taskId'); + if (!taskId) { + this._sendJson(res, 400, { success: false, message: '缺少 taskId 参数' }); + return; + } + // 先查内存(正在下载的任务有 progress 信息) + const memTask = this._hikTasks.get(taskId); + if (memTask) { + if (memTask.status === 'done') { + const resultWithUrl = { ...memTask.result }; + if (memTask.result?.output) { + resultWithUrl.downloadUrl = this._filePathToRecordingsUrl(memTask.result.output); + } + this._sendJson(res, 200, { success: true, taskId, status: 'done', result: resultWithUrl }); + } else if (memTask.status === 'error') { + this._sendJson(res, 200, { success: false, taskId, status: 'error', message: memTask.error || '下载失败' }); + } else { + this._sendJson(res, 200, { success: true, taskId, status: memTask.status, progress: memTask.progress, params: memTask.params }); + } + return; + } + // 查 DB + const dbTask = this.db.get('SELECT * FROM hik_tasks WHERE task_id = ?', taskId); + if (!dbTask) { + this._sendJson(res, 404, { success: false, message: '任务不存在' }); + return; + } + const parsed = { ...dbTask, task_params: dbTask.task_params ? JSON.parse(dbTask.task_params) : {} }; + if (dbTask.status === 'completed') { + const result = dbTask.result ? JSON.parse(dbTask.result) : {}; + if (result.output) { + result.downloadUrl = this._filePathToRecordingsUrl(result.output); + } + this._sendJson(res, 200, { success: true, taskId, status: 'done', result }); + } else if (dbTask.status === 'failed' || dbTask.status === 'timeout') { + this._sendJson(res, 200, { success: false, taskId, status: dbTask.status, message: dbTask.error_message || '任务失败' }); + } else { + this._sendJson(res, 200, { success: true, taskId, status: dbTask.status }); + } + } + + /** + * 海康任务列表 GET /api/hikvision/tasks + */ + _handleHikvisionTasks(res, params) { + try { + const page = parseInt(params.get('page')) || 1; + const pageSize = Math.min(parseInt(params.get('pageSize')) || 20, 100); + const statusFilter = params.get('status') || ''; + const offset = (page - 1) * pageSize; + + let whereClause = ''; + const queryParams = []; + if (statusFilter) { + whereClause = 'WHERE status = ?'; + queryParams.push(statusFilter); + } + + const totalRow = this.db.get(`SELECT COUNT(*) as total FROM hik_tasks ${whereClause}`, ...queryParams); + const total = totalRow ? totalRow.total : 0; + + const rows = this.db.all( + `SELECT * FROM hik_tasks ${whereClause} ORDER BY id DESC LIMIT ? OFFSET ?`, + ...queryParams, pageSize, offset + ); + + this._sendJson(res, 200, { + success: true, + data: { + list: rows.map(r => { + const params = r.task_params ? JSON.parse(r.task_params) : {}; + const result = r.result ? JSON.parse(r.result) : null; + // 合并内存中的进度(正在下载的任务) + const mem = this._hikTasks.get(r.task_id); + return { + id: r.id, task_id: r.task_id, unique_code: r.unique_code || '', + status: mem ? mem.status : r.status, + ip: params.ip || '', channel: params.channel || 0, + speed: params.speed || 4, videoTime: params.videoTime || 0, + rec_start: params.start || '', rec_end: params.end || '', + output: params.output || '', retry: r.retry, + error_message: r.error_message, start_time: r.start_time, end_time: r.end_time, + created_at: r.created_at, + progress: mem ? mem.progress : null, + result + }; + }), + page, pageSize, total + } + }); + } catch (e) { + this._sendJson(res, 500, { success: false, message: e.message }); + } + } + + /** + * 重试任务 POST /api/hikvision/retry + * 支持 failed/timeout 重试,也支持 completed 任务重新录制 + */ + async _handleHikvisionRetry(res, body) { + const taskId = body && body.taskId; + if (!taskId) { + this._sendJson(res, 400, { success: false, message: '缺少 taskId' }); + return; + } + try { + const task = this.db.get('SELECT status FROM hik_tasks WHERE task_id = ?', taskId); + if (!task) { + this._sendJson(res, 404, { success: false, message: '任务不存在' }); + return; + } + if (task.status === 'completed' || task.status === 'done') { + // 重录已完成任务:先删除旧文件,再重置为 pending + console.log('[Retry] 重录已完成任务:', taskId, '原状态:', task.status); + const oldRow = this.db.get('SELECT tmp_file_path FROM hik_tasks WHERE task_id = ?', taskId); + if (oldRow && oldRow.tmp_file_path) { + try { + const fp = this._resolvePath(oldRow.tmp_file_path); + if (fp && fs.existsSync(fp)) { fs.unlinkSync(fp); console.log('[Retry] 已删除旧文件:', fp); } + } catch (e) { console.error('[Retry] 删除旧文件失败:', e.message); } + } + this.db.run( + `UPDATE hik_tasks SET status='pending', retry=0, error_message=NULL, result=NULL, + end_time=NULL, pushed=0, push_retry=0, push_next_retry_at='' WHERE task_id=?`, + taskId + ); + this._scheduleHikTasks(); + this._sendJson(res, 200, { success: true, message: '已重新加入录制队列' }); + } else if (task.status === 'failed' || task.status === 'timeout') { + console.log('[Retry] 重试失败任务:', taskId); + this.db.run( + `UPDATE hik_tasks SET status='pending', retry=retry+1, error_message=NULL WHERE task_id=?`, + taskId + ); + this._scheduleHikTasks(); + this._sendJson(res, 200, { success: true, message: '已重新加入队列' }); + } else { + this._sendJson(res, 400, { success: false, message: '当前状态不支持重试: ' + task.status }); + } + } catch (e) { + this._sendJson(res, 500, { success: false, message: e.message }); + } + } + + /** + * 任务调度器:超时释放 → 重试 → 启动新任务 + * 由定时器每 3 秒调用一次 + */ + _scheduleHikTasks() { + if (this._hikScheduling) return; + this._hikScheduling = true; + + try { + const hikvisionService = this.services.hikvision; + if (!hikvisionService) return; + const MAX_WORKERS = 2; + + // ① 超时释放(统一用 UTC 时间比较) + this.db.run(` + UPDATE hik_tasks SET status='timeout', worker_id=NULL, end_time=datetime('now') + WHERE status='running' AND (strftime('%s','now') - strftime('%s',start_time)) > (timeout + 30) + `); + + // ② 重试失败任务 + this.db.run(` + UPDATE hik_tasks SET status='pending', worker_id=NULL, retry=retry+1 + WHERE status IN ('failed','timeout') AND retry < 3 + AND (strftime('%s','now') - strftime('%s',COALESCE(end_time,created_at))) > 30 + `); + + // ③ 重试耗尽标记 + const exhausted = this.db.all(`SELECT * FROM hik_tasks WHERE status IN ('failed','timeout') AND retry >= 3 AND notice = 0`); + for (const row of exhausted) { + this.db.run(`UPDATE hik_tasks SET notice = 1 WHERE id = ?`, row.id); + try { const p = JSON.parse(row.task_params || '{}'); const fp = this._resolvePath(p.output); if (fp && fs.existsSync(fp)) fs.unlinkSync(fp); } catch {} + } + + // ④ while 循环填满 worker + let started = 0; + while (started < MAX_WORKERS) { + const running = this.db.all(`SELECT DISTINCT worker_id FROM hik_tasks WHERE status = 'running' AND worker_id IS NOT NULL`); + const used = running.map(r => r.worker_id); + let wid = null; + for (let i = 1; i <= MAX_WORKERS; i++) { if (!used.includes(i)) { wid = i; break; } } + if (wid === null) break; + + const pt = this.db.get(`SELECT * FROM hik_tasks WHERE status = 'pending' ORDER BY id ASC LIMIT 1`); + if (!pt) break; + + const tp = JSON.parse(pt.task_params || '{}'); + if (!tp.ip || !tp.start || !tp.end) { + this.db.run(`UPDATE hik_tasks SET status='failed', error_message='参数不完整' WHERE id = ?`, pt.id); + continue; + } + + // 将相对路径解析为绝对路径以供下载使用 + const downloadCfg = { ...tp, output: this._resolvePath(tp.output) }; + + this.db.run(`UPDATE hik_tasks SET status='running', worker_id=?, start_time=datetime('now') WHERE id=?`, wid, pt.id); + + const taskId = pt.task_id; + const self = this; + const task = { + startTime: Date.now(), + progress: { chunks: 0, totalBytes: 0, totalMB: 0, speed: tp.speed || 4 }, + params: tp, status: 'running', + _onDone: (result) => { + // 0 字节或标记失败 → 转为失败处理 + if (result.success === false || (result.size || 0) === 0) { + const errMsg = result.success === false ? '录制返回失败' : '录制文件大小为 0'; + task._onError(new Error(errMsg)); + return; + } + task.status = 'done'; task.result = result; + // 结果中的 output 是绝对路径,转为相对路径存储 + const relResult = { ...result, output: self._relativizePath(result.output || '') }; + self.db.run(`UPDATE hik_tasks SET status='completed', end_time=datetime('now'), error_message=NULL, result=? WHERE task_id=?`, JSON.stringify(relResult), taskId); + try { self.db.table('hik_downloads').insert({ task_id: taskId, ip: tp.ip || '', channel: tp.channel || 0, output_path: relResult.output || tp.output || '', file_size: result.size || 0, duration: result.duration || 0, resolution: result.resolution || '', status: 'done' }); } catch (e) {} + self.checkHikStorageQuota().catch(() => {}); + // Push 任务结果到远程服务器 + self._pushTaskResult(taskId, relResult); + setTimeout(() => self._hikTasks.delete(taskId), 5 * 60 * 1000); + self._scheduleHikTasks(); + }, + _onError: (err) => { + task.status = 'error'; task.error = err.message; + self.db.run(`UPDATE hik_tasks SET status='failed', end_time=datetime('now'), error_message=? WHERE task_id=?`, err.message, taskId); + try { const fp = self._resolvePath(tp.output); if (fp && fs.existsSync(fp)) fs.unlinkSync(fp); } catch {} + // Push 失败信息到远程服务器 + self._pushTaskFailed(taskId, err.message); + setTimeout(() => self._hikTasks.delete(taskId), 5 * 60 * 1000); + self._scheduleHikTasks(); + } + }; + this._hikTasks.set(taskId, task); + hikvisionService.startDownload(downloadCfg, taskId, task); + started++; + } + // 空闲拉取:有空闲 worker 且无 pending 任务,距上次拉取 >5分钟则触发 + if (started < MAX_WORKERS) { + const pending = this.db.get('SELECT COUNT(*) as c FROM hik_tasks WHERE status = ?', 'pending'); + if (!pending || pending.c === 0) { + const now = Date.now(); + if (!this._lastFetchTime || (now - this._lastFetchTime) > 5 * 60 * 1000) { + this._lastFetchTime = now; + this.services.hikvision?.fetchTasks(); + } + } + } + + // ⑤ 推送重试:已完成/失败但服务端未确认的任务,按退避间隔重试 + this._retryPendingPushes(); + } catch (e) { + console.error('[Hikvision] 调度异常:', e.message); + } finally { + this._hikScheduling = false; + } + } + + /** + * 启动任务调度定时器 + */ + _startHikScheduler() { + if (this._hikScheduleTimer) return; + this._hikScheduleTimer = setInterval(() => this._scheduleHikTasks(), 3000); + console.log('[Hikvision] 任务调度器已启动(每3秒),空闲拉取(间隔5分钟)'); + } + + /** + * 获取 NVR 通道列表 POST /api/hikvision/channels + * body: { ip, httpPort, user, pass } + */ + async _handleHikvisionChannels(res, body) { + if (!body || !body.ip || !body.user || !body.pass) { + this._sendJson(res, 400, { success: false, message: '缺少参数: ip, user, pass' }); + return; + } + const hikvisionService = this.services.hikvision; + if (!hikvisionService) { + this._sendJson(res, 503, { success: false, message: '海康服务未就绪' }); + return; + } + try { + const channels = await hikvisionService.getChannels(body.ip, body.httpPort || 80, body.user, body.pass); + this._sendJson(res, 200, { success: true, channels }); + } catch (err) { + console.error('[Main] getChannels 失败:', err.message); + this._sendJson(res, 500, { success: false, message: err.message }); + } + } + + /** + * 获取实时流 WebSocket URL POST /api/hikvision/live-url + * body: { ip, httpPort, user, pass, port, channel, streamType } + */ + async _handleHikvisionLiveUrl(res, body) { + if (!body || !body.ip || !body.user || !body.pass) { + this._sendJson(res, 400, { success: false, message: '缺少参数: ip, user, pass' }); + return; + } + const hikvisionService = this.services.hikvision; + if (!hikvisionService) { + this._sendJson(res, 503, { success: false, message: '海康服务未就绪' }); + return; + } + try { + const info = await hikvisionService.getLiveUrl(body.ip, body.httpPort || 80, body.user, body.pass, body.port || 7681, body.channel || 33, body.streamType || 1); + this._sendJson(res, 200, { success: true, ...info }); + } catch (err) { + this._sendJson(res, 500, { success: false, message: err.message }); + } + } + + /** + * MJPEG 实时流中转 GET /api/hikvision/live-stream + * query: ip, user, pass, channel, streamType, mode=rtsp|ws + * mode=rtsp(默认): ffmpeg 拉 RTSP → 转 MJPEG + * mode=ws: ISAPI WebSocket 实时预览(7681 端口,公网可用) + */ + async _handleHikvisionLiveStream(res, params) { + const ip = params.get('ip'); + const user = params.get('user'); + const pass = params.get('pass'); + const channel = parseInt(params.get('channel')) || 33; + const streamType = parseInt(params.get('streamType')) || 1; // 1=主码流, 2=子码流(海康标准) + const mode = params.get('mode') || 'auto'; // auto=RTSP优先→失败降级HTTP + const channelCode = 100 * channel + streamType; + + if (!ip || !user || !pass) { + this._sendJson(res, 400, { success: false, message: '缺少参数: ip, user, pass' }); + return; + } + + const hikvisionService = this.services.hikvision; + const ffmpegPath = hikvisionService?._findFfmpeg(); + + // WebSocket 模式:通过 ISAPI WebSocket 取流(7681 端口) + if (mode === 'ws') { + if (!ffmpegPath) { this._sendJson(res, 500, { success: false, message: 'ffmpeg 未找到' }); return; } + return this._handleHikvisionLiveStreamWs(res, { ip, user, pass, channel, streamType, channelCode, ffmpegPath, hikvisionService, params }); + } + + // HTTP 快照模式:纯 HTTP 轮询 ISAPI 快照(仅需 80 端口) + if (mode === 'http') { + return this._handleHikvisionLiveStreamHttp(res, { ip, user, pass, channel, streamType, channelCode, hikvisionService, params }); + } + + // rtsp 模式:强制 RTSP + if (mode === 'rtsp') { + if (!ffmpegPath) { this._sendJson(res, 500, { success: false, message: 'ffmpeg 未找到' }); return; } + } + + // auto 模式或无 ffmpeg → 先尝试 RTSP(如果有 ffmpeg),不行降级 HTTP + const useAutoFallback = mode === 'auto' || !ffmpegPath; + if (!ffmpegPath && mode === 'auto') { + return this._handleHikvisionLiveStreamHttp(res, { ip, user, pass, channel, streamType, channelCode, hikvisionService, params }); + } + + // RTSP 模式(默认) + const rtspPort = parseInt(params.get('rtspPort')) || 554; + const rtspUrl = `rtsp://${encodeURIComponent(user)}:${encodeURIComponent(pass)}@${ip}:${rtspPort}/Streaming/Channels/${channelCode}`; + console.log('[Hikvision] live-stream RTSP channel=%d code=%d url=%s', channel, channelCode, + rtspUrl.replace(/:[^:@]+@/, ':****@')); + + let ffmpeg = null; + let closed = false; + let lastDataTime = Date.now(); + let idleCheck = null; + + const doCleanup = () => { + if (closed) return; + closed = true; + if (idleCheck) clearInterval(idleCheck); + try { ffmpeg?.kill('SIGKILL'); } catch {} + if (!res.writableEnded) try { res.end(); } catch {} + }; + + // RTSP 失败时降级到 HTTP 快照模式 + const fallbackToHttp = () => { + if (closed) return; + closed = true; + res.removeAllListeners('close'); + res.removeAllListeners('error'); + if (idleCheck) clearInterval(idleCheck); + try { ffmpeg?.kill('SIGKILL'); } catch {} + console.log('[Hikvision] RTSP 失败,降级到 HTTP 快照模式'); + this._handleHikvisionLiveStreamHttp(res, { ip, user, pass, channel, streamType, channelCode, hikvisionService, params }); + }; + + res.on('close', doCleanup); + res.on('error', doCleanup); + + // 空闲超时:30s 无数据 → 断开 + idleCheck = setInterval(() => { + if (!closed && Date.now() - lastDataTime > 30000) { + console.error('[Hikvision] live-stream 超时无数据, 断开'); + doCleanup(); + } + }, 5000); + + try { + const { spawn } = await import('child_process'); + + // 先不发送响应头——等首帧到或 ffmpeg 失败后再决定 + // 如果连不上 RTSP,ffmpeg 会快速退出,此时可返回 JSON 错误 + + ffmpeg = spawn(ffmpegPath, [ + '-rtsp_transport', 'tcp', + '-timeout', '3000000', // RTSP 连接超时 3s(微秒) + '-i', rtspUrl, + '-f', 'mjpeg', + '-q:v', '5', + '-an', + '-nostdin', + 'pipe:1' + ], { stdio: ['pipe', 'pipe', 'pipe'] }); + + let ffmpegStderr = ''; + ffmpeg.stderr.on('data', (d) => { + ffmpegStderr += d.toString(); + // 截断防止内存泄漏 + if (ffmpegStderr.length > 4096) ffmpegStderr = ffmpegStderr.slice(-2048); + }); + + ffmpeg.on('error', (err) => { + console.error('[Hikvision] live-stream ffmpeg 异常:', err.message); + if (!headersSent && !closed) { + if (useAutoFallback) return fallbackToHttp(); + this._sendJson(res, 500, { success: false, message: 'ffmpeg 启动失败: ' + err.message }); + } + doCleanup(); + }); + + // 关键:ffmpeg 退出时的处理 + let headersSent = false; + let startTime = Date.now(); + ffmpeg.on('exit', (code) => { + clearTimeout(startupTimer); + (async () => { + if (!headersSent && !closed) { + if (useAutoFallback) return fallbackToHttp(); + const isDomain = !/^(\d+\.){3}\d+$/.test(ip); + const wsHint = isDomain ? ' 公网请加 &mode=ws' : ''; + const errMsg = code === 0 ? 'RTSP 流无数据' : + ffmpegStderr.includes('Connection refused') ? '无法连接 NVR' + wsHint : + ffmpegStderr.includes('401') || ffmpegStderr.includes('Unauthorized') ? 'RTSP 认证失败' : + ffmpegStderr.includes('timeout') || ffmpegStderr.includes('Timed out') ? 'RTSP 连接超时' + wsHint : + 'RTSP 取流失败' + wsHint; + console.error('[Hikvision] live-stream 启动失败:', errMsg); + await this._sendErrorImage(res, errMsg + ' (ch=' + channelCode + ')', ffmpegPath); + } + doCleanup(); + })(); + }); + + // 启动超时:3s 内没收到首帧 → 降级(不可达瞬间退出,不会等) + const startupTimer = setTimeout(() => { + (async () => { + if (!headersSent && !closed) { + if (useAutoFallback) return fallbackToHttp(); + console.error('[Hikvision] live-stream 启动超时'); + await this._sendErrorImage(res, 'RTSP 取流超时 (ch=' + channelCode + ')', ffmpegPath); + } + doCleanup(); + })(); + }, 5000); + + let firstFrameWritten = false; + let jpegBuf = Buffer.alloc(0); + ffmpeg.stdout.on('data', (chunk) => { + if (closed || res.destroyed) return; + lastDataTime = Date.now(); + jpegBuf = Buffer.concat([jpegBuf, chunk]); + + // 按 JPEG SOI (FFD8) / EOI (FFD9) 切分完整帧 + while (!closed && jpegBuf.length > 2) { + const soi = jpegBuf.indexOf(Buffer.from([0xFF, 0xD8])); + if (soi === -1) { jpegBuf = Buffer.alloc(0); break; } + if (soi > 0) jpegBuf = jpegBuf.slice(soi); + + const eoi = jpegBuf.indexOf(Buffer.from([0xFF, 0xD9]), 2); + if (eoi === -1) break; + + const frame = jpegBuf.slice(0, eoi + 2); + jpegBuf = jpegBuf.slice(eoi + 2); + + if (frame.length < 1000) continue; + + if (!firstFrameWritten) { + firstFrameWritten = true; + clearTimeout(startupTimer); + // 首帧到达,发送 MJPEG 响应头 + res.writeHead(200, { + 'Content-Type': 'multipart/x-mixed-replace; boundary=ffmpeg', + 'Cache-Control': 'no-cache, no-store, must-revalidate', + 'Pragma': 'no-cache', + 'Expires': '0', + 'Connection': 'keep-alive', + 'Access-Control-Allow-Origin': '*' + }); + headersSent = true; + console.log('[Hikvision] live-stream 首帧: %d bytes, 耗时 %dms', frame.length, Date.now() - startTime); + } + + if (!res.destroyed) { + res.write(`--ffmpeg\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`); + res.write(frame); + res.write('\r\n'); + } + } + }); + + } catch (err) { + console.error('[Main] live-stream 启动失败:', err.message); + if (!res.headersSent) { + this._sendJson(res, 500, { success: false, message: err.message }); + } + doCleanup(); + } + } + + /** + * WebSocket 模式实时预览(公网可用,走 7681 端口) + * 通过 ISAPI WebSocket 取流 → ffmpeg 转 MJPEG + */ + async _handleHikvisionLiveStreamWs(res, { ip, user, pass, channel, streamType, channelCode, ffmpegPath, hikvisionService, params }) { + const wsPort = parseInt(params.get('wsPort')) || 7681; + const httpPort = parseInt(params.get('httpPort')) || parseInt(params.get('port')) || 80; + + let ffmpeg = null; + let liveView = null; + let closed = false; + let lastDataTime = Date.now(); + let idleCheck = null; + + const doCleanup = () => { + if (closed) return; + closed = true; + if (idleCheck) clearInterval(idleCheck); + try { ffmpeg?.kill('SIGKILL'); } catch {} + try { liveView?.close(); } catch {} + if (!res.writableEnded) try { res.end(); } catch {} + }; + + res.on('close', doCleanup); + res.on('error', doCleanup); + + idleCheck = setInterval(() => { + if (!closed && Date.now() - lastDataTime > 30000) { + console.error('[Hikvision] live-stream WS 超时无数据, 断开'); + doCleanup(); + } + }, 5000); + + try { + // Step 1: ISAPI 登录获取 token + const { token } = await hikvisionService.login(ip, httpPort, user, pass); + console.log('[Hikvision] live-stream WS 登录成功, 开始取流 ch=%d', channel); + + const { spawn } = await import('child_process'); + + // Step 2: 启动 ffmpeg(从 stdin 读取 PS 流 → MJPEG 输出) + ffmpeg = spawn(ffmpegPath, [ + '-f', 'mpegts', + '-i', 'pipe:0', + '-f', 'mjpeg', + '-q:v', '5', + '-an', + '-nostdin', + 'pipe:1' + ], { stdio: ['pipe', 'pipe', 'pipe'] }); + + let ffmpegStderr = ''; + ffmpeg.stderr.on('data', (d) => { + ffmpegStderr += d.toString(); + if (ffmpegStderr.length > 4096) ffmpegStderr = ffmpegStderr.slice(-2048); + }); + + let headersSent = false; + let startTime = Date.now(); + + ffmpeg.on('error', (err) => { + console.error('[Hikvision] live-stream WS ffmpeg 异常:', err.message); + if (!headersSent && !closed) { + this._sendJson(res, 500, { success: false, message: 'ffmpeg 启动失败: ' + err.message }); + } + doCleanup(); + }); + + ffmpeg.on('exit', (code) => { + clearTimeout(startupTimer); + (async () => { + if (!headersSent && !closed) { + const errMsg = ffmpegStderr.includes('Connection refused') ? '无法连接' : + ffmpegStderr.includes('401') || ffmpegStderr.includes('Unauthorized') ? '认证失败' : + 'WS 取流失败'; + console.error('[Hikvision] live-stream WS 启动失败:', errMsg); + await this._sendErrorImage(res, errMsg + ' (ch=' + channelCode + ')', ffmpegPath); + } + doCleanup(); + })(); + }); + + const startupTimer = setTimeout(() => { + (async () => { + if (!headersSent && !closed) { + console.error('[Hikvision] live-stream WS 启动超时'); + await this._sendErrorImage(res, 'WS 取流超时 (ch=' + channelCode + ')', ffmpegPath); + } + doCleanup(); + })(); + }, 20000); + + // Step 3: 打开 WebSocket 实时预览 + liveView = await hikvisionService._wsLiveView({ + ip, port: wsPort, channel, streamType, token, + onData: (data) => { + if (closed || ffmpeg?.stdin?.destroyed) return; + lastDataTime = Date.now(); + try { ffmpeg.stdin.write(data); } catch {} + }, + onError: (err) => { + console.error('[Hikvision] live-stream WS 错误:', err.message); + if (!headersSent && !closed) { + this._sendJson(res, 500, { success: false, message: 'WS 连接失败: ' + err.message }); + } + doCleanup(); + } + }); + + // Step 4: ffmpeg stdout → MJPEG HTTP 响应 + let firstFrameWritten = false; + let jpegBuf = Buffer.alloc(0); + ffmpeg.stdout.on('data', (chunk) => { + if (closed || res.destroyed) return; + lastDataTime = Date.now(); + jpegBuf = Buffer.concat([jpegBuf, chunk]); + + while (!closed && jpegBuf.length > 2) { + const soi = jpegBuf.indexOf(Buffer.from([0xFF, 0xD8])); + if (soi === -1) { jpegBuf = Buffer.alloc(0); break; } + if (soi > 0) jpegBuf = jpegBuf.slice(soi); + + const eoi = jpegBuf.indexOf(Buffer.from([0xFF, 0xD9]), 2); + if (eoi === -1) break; + + const frame = jpegBuf.slice(0, eoi + 2); + jpegBuf = jpegBuf.slice(eoi + 2); + + if (frame.length < 1000) continue; + + if (!firstFrameWritten) { + firstFrameWritten = true; + clearTimeout(startupTimer); + res.writeHead(200, { + 'Content-Type': 'multipart/x-mixed-replace; boundary=ffmpeg', + 'Cache-Control': 'no-cache, no-store, must-revalidate', + 'Pragma': 'no-cache', + 'Expires': '0', + 'Connection': 'keep-alive', + 'Access-Control-Allow-Origin': '*' + }); + headersSent = true; + console.log('[Hikvision] live-stream WS 首帧: %d bytes, 耗时 %dms', frame.length, Date.now() - startTime); + } + + if (!res.destroyed) { + res.write(`--ffmpeg\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`); + res.write(frame); + res.write('\r\n'); + } + } + }); + + } catch (err) { + console.error('[Main] live-stream WS 启动失败:', err.message); + if (!res.headersSent) { + this._sendJson(res, 500, { success: false, message: err.message }); + } + doCleanup(); + } + } + + /** + * HTTP 快照模式实时预览(公网通用,仅需 80 端口,无需 ffmpeg) + * 通过 ISAPI HTTP 轮询 /ISAPI/Streaming/channels/{code}/picture → MJPEG + */ + async _handleHikvisionLiveStreamHttp(res, { ip, user, pass, channel, streamType, channelCode, hikvisionService, params }) { + const httpPort = parseInt(params.get('httpPort')) || parseInt(params.get('port')) || 80; + const interval = Math.max(100, parseInt(params.get('interval')) || 250); // 轮询间隔 ms + + let closed = false; + let frameCount = 0; + const startTime = Date.now(); + let cookieJar = {}; + let sessionTag = ''; + + const doCleanup = () => { + if (closed) return; + closed = true; + if (!res.writableEnded) try { res.end(); } catch {} + }; + + res.on('close', doCleanup); + res.on('error', doCleanup); + + try { + // Step 1: 登录 + const loginResult = await hikvisionService.login(ip, httpPort, user, pass); + cookieJar = loginResult.cookieJar; + sessionTag = loginResult.sessionTag; + console.log('[Hikvision] live-stream HTTP 登录成功 ch=%d, 开始轮询', channel); + + // Step 2: 发送 MJPEG 响应头 + res.writeHead(200, { + 'Content-Type': 'multipart/x-mixed-replace; boundary=snapshot', + 'Cache-Control': 'no-cache, no-store, must-revalidate', + 'Pragma': 'no-cache', + 'Expires': '0', + 'Connection': 'keep-alive', + 'Access-Control-Allow-Origin': '*' + }); + + const snapshotUrl = `http://${ip}:${httpPort}/ISAPI/Streaming/channels/${channelCode}/picture`; + const headers = sessionTag ? { 'SessionTag': sessionTag } : {}; + + // Step 3: 轮询循环 + while (!closed) { + const loopStart = Date.now(); + try { + const result = await hikvisionService._req('GET', snapshotUrl, null, headers, cookieJar, true); + if (result.statusCode === 200 && result.body && result.body.length > 500) { + const jpeg = result.body; // Buffer (binary=true) + if (!res.destroyed) { + res.write(`--snapshot\r\nContent-Type: image/jpeg\r\nContent-Length: ${jpeg.length}\r\n\r\n`); + res.write(jpeg); + res.write('\r\n'); + frameCount++; + } + } else if (result.statusCode === 401) { + // Session 过期,重新登录 + console.log('[Hikvision] live-stream HTTP session 过期,重新登录'); + const relogin = await hikvisionService.login(ip, httpPort, user, pass); + cookieJar = relogin.cookieJar; + sessionTag = relogin.sessionTag; + headers['SessionTag'] = sessionTag || ''; + } + } catch (e) { + // 单次快照失败不中断,继续轮询 + } + + // 控制轮询频率 + const elapsed = Date.now() - loopStart; + const delay = Math.max(0, interval - elapsed); + if (delay > 0) await new Promise(r => setTimeout(r, delay)); + } + } catch (err) { + console.error('[Main] live-stream HTTP 启动失败:', err.message); + if (!res.headersSent) { + await this._sendErrorImage(res, err.message, hikvisionService?._findFfmpeg()); + } + doCleanup(); + } + } + + /** + * 查询海康下载任务状态/进度(只读全局 store,不阻塞) + * GET /api/hikvision/status?taskId=xxx + */ + _handleHikvisionStatus(res, params) { + const taskId = params.get('taskId'); + if (!taskId) { + this._sendJson(res, 400, { success: false, message: '缺少 taskId 参数' }); + return; + } + const task = this._hikTasks.get(taskId); + if (!task) { + this._sendJson(res, 404, { success: false, message: '任务不存在或已过期' }); + return; + } + + if (task.status === 'done') { + const resultWithUrl = { ...task.result }; + if (task.result?.output) { + resultWithUrl.downloadUrl = `http://127.0.0.1:${this._httpPort || 17311}/api/hikvision/file?path=${encodeURIComponent(task.result.output)}`; + resultWithUrl.expiresAt = task.expiresAt; + } + this._sendJson(res, 200, { success: true, taskId, status: 'done', message: '下载完成', result: resultWithUrl }); + } else if (task.status === 'error') { + this._sendJson(res, 200, { success: false, taskId, status: 'error', message: task.error || '下载失败' }); + } else { + this._sendJson(res, 200, { success: true, taskId, status: task.status, message: task.status === 'starting' ? '正在准备下载...' : '下载中...', progress: task.progress, params: task.params }); + } + } + + /** + * 海康文件列表 GET /api/hikvision/files?page=1&pageSize=20&search= + */ + _handleHikvisionFiles(res, params) { + try { + const page = parseInt(params.get('page')) || 1; + const pageSize = Math.min(parseInt(params.get('pageSize')) || 20, 100); + const search = (params.get('search') || '').trim(); + const offset = (page - 1) * pageSize; + + let whereClause = ''; + const queryParams = []; + if (search) { + whereClause = 'WHERE (ip LIKE ? OR output_path LIKE ?)'; + queryParams.push('%' + search + '%', '%' + search + '%'); + } + + const countResult = this.db.get( + `SELECT COUNT(*) as total FROM hik_downloads ${whereClause}`, + ...queryParams + ); + const total = countResult ? countResult.total : 0; + + const rows = this.db.all( + `SELECT * FROM hik_downloads ${whereClause} ORDER BY id DESC LIMIT ? OFFSET ?`, + ...queryParams, pageSize, offset + ); + + const storageResult = this.db.get( + 'SELECT COALESCE(SUM(file_size), 0) as used, COUNT(*) as fileCount FROM hik_downloads WHERE deleted = 0' + ); + const usedBytes = storageResult ? storageResult.used : 0; + const fileCount = storageResult ? storageResult.fileCount : 0; + + const hikCfg = this.config.hikvision || {}; + const maxStorage = this._parseSizeToBytes(hikCfg.maxStorage || '50GB'); + + this._sendJson(res, 200, { + success: true, + data: { + list: rows.map(r => ({ + ...r, + downloadUrl: r.output_path ? this._filePathToRecordingsUrl(r.output_path) : null + })), + page, pageSize, total, + storage: { used: usedBytes, max: maxStorage, fileCount, percent: maxStorage > 0 ? Math.round(usedBytes / maxStorage * 100) : 0 } + } + }); + } catch (e) { + this._sendJson(res, 500, { success: false, message: e.message }); + } + } + + /** + * 保存海康配置 POST /api/hikvision/config + */ + async _handleHikvisionConfig(res, body) { + if (!body) { + this._sendJson(res, 400, { success: false, message: '缺少配置参数' }); + return; + } + try { + console.log('[Hikvision] 保存配置:', JSON.stringify(body)); + const currentConfig = configUtil.read(); + currentConfig.hikvision = { ...(currentConfig.hikvision || {}), ...body }; + const ok = configUtil.write(currentConfig); + this.config = currentConfig; + console.log('[Hikvision] 配置已写入文件:', ok); + this._sendJson(res, 200, { success: true, message: '配置已保存', hikvision: currentConfig.hikvision }); + } catch (e) { + console.error('[Hikvision] 配置保存失败:', e.message); + this._sendJson(res, 500, { success: false, message: e.message }); + } + } + + /** + * 获取录制根目录(基于配置的 downloadDir) + * "D" → "D:/hikvision_recordings", "/mnt/data" → "/mnt/data" + */ + _getRecordingBaseDir() { + const hikCfg = this.config.hikvision || {}; + let baseDir = (hikCfg.downloadDir || '').replace(/[\\\/]+$/, ''); + if (!baseDir) baseDir = 'G:/gameauto/recordings'; + else if (/^[A-Za-z]$/.test(baseDir)) { + baseDir = baseDir + ':/hikvision_recordings'; + } + return baseDir; + } + + /** + * 将存储路径转为 /recordings/ 相对 URL + * 支持绝对路径和相对路径两种格式 + */ + _filePathToRecordingsUrl(filePath) { + if (!filePath) return null; + // 如果是相对路径(以 / 开头),直接拼接 + if (filePath.startsWith('/')) { + return '/recordings' + filePath; + } + // 绝对路径:尝试匹配录制根目录 + const baseDir = this._getRecordingBaseDir().replace(/\\/g, '/'); + const normalized = filePath.replace(/\\/g, '/'); + if (normalized.startsWith(baseDir + '/')) { + return '/recordings' + normalized.slice(baseDir.length); + } + // 兜底:使用文件名 + return '/recordings/' + encodeURIComponent(path.basename(filePath)); + } + + /** + * 将存储路径(相对或绝对)解析为文件系统绝对路径 + */ + _resolvePath(storedPath) { + if (!storedPath) return ''; + // 相对路径:以 / 或 \ 开头,拼接录制根目录 + const cleaned = storedPath.replace(/\\/g, '/').replace(/^\/+/, ''); + if (storedPath.startsWith('/') || storedPath.startsWith('\\')) { + const base = this._getRecordingBaseDir(); + return path.join(base, cleaned); + } + // 已经是绝对路径(如 G:/...)—— 兼容旧数据 + return storedPath; + } + + /** + * 将文件系统绝对路径转为存储用的相对路径 + * D:/hikvision_recordings/2026/07/26/xxx.mp4 → /2026/07/26/xxx.mp4 + */ + _relativizePath(absPath) { + if (!absPath) return ''; + const baseDir = this._getRecordingBaseDir().replace(/\\/g, '/'); + const normalized = absPath.replace(/\\/g, '/'); + if (normalized.startsWith(baseDir + '/')) { + return normalized.slice(baseDir.length); // "/2026/07/26/xxx.mp4" + } + // 不在录制目录下,保留原路径(兼容旧数据) + return absPath; + } + + /** + * 静态文件服务:GET /recordings/2026/07/26/xxx.mp4 + * 映射到录制根目录下的相对路径,禁止目录穿越 + */ + _handleRecordingsFile(res, req, pathname) { + try { + const baseDir = this._getRecordingBaseDir(); + const relativePath = decodeURIComponent(pathname.slice('/recordings'.length)).replace(/\\/g, '/'); + const safePath = relativePath.replace(/^\/+/, '').split('/').filter(s => s && s !== '..').join('/'); + const filePath = path.join(baseDir, safePath); + + if (!filePath.replace(/\\/g, '/').startsWith(baseDir.replace(/\\/g, '/'))) { + this._sendJson(res, 403, { success: false, message: '禁止访问' }); + return; + } + + if (!fs.existsSync(filePath)) { + this._sendJson(res, 404, { success: false, message: '文件不存在' }); + return; + } + + const stat = fs.statSync(filePath); + if (!stat.isFile()) { + this._sendJson(res, 404, { success: false, message: '不是文件' }); + return; + } + + const ext = path.extname(filePath).toLowerCase(); + const mimeTypes = { '.mp4': 'video/mp4', '.ps': 'application/octet-stream', '.mkv': 'video/x-matroska' }; + const contentType = mimeTypes[ext] || 'application/octet-stream'; + const fileSize = stat.size; + const rangeHeader = req.headers.range; + + if (rangeHeader) { + const parts = rangeHeader.replace(/bytes=/, '').split('-'); + const start = parseInt(parts[0], 10); + const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1; + const chunkSize = (end - start) + 1; + res.writeHead(206, { + 'Content-Range': `bytes ${start}-${end}/${fileSize}`, + 'Accept-Ranges': 'bytes', + 'Content-Length': chunkSize, + 'Content-Type': contentType, + 'Cache-Control': 'public, max-age=3600' + }); + const stream = fs.createReadStream(filePath, { start, end }); + stream.pipe(res); + stream.on('error', () => { try { res.end(); } catch { /* */ } }); + } else { + const fileName = encodeURIComponent(path.basename(filePath)); + res.writeHead(200, { + 'Content-Type': contentType, + 'Content-Length': fileSize, + 'Accept-Ranges': 'bytes', + 'Content-Disposition': `inline; filename*=UTF-8''${fileName}`, + 'Cache-Control': 'public, max-age=3600' + }); + const stream = fs.createReadStream(filePath); + stream.pipe(res); + stream.on('error', () => { try { res.end(); } catch { /* */ } }); + } + } catch (e) { + this._sendJson(res, 500, { success: false, message: e.message }); + } + } + + /** + * 文件下载/播放端点 GET /api/hikvision/file?id=xxx 或 ?path=xxx + * 支持 HTTP Range 请求,实现视频拖动进度条 + */ + _handleHikvisionFileDownload(res, req) { + const url = new URL(req.url, `http://${req.headers.host}`); + let filePath = url.searchParams.get('path'); + const fileId = url.searchParams.get('id'); + + // 优先通过 ID 查找(不暴露文件系统路径) + if (!filePath && fileId) { + try { + const row = this.db.get('SELECT output_path FROM hik_downloads WHERE id = ?', parseInt(fileId)); + if (row) filePath = this._resolvePath(row.output_path); + } catch (_) { /* fall through */ } + } + + // 解析相对路径或绝对路径 + if (filePath) filePath = this._resolvePath(filePath); + + if (!filePath) { + this._sendJson(res, 400, { success: false, message: '缺少 path 或 id 参数' }); + return; + } + try { + if (!fs.existsSync(filePath)) { + this._sendJson(res, 404, { success: false, message: '文件不存在' }); + return; + } + const stat = fs.statSync(filePath); + const fileSize = stat.size; + const ext = path.extname(filePath).toLowerCase(); + const mimeTypes = { '.mp4': 'video/mp4', '.ps': 'application/octet-stream', '.mkv': 'video/x-matroska' }; + const contentType = mimeTypes[ext] || 'application/octet-stream'; + const rangeHeader = req.headers.range; + + if (rangeHeader) { + // 解析 Range: bytes=start-end + const parts = rangeHeader.replace(/bytes=/, '').split('-'); + const start = parseInt(parts[0], 10); + const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1; + const chunkSize = (end - start) + 1; + + res.writeHead(206, { + 'Content-Range': `bytes ${start}-${end}/${fileSize}`, + 'Accept-Ranges': 'bytes', + 'Content-Length': chunkSize, + 'Content-Type': contentType, + 'Cache-Control': 'no-cache' + }); + const stream = fs.createReadStream(filePath, { start, end }); + stream.pipe(res); + stream.on('error', () => { try { res.end(); } catch { /* */ } }); + } else { + // 完整文件(下载模式) + const fileName = encodeURIComponent(path.basename(filePath)); + res.writeHead(200, { + 'Content-Type': contentType, + 'Content-Length': fileSize, + 'Accept-Ranges': 'bytes', + 'Content-Disposition': `attachment; filename*=UTF-8''${fileName}`, + 'Cache-Control': 'no-cache' + }); + const stream = fs.createReadStream(filePath); + stream.pipe(res); + stream.on('error', () => { try { res.end(); } catch { /* */ } }); + } + } catch (e) { + this._sendJson(res, 500, { success: false, message: e.message }); + } + } + + /** + * 启动时执行 db/init.sql 建表 + */ + _initDbSchema() { + try { + // 迁移旧数据库:补全新字段(init.sql 中 CREATE TABLE 已包含,此处仅处理已存在的旧表) + try { this.db.exec('ALTER TABLE hik_tasks ADD COLUMN pushed INTEGER DEFAULT 0'); } catch (_) {} + try { this.db.exec('ALTER TABLE hik_tasks ADD COLUMN unique_code TEXT DEFAULT \'\''); } catch (_) {} + try { this.db.exec('ALTER TABLE hik_tasks ADD COLUMN push_retry INTEGER DEFAULT 0'); } catch (_) {} + try { this.db.exec('ALTER TABLE hik_tasks ADD COLUMN push_next_retry_at TEXT DEFAULT \'\''); } catch (_) {} + + // 优先读取 db/init.sql + const candidates = [ + path.join(getResourcePath('config.json'), '..', '..', 'db', 'init.sql'), + path.join(process.cwd(), 'db', 'init.sql'), + ]; + let sqlPath = null; + for (const c of candidates) { + if (fs.existsSync(c)) { sqlPath = c; break; } + } + if (!sqlPath) { + const resPath = getResourcePath('init.sql'); + if (fs.existsSync(resPath)) sqlPath = resPath; + } + if (sqlPath && fs.existsSync(sqlPath)) { + const sql = fs.readFileSync(sqlPath, 'utf-8'); + this.db.exec(sql); + console.log('[Main] init.sql 已执行:', sqlPath); + } else { + // fallback: 直接执行内联 DDL + this.db.exec(` + CREATE TABLE IF NOT EXISTS hik_downloads ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + task_id TEXT NOT NULL UNIQUE, + ip TEXT DEFAULT '', + channel INTEGER DEFAULT 0, + output_path TEXT NOT NULL, + file_size INTEGER DEFAULT 0, + duration REAL DEFAULT 0, + resolution TEXT DEFAULT '', + status TEXT DEFAULT 'done', + deleted INTEGER DEFAULT 0, + created_at TEXT DEFAULT (datetime('now')) + ); + CREATE INDEX IF NOT EXISTS idx_hik_downloads_deleted ON hik_downloads(deleted); + CREATE INDEX IF NOT EXISTS idx_hik_downloads_status ON hik_downloads(status); + + CREATE TABLE IF NOT EXISTS hik_tasks ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + task_id TEXT NOT NULL UNIQUE, + unique_code TEXT DEFAULT '', + task_params TEXT, + status TEXT DEFAULT 'pending', + worker_id INTEGER, + retry INTEGER DEFAULT 0, + notice INTEGER DEFAULT 0, + timeout INTEGER DEFAULT 0, + error_message TEXT, + result TEXT, + tmp_file_path TEXT DEFAULT '', + pushed INTEGER DEFAULT 0, + start_time TEXT, + end_time TEXT, + created_at TEXT DEFAULT (datetime('now')) + ); + CREATE INDEX IF NOT EXISTS idx_hik_tasks_status ON hik_tasks(status); + CREATE INDEX IF NOT EXISTS idx_hik_tasks_worker ON hik_tasks(worker_id); + CREATE INDEX IF NOT EXISTS idx_hik_tasks_unique_code ON hik_tasks(unique_code); + `); + console.log('[Main] init.sql 未找到,已执行内联 DDL'); + } + } catch (e) { + console.error('[Main] init.sql 执行失败:', e.message); + } + } + + /** + * 海康下载存储配额检查(循环清理) + * DB 驱动:累计文件大小超配额时,标记删除最旧记录 + 清理文件 + */ + async checkHikStorageQuota() { + const hikCfg = this.config.hikvision || {}; + if (!hikCfg.circularRecording) return; + + const maxStorage = this._parseSizeToBytes(hikCfg.maxStorage || '50GB'); + let deletedCount = 0; + + while (true) { + const result = this.db.get( + 'SELECT COALESCE(SUM(file_size), 0) as total FROM hik_downloads WHERE deleted = 0' + ); + const usedBytes = result ? result.total : 0; + if (usedBytes < maxStorage) break; + + if (deletedCount === 0) { + console.log('[Hikvision] 存储配额超限: %s / %s,开始清理...', + this._formatBytes(usedBytes), this._formatBytes(maxStorage)); + } + + const oldest = this.db.get( + 'SELECT id, output_path FROM hik_downloads WHERE deleted = 0 ORDER BY id ASC LIMIT 1' + ); + if (!oldest) break; + + // 删除磁盘文件 + const filePath = this._resolvePath(oldest.output_path); + if (filePath && fs.existsSync(filePath)) { + try { fs.unlinkSync(filePath); } catch (e) { /* */ } + } + // 标记 DB 记录为已删除 + this.db.run('UPDATE hik_downloads SET deleted = 1 WHERE id = ?', oldest.id); + deletedCount++; + } + + if (deletedCount > 0) { + console.log('[Hikvision] 循环清理完成: %d 个文件', deletedCount); + } + } + + _parseSizeToBytes(sizeStr) { + const match = String(sizeStr).match(/^([\d.]+)\s*(TB|GB|MB|KB)$/i); + if (!match) return 50 * 1024 * 1024 * 1024; // 默认 50GB + const num = parseFloat(match[1]); + const multipliers = { TB: 1024**4, GB: 1024**3, MB: 1024**2, KB: 1024 }; + return Math.round(num * (multipliers[match[2].toUpperCase()] || 1)); + } + + /** + * 通过文件路径在 hik_downloads 中查找记录(用于生成 ID 式下载链接) + */ + _findDownloadFileByPath(filePath) { + if (!filePath) return null; + try { + return this.db.get('SELECT id FROM hik_downloads WHERE output_path = ? LIMIT 1', filePath); + } catch (_) { return null; } + } + + /** + * Push 任务完成结果到远程服务器 + */ + _pushTaskResult(taskId, result) { + if (!this.wsClient || this.wsClient.status !== 'connected') { + // 未连接时稍后重试 + setTimeout(() => this._pushTaskResult(taskId, result), 10000); + return; + } + const { uniqueCode } = this._getTaskMeta(taskId); + const fileUrl = this._filePathToRecordingsUrl(result.output); + this.wsClient.send({ + method: 'hikvision.taskComplete', + data: { + taskId, + uniqueCode, + output: result.output, + size: result.size || 0, + duration: result.duration || 0, + speed: result.speed || 4, + success: result.success !== false, + status: 'completed', + fileUrl + } + }); + } + + /** + * Push 任务失败信息到远程服务器 + */ + _pushTaskFailed(taskId, errorMessage) { + if (!this.wsClient || this.wsClient.status !== 'connected') { + setTimeout(() => this._pushTaskFailed(taskId, errorMessage), 10000); + return; + } + const { uniqueCode } = this._getTaskMeta(taskId); + this.wsClient.send({ + method: 'hikvision.taskComplete', + data: { + taskId, + uniqueCode, + success: false, + status: 'failed', + error: errorMessage + } + }); + // 记录推送,1 分钟后检查是否需要重试 + this._markPushAttempt(taskId, 1); + } + + /** + * 标记一次推送尝试,设置下次重试时间 + * @param {string} taskId + * @param {number} retryCount 当前是第几次(1-based) + */ + _markPushAttempt(taskId, retryCount) { + // 重试间隔:1 分钟、3 分钟、9 分钟 + const delays = [60, 180, 540]; + const delaySec = delays[Math.min(retryCount - 1, delays.length - 1)]; + const nextAt = new Date(Date.now() + delaySec * 1000).toISOString(); + try { + this.db.run( + 'UPDATE hik_tasks SET push_retry = ?, push_next_retry_at = ? WHERE task_id = ?', + retryCount, nextAt, taskId + ); + } catch (_) { /* */ } + } + + /** + * 重试未确认的推送:已完成/失败但服务端未 ack 的任务 + * 退避间隔:1 分钟 → 3 分钟 → 9 分钟,3 次后放弃 + */ + _retryPendingPushes() { + try { + const nowISO = new Date().toISOString(); + // 查找需要重试的任务:pushed=0, push_retry 1~3, 且已到重试时间 + const rows = this.db.all( + `SELECT task_id, unique_code, status, result, error_message, push_retry + FROM hik_tasks + WHERE pushed = 0 AND push_retry > 0 AND push_retry <= 3 + AND push_next_retry_at <= ?`, + nowISO + ); + for (const row of rows) { + if (!this.wsClient || this.wsClient.status !== 'connected') break; + + const nextRetry = row.push_retry + 1; + if (nextRetry > 3) { + // 3 次后放弃 + this.db.run('UPDATE hik_tasks SET pushed = -1, push_retry = 0, push_next_retry_at = \'\' WHERE task_id = ?', row.task_id); + console.log('[Hikvision] 推送放弃(3次重试失败):', row.task_id); + continue; + } + + // 重建推送内容 + let pushData; + if (row.status === 'completed' && row.result) { + try { + const r = JSON.parse(row.result); + const fileUrl = this._filePathToRecordingsUrl(r.output || ''); + pushData = { + taskId: row.task_id, + uniqueCode: row.unique_code, + output: r.output || '', + size: r.size || 0, + duration: r.duration || 0, + speed: r.speed || 4, + success: true, + status: 'completed', + fileUrl + }; + } catch { continue; } + } else if (row.status === 'failed') { + pushData = { + taskId: row.task_id, + uniqueCode: row.unique_code, + success: false, + status: 'failed', + error: row.error_message || '未知错误' + }; + } else { + continue; + } + + this.wsClient.send({ method: 'hikvision.taskComplete', data: pushData }); + this._markPushAttempt(row.task_id, nextRetry); + console.log('[Hikvision] 推送重试 #' + nextRetry + ':', row.task_id); + } + } catch (e) { + console.error('[Hikvision] 推送重试异常:', e.message); + } + } + + /** + * 读取任务的元信息 + */ + _getTaskMeta(taskId) { + let uniqueCode = ''; + try { + const row = this.db.get('SELECT unique_code FROM hik_tasks WHERE task_id = ?', taskId); + if (row) uniqueCode = row.unique_code || ''; + } catch (_) { /* */ } + return { uniqueCode }; + } + + _formatBytes(bytes) { + if (bytes >= 1024**4) return (bytes / 1024**4).toFixed(1) + 'TB'; + if (bytes >= 1024**3) return (bytes / 1024**3).toFixed(1) + 'GB'; + if (bytes >= 1024**2) return (bytes / 1024**2).toFixed(1) + 'MB'; + return (bytes / 1024).toFixed(1) + 'KB'; + } + async restartBackendRuntime(options = {}) { - const wsPort = Number(options.wsPort) || Number(this.config.wsPort) || 3001; + const wsPort = Number(options.wsPort) || Number(this.config.wsPort) || 17301; // 托管后端进程由桌面壳监管,当前进程不直接执行本地热重启。 if (hasProcessArg('--backend-runner') || hasProcessArg('--service-runner')) { diff --git a/core/wsClient.js b/core/wsClient.js index de3a905..72b5bc3 100644 --- a/core/wsClient.js +++ b/core/wsClient.js @@ -108,7 +108,6 @@ class WSClient { if (this.status === 'connected') { this.send('ping'); const { token, refreshToken, tokenExpireTime } = this.app.config; - console.log(this.app.info,"this.app.info的值") if (!this.app.info && token && refreshToken && tokenExpireTime) { if (tokenExpireTime < Date.now()) { //console.log('[WSClient] 心跳检测: token 已过期,尝试刷新'); @@ -136,7 +135,6 @@ class WSClient { return; } const { method, data } = parsed; - //console.log('[WSClient] 可用服务列表:', method, this.services, '方法:', method); if (!method) { //this.send({ success: false, message: '消息缺少 method 字段' }); return; @@ -145,9 +143,12 @@ class WSClient { let serviceFn = this.services; for (let i = 0; i < methodPath.length; i++) { serviceFn = serviceFn[methodPath[i]]; - //console.log("serviceFn", serviceFn,methodPath[i]); if (!serviceFn) break; } + // 调试:打印非高频方法的路由情况 + if (method && method !== 'base.printerList' && method !== 'printerComponent.statusChange' && method !== 'setting.setToken' && method !== 'setting.setInfo') { + console.log('[WSClient] 方法路由:', method, typeof serviceFn === 'function' ? 'OK' : 'MISSING'); + } if (typeof serviceFn === 'function') { try { const result = await serviceFn(data); diff --git a/core/wsServer.js b/core/wsServer.js index 20f7d16..c4f216c 100644 --- a/core/wsServer.js +++ b/core/wsServer.js @@ -2,14 +2,23 @@ import { WebSocketServer } from 'ws'; import path from 'path'; import fs from 'fs'; import { pathToFileURL } from 'url'; +import { isRecordingMode } from '../utils/runtime.js'; class WSServer { - constructor(port, app, options = {}) { - this.port = port || 8081; + /** + * @param {number|number[]} portCandidates 单个端口或端口候选数组 + * @param {object} app Main 实例 + * @param {object} options WebSocketServer 额外选项 + */ + constructor(portCandidates, app, options = {}) { + this.portCandidates = Array.isArray(portCandidates) + ? portCandidates.filter(p => Number.isFinite(p) && p > 0) + : (Number.isFinite(portCandidates) && portCandidates > 0 ? [portCandidates] : [8081]); + this.port = null; // 实际监听的端口(_start 成功后赋值) this.options = options; this.server = null; this.clients = new Set(); - this.services = app.services; // 从 app 获取服务实例 + this.services = app.services; this.app = app; this._eventHandlers = {}; this._start(); @@ -46,12 +55,24 @@ class WSServer { this._eventHandlers.updateDownloadProgress = (data) => { this.broadcast({ success: true, method: 'update.downloadProgress', result: data }); }; + this._eventHandlers.infoChanged = (data) => { + this.broadcast({ success: true, method: 'setting.infoChanged', result: data }); + }; + this._eventHandlers.frpcStatusChange = (data) => { + this.broadcast({ success: true, method: 'frpc.statusChange', result: data }); + }; + this._eventHandlers.migrationNeeded = (data) => { + this.broadcast({ success: true, method: 'setting.migrationNeeded', result: data }); + }; this.app.on('printerComponentStatusChange', this._eventHandlers.printerComponentStatusChange); this.app.on('wsClientStatusChange', this._eventHandlers.wsClientStatusChange); this.app.on('generateCode', this._eventHandlers.generateCode); this.app.on('printerList', this._eventHandlers.printerList); this.app.on('updateDownloadProgress', this._eventHandlers.updateDownloadProgress); + this.app.on('infoChanged', this._eventHandlers.infoChanged); + this.app.on('frpcStatusChange', this._eventHandlers.frpcStatusChange); + this.app.on('migrationNeeded', this._eventHandlers.migrationNeeded); } _unbindAppEvents() { @@ -74,35 +95,69 @@ class WSServer { if (this._eventHandlers.updateDownloadProgress) { this.app.off('updateDownloadProgress', this._eventHandlers.updateDownloadProgress); } + if (this._eventHandlers.infoChanged) { + this.app.off('infoChanged', this._eventHandlers.infoChanged); + } + if (this._eventHandlers.frpcStatusChange) { + this.app.off('frpcStatusChange', this._eventHandlers.frpcStatusChange); + } + if (this._eventHandlers.migrationNeeded) { + this.app.off('migrationNeeded', this._eventHandlers.migrationNeeded); + } this._eventHandlers = {}; } _start() { - this.server = new WebSocketServer({ port: this.port, ...this.options }); - this.server.on('connection', (ws, req) => { - this.clients.add(ws); - //console.log('[WSServer] 新客户端连接,当前连接数:', this.clients.size); - if (typeof this.onConnection === 'function') { - this.onConnection(ws, req); + const tryPort = (index) => { + if (index >= this.portCandidates.length) { + console.error('[WSServer] 所有端口均被占用:', this.portCandidates); + return; } - ws.on('message', (msg) => { - //console.log('[WSServer] 收到消息:', msg); - this._handleMessage(ws, msg); + const candidate = this.portCandidates[index]; + const server = new WebSocketServer({ port: candidate, ...this.options }); + + server.on('listening', () => { + this.port = candidate; + this.server = server; + console.log('[WSServer] WS 服务已启动,端口:', candidate); + this.app.emit('wsServerReady', { port: candidate }); }); - ws.on('close', () => { - this.clients.delete(ws); - if (this.clients.size === 0 && this.app.CodeTimer) { - clearTimeout(this.app.CodeTimer); - console.log('所有客户端已断开,清除绑定码定时器', this.app.CodeTimer); - this.app.CodeTimer = null; + + server.on('error', (err) => { + if (err.code === 'EADDRINUSE') { + console.warn('[WSServer] 端口 %d 被占用,尝试下一个', candidate); + tryPort(index + 1); + return; } - console.log('[WSServer] 客户端断开,当前连接数:', this.clients.size); + console.error('[WSServer] 端口 %d 启动失败:', candidate, err.message); + tryPort(index + 1); }); - ws.on('error', (err) => { - this.clients.delete(ws); - console.log('[WSServer] 客户端错误:', err.message); + + server.on('connection', (ws, req) => { + this.clients.add(ws); + if (typeof this.onConnection === 'function') { + this.onConnection(ws, req); + } + ws.on('message', (msg) => { + this._handleMessage(ws, msg); + }); + ws.on('close', () => { + this.clients.delete(ws); + if (this.clients.size === 0 && this.app.CodeTimer) { + clearTimeout(this.app.CodeTimer); + console.log('所有客户端已断开,清除绑定码定时器', this.app.CodeTimer); + this.app.CodeTimer = null; + } + console.log('[WSServer] 客户端断开,当前连接数:', this.clients.size); + }); + ws.on('error', (err) => { + this.clients.delete(ws); + console.log('[WSServer] 客户端错误:', err.message); + }); }); - }); + }; + + tryPort(0); } async onConnection(ws, req) { const tasks = []; @@ -127,8 +182,10 @@ class WSServer { })); } - // 发送打印组件列表 - if (this.services.printerComponent && typeof this.services.printerComponent.getAll === 'function') { + // 发送打印组件列表(录制模式跳过) + if (isRecordingMode(this.app.config)) { + // 录制模式:静默跳过,不发送错误 + } else if (this.services.printerComponent && typeof this.services.printerComponent.getAll === 'function') { try { const components = this.services.printerComponent.getAll(); // 同步调用 ws.send(JSON.stringify({ success: true, method: 'printerComponent.getAll', result: components })); @@ -139,8 +196,10 @@ class WSServer { ws.send(JSON.stringify({ success: false, message: 'printerComponent.getAll 服务不可用' })); } - // 发送打印机列表 - if (this.services.printer && typeof this.services.printer.getWindowsPrinters === 'function') { + // 发送打印机列表(录制模式跳过) + if (isRecordingMode(this.app.config)) { + // 录制模式:静默跳过 + } else if (this.services.printer && typeof this.services.printer.getWindowsPrinters === 'function') { tasks.push( this.services.printer.getWindowsPrinters() ); @@ -152,6 +211,15 @@ class WSServer { if (this.app.wsClient) { ws.send(JSON.stringify({ success: true, method: 'wsClient.statusChange', result: { status: this.app.wsClient.status } })); } + // 发送 frpc 初始状态(弥补时序:frpc 可能在 wsServer 启动前就已就绪) + if (this.services.frpc && typeof this.services.frpc.getStatus === 'function') { + try { + const frpcStatus = this.services.frpc.getStatus(); + ws.send(JSON.stringify({ success: true, method: 'frpc.statusChange', result: frpcStatus })); + } catch (err) { + ws.send(JSON.stringify({ success: false, message: '获取 frpc 状态失败: ' + err.message })); + } + } if (!this.app.config.token) { //检测是否随机码过期 if (this.app.randomCode) { diff --git a/db/init.sql b/db/init.sql new file mode 100644 index 0000000..2be6ce0 --- /dev/null +++ b/db/init.sql @@ -0,0 +1,44 @@ +-- printServer SQLite 建表脚本 +-- 数据库文件: printserver.db + +-- 海康 NVR 下载记录表(存储配额管理) +CREATE TABLE IF NOT EXISTS hik_downloads ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + task_id TEXT NOT NULL UNIQUE, + ip TEXT DEFAULT '', + channel INTEGER DEFAULT 0, + output_path TEXT NOT NULL, + file_size INTEGER DEFAULT 0, + duration REAL DEFAULT 0, + resolution TEXT DEFAULT '', + status TEXT DEFAULT 'done', + deleted INTEGER DEFAULT 0, + created_at TEXT DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_hik_downloads_deleted ON hik_downloads(deleted); +CREATE INDEX IF NOT EXISTS idx_hik_downloads_status ON hik_downloads(status); + +-- 海康 NVR 任务池表(调度、重试、超时管理) +CREATE TABLE IF NOT EXISTS hik_tasks ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + task_id TEXT NOT NULL UNIQUE, + unique_code TEXT DEFAULT '', + task_params TEXT, + status TEXT DEFAULT 'pending', + worker_id INTEGER, + retry INTEGER DEFAULT 0, + notice INTEGER DEFAULT 0, + timeout INTEGER DEFAULT 0, + error_message TEXT, + result TEXT, + tmp_file_path TEXT DEFAULT '', + pushed INTEGER DEFAULT 0, + push_retry INTEGER DEFAULT 0, + push_next_retry_at TEXT DEFAULT '', + start_time TEXT, + end_time TEXT, + created_at TEXT DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_hik_tasks_unique_code ON hik_tasks(unique_code); +CREATE INDEX IF NOT EXISTS idx_hik_tasks_status ON hik_tasks(status); +CREATE INDEX IF NOT EXISTS idx_hik_tasks_worker ON hik_tasks(worker_id); diff --git a/e2e_test.mjs b/e2e_test.mjs new file mode 100644 index 0000000..ad01ee9 --- /dev/null +++ b/e2e_test.mjs @@ -0,0 +1,63 @@ +// e2e 测试:下载+转码+验证链接 +const base = 'http://127.0.0.1:3002'; + +async function post(path, body) { + const res = await fetch(base + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + return res.json(); +} + +async function get(path) { + const res = await fetch(base + path); + return res.json(); +} + +const cfg = { ip: '192.168.8.241', port: 7681, httpPort: 80, user: 'admin', pass: 'ky666888', channel: 33, start: '2026-07-01T00:03:00Z', end: '2026-07-01T00:05:00Z', speed: 4, output: 'G:/gameauto/recordings/verify_link.ps' }; + +console.log('[1] POST /api/hikvision/download'); +const { taskId, status } = await post('/api/hikvision/download', cfg); +console.log(' taskId:', taskId, 'status:', status); + +console.log('[2] 轮询...'); +let s; +for (let i = 0; i < 30; i++) { + await new Promise(r => setTimeout(r, 1000)); + s = await get('/api/hikvision/status?taskId=' + taskId); + const mb = s.progress?.totalMB || 0; + console.log(' [' + (i + 1) + ']', s.status, mb + 'MB'); + if (s.status !== 'downloading' && s.status !== 'starting') break; +} + +console.log('\n========================================'); +console.log(' 最终结果'); +console.log('========================================'); +const { result } = s; +console.log(' output :', result.output); +console.log(' size :', (result.size / 1024).toFixed(0) + 'KB'); +console.log(' duration:', result.duration + 's'); +console.log(' rawPs :', result.rawPs || false); +console.log(' chunks :', result.chunks || 'n/a'); + +const fs = await import('fs'); +const filePath = result.output; +if (fs.existsSync(filePath)) { + const stat = fs.statSync(filePath); + console.log('\n ✅ 文件存在: ' + stat.size + ' bytes'); + console.log(' 📁 本地路径: ' + filePath); + console.log(' 🔗 file 链接: file:///' + filePath.replace(/\\/g, '/')); + + // ffprobe 验证 + const { execSync } = await import('child_process'); + try { + const probe = execSync('ffprobe "' + filePath + '" 2>&1', { encoding: 'utf-8', stdio: 'pipe' }); + const durMatch = probe.match(/Duration: ([^,]+)/); + const vidMatch = probe.match(/Video: ([^\n]+)/); + const audMatch = probe.match(/Audio: ([^\n]+)/); + if (durMatch) console.log(' ⏱ Duration:', durMatch[1].trim()); + if (vidMatch) console.log(' 🎬 Video :', vidMatch[1].trim()); + if (audMatch) console.log(' 🔊 Audio :', audMatch[1].trim()); + } catch (e) { + console.log(' ffprobe 失败:', e.message); + } +} else { + console.log('\n ❌ 文件不存在: ' + filePath); +} diff --git a/electron/build-installer.mjs b/electron/build-installer.mjs index 98a8035..ed2854d 100644 --- a/electron/build-installer.mjs +++ b/electron/build-installer.mjs @@ -8,5 +8,5 @@ await build({ projectDir, prepackaged, win: ['nsis'], - publish: 'never' + publish: 'never', }); \ No newline at end of file diff --git a/electron/main.cjs b/electron/main.cjs index b2607f7..d486d37 100644 --- a/electron/main.cjs +++ b/electron/main.cjs @@ -1,4 +1,4 @@ -const { app, BrowserWindow, Menu, Tray, nativeImage, ipcMain } = require('electron'); +const { app, BrowserWindow, Menu, Tray, nativeImage, ipcMain, dialog } = require('electron'); const path = require('path'); const net = require('net'); const { spawn } = require('child_process'); @@ -88,7 +88,20 @@ function isPortReachable(port) { } async function isBackendReady() { - return isPortReachable(3001); + try { + // 优先读运行时状态(后端实际选中的端口) + var runtimeMod = await loadWorkspaceModule('utils/runtime.js'); + var rt = runtimeMod.readRuntimeState(); + if (rt.wsPort) { + return isPortReachable(rt.wsPort); + } + // 降级:读配置 + var config = await readRuntimeConfig(); + var port = config.wsPort || 17301; + return isPortReachable(port); + } catch (_) { + return isPortReachable(17301); + } } // ─── 打包模式:WS 桥接(连接子进程的本地 WS 服务) ─── @@ -99,8 +112,19 @@ async function ensureBackendBridge() { if (_bridgeConnectPromise) return _bridgeConnectPromise; _bridgeConnectPromise = (async function () { - var config = await readRuntimeConfig(); - var wsPort = config.wsPort || 3001; + // 优先读运行时状态(后端实际选中的端口) + var wsPort; + try { + var runtimeMod = await loadWorkspaceModule('utils/runtime.js'); + var rt = runtimeMod.readRuntimeState(); + if (rt.wsPort) { + wsPort = rt.wsPort; + } + } catch (_) { /* ignore */ } + if (!wsPort) { + var config = await readRuntimeConfig(); + wsPort = config.wsPort || 17301; + } var mod = await import('ws'); var WebSocketImpl = mod.default || mod.WebSocket || require('ws'); @@ -249,6 +273,218 @@ ipcMain.handle('service:getBackendStatus', () => { return 'connecting'; }); +/** 获取后端 HTTP 端口 */ +ipcMain.handle('service:getHttpPort', async () => { + try { + var runtimeMod = await loadWorkspaceModule('utils/runtime.js'); + var rt = runtimeMod.readRuntimeState(); + if (rt.httpPort) return rt.httpPort; + } catch (_) { /* ignore */ } + try { + var config = await readRuntimeConfig(); + return config.httpPort || 17311; + } catch (_) { + return 17311; + } +}); + +/** 通过 IPC 代理调用后端 API(全模式内部直调,共享文件系统) */ +ipcMain.handle('service:callApi', async (_event, apiPath, options) => { + try { + var method = (options && options.method) || 'GET'; + var body = options && options.body; + var urlParams = new URLSearchParams(apiPath.includes('?') ? apiPath.split('?')[1] : ''); + var pathOnly = apiPath.split('?')[0]; + + // /api/hikvision/files → 直接查 DB + if (pathOnly === '/api/hikvision/files' && method === 'GET') { + try { + var dbMod = await loadWorkspaceModule('utils/db.js'); + var db = dbMod.default; + var page = parseInt(urlParams.get('page')) || 1; + var pageSize = Math.min(parseInt(urlParams.get('pageSize')) || 20, 100); + var search = (urlParams.get('search') || '').trim(); + var offset = (page - 1) * pageSize; + + var whereClause = ''; + var queryParams = []; + if (search) { + whereClause = 'WHERE (ip LIKE ? OR output_path LIKE ?)'; + queryParams.push('%' + search + '%', '%' + search + '%'); + } + var totalRow = db.get('SELECT COUNT(*) as total FROM hik_downloads ' + whereClause, ...queryParams); + var total = totalRow ? totalRow.total : 0; + var rows = db.all('SELECT * FROM hik_downloads ' + whereClause + ' ORDER BY id DESC LIMIT ? OFFSET ?', ...queryParams, pageSize, offset); + var storageRow = db.get('SELECT COALESCE(SUM(file_size), 0) as used, COUNT(*) as fileCount FROM hik_downloads WHERE deleted = 0'); + var usedBytes = storageRow ? storageRow.used : 0; + var fileCount = storageRow ? storageRow.fileCount : 0; + var hikCfg = (backendApp ? backendApp.config : await readRuntimeConfig()).hikvision || {}; + var maxStorage = parseSizeToBytes(hikCfg.maxStorage || '50GB'); + + // 获取 HTTP 端口用于生成播放 URL + var dlPort; + try { + var rtMod = await loadWorkspaceModule('utils/runtime.js'); + dlPort = rtMod.readRuntimeState().httpPort; + } catch (_) { /* ignore */ } + if (!dlPort) dlPort = (backendApp ? backendApp.config : await readRuntimeConfig()).httpPort || 17311; + + return { + success: true, + data: { + list: rows.map(function (r) { + return { + ...r, + downloadUrl: r.output_path ? 'http://127.0.0.1:' + dlPort + '/api/hikvision/file?path=' + encodeURIComponent(r.output_path) : null + }; + }), + page: page, pageSize: pageSize, total: total, + storage: { used: usedBytes, max: maxStorage, fileCount: fileCount, percent: maxStorage > 0 ? Math.round(usedBytes / maxStorage * 100) : 0 } + } + }; + } catch (e) { return { success: false, message: e.message }; } + } + + // /api/hikvision/config → 直接读写 config.json + if (pathOnly === '/api/hikvision/config') { + if (method === 'GET') { + try { + var cfg = (backendApp ? backendApp.config : await readRuntimeConfig()).hikvision || {}; + return { success: true, hikvision: cfg }; + } catch (e) { return { success: false, message: e.message }; } + } + if (method === 'POST') { + try { + var cfgMod = await loadWorkspaceModule('utils/config.js'); + var configUtil = cfgMod.default; + var currentConfig = configUtil.read(); + currentConfig.hikvision = { ...(currentConfig.hikvision || {}), ...body }; + configUtil.write(currentConfig); + if (backendApp) backendApp.config = currentConfig; + return { success: true, message: '配置已保存', hikvision: currentConfig.hikvision }; + } catch (e) { return { success: false, message: e.message }; } + } + } + + // /api/health + if (pathOnly === '/api/health' && method === 'GET') { + return { success: true, message: 'OK' }; + } + + // /api/hikvision/tasks → 查询 hik_tasks 表 + if (pathOnly === '/api/hikvision/tasks' && method === 'GET') { + try { + var dbMod2 = await loadWorkspaceModule('utils/db.js'); + var db2 = dbMod2.default; + var tPage = parseInt(urlParams.get('page')) || 1; + var tPageSize = Math.min(parseInt(urlParams.get('pageSize')) || 50, 100); + var tStatus = urlParams.get('status') || ''; + var tOffset = (tPage - 1) * tPageSize; + + var tWhere = ''; + var tParams = []; + if (tStatus) { tWhere = 'WHERE status = ?'; tParams.push(tStatus); } + + var tTotalRow = db2.get('SELECT COUNT(*) as total FROM hik_tasks ' + tWhere, ...tParams); + var tRows = db2.all('SELECT * FROM hik_tasks ' + tWhere + ' ORDER BY id DESC LIMIT ? OFFSET ?', ...tParams, tPageSize, tOffset); + + return { + success: true, + data: { + list: tRows.map(function(r) { + var p = r.task_params ? JSON.parse(r.task_params) : {}; + var rt = r.result ? JSON.parse(r.result) : null; + return { + id: r.id, task_id: r.task_id, unique_code: r.unique_code || '', + status: r.status, + ip: p.ip || '', channel: p.channel || 0, + speed: p.speed || 4, videoTime: p.videoTime || 0, + rec_start: p.start || '', rec_end: p.end || '', + output: p.output || '', retry: r.retry, + error_message: r.error_message, start_time: r.start_time, end_time: r.end_time, + created_at: r.created_at, progress: null, result: rt + }; + }), + page: tPage, pageSize: tPageSize, + total: tTotalRow ? tTotalRow.total : 0 + } + }; + } catch (e) { return { success: false, message: e.message }; } + } + + // /api/hikvision/retry → 重试/重录任务 + if (pathOnly === '/api/hikvision/retry' && method === 'POST') { + try { + var dbMod3 = await loadWorkspaceModule('utils/db.js'); + var db3 = dbMod3.default; + var taskId = (body && body.taskId) || ''; + if (!taskId) return { success: false, message: '缺少 taskId' }; + + var task = db3.get('SELECT status FROM hik_tasks WHERE task_id = ?', taskId); + if (!task) return { success: false, message: '任务不存在' }; + + if (task.status === 'completed' || task.status === 'done') { + // 重录已完成任务:先删除旧文件,再重置状态 + console.log('[Retry] 重录已完成任务:', taskId, '原状态:', task.status); + // 读取旧文件路径并删除 + var oldRow = db3.get('SELECT tmp_file_path FROM hik_tasks WHERE task_id = ?', taskId); + if (oldRow && oldRow.tmp_file_path) { + try { + var cfgMod4 = await loadWorkspaceModule('utils/config.js'); + var hikCfg = cfgMod4.default.read().hikvision || {}; + var baseDir = (hikCfg.downloadDir || 'D').replace(/[\\\/]+$/, ''); + if (/^[A-Za-z]$/.test(baseDir)) baseDir = baseDir + ':/hikvision_recordings'; + var absPath = require('path').join(baseDir, oldRow.tmp_file_path); + if (require('fs').existsSync(absPath)) { + require('fs').unlinkSync(absPath); + console.log('[Retry] 已删除旧文件:', absPath); + } + } catch (e) { console.error('[Retry] 删除旧文件失败:', e.message); } + } + db3.run( + "UPDATE hik_tasks SET status='pending', retry=0, error_message=NULL, result=NULL, end_time=NULL, pushed=0, push_retry=0, push_next_retry_at='' WHERE task_id=?", + taskId + ); + return { success: true, message: '已重新加入录制队列' }; + } else if (task.status === 'failed' || task.status === 'timeout') { + console.log('[Retry] 重试失败任务:', taskId); + db3.run( + "UPDATE hik_tasks SET status='pending', retry=retry+1, error_message=NULL WHERE task_id=?", + taskId + ); + return { success: true, message: '已重新加入队列' }; + } else { + return { success: false, message: '当前状态不支持重试: ' + task.status }; + } + } catch (e) { return { success: false, message: e.message }; } + } + + return { success: false, message: 'Unknown API: ' + pathOnly }; + } catch (e) { + console.error('[callApi] error:', e.message); + return { success: false, message: e.message }; + } +}); + +function parseSizeToBytes(sizeStr) { + var match = String(sizeStr).match(/^([\d.]+)\s*(TB|GB|MB|KB)$/i); + if (!match) return 50 * 1024 * 1024 * 1024; + var num = parseFloat(match[1]); + var multipliers = { TB: Math.pow(1024, 4), GB: Math.pow(1024, 3), MB: Math.pow(1024, 2), KB: 1024 }; + return Math.round(num * (multipliers[match[2].toUpperCase()] || 1)); +} + +/** 打开文件夹选择对话框 */ +ipcMain.handle('dialog:openFolder', async () => { + if (!mainWindow || mainWindow.isDestroyed()) return { canceled: true }; + var result = await dialog.showOpenDialog(mainWindow, { + title: '选择下载目录', + properties: ['openDirectory'] + }); + if (result.canceled) return { canceled: true }; + return { canceled: false, path: result.filePaths[0] }; +}); + /** * 注册后端事件 → 渲染进程转发(替代 WSServer.onConnection / _bindAppEvents) */ @@ -271,15 +507,33 @@ function setupEventForwarding() { // wsClient 状态变化改用防抖转发,避免短暂断开/重连导致 UI 闪烁 let wsStatusDebounceTimer = null; + let wsLastForwardedStatus = null; const forwardWsStatus = (data) => { + // error 立即转发,不防抖 + if (data.status === 'error') { + if (wsStatusDebounceTimer) { + clearTimeout(wsStatusDebounceTimer); + wsStatusDebounceTimer = null; + } + wsLastForwardedStatus = data.status; + if (mainWindow && !mainWindow.isDestroyed()) { + mainWindow.webContents.send('service:event', { + success: true, + method: 'wsClient.statusChange', + result: data + }); + } + return; + } if (wsStatusDebounceTimer) { clearTimeout(wsStatusDebounceTimer); wsStatusDebounceTimer = null; } - // connected 立即转发;disconnected/error 延迟 2 秒确认 + // connected 立即转发;disconnected 延迟 2 秒确认 const delayMs = data.status === 'connected' ? 0 : 2000; wsStatusDebounceTimer = setTimeout(() => { wsStatusDebounceTimer = null; + wsLastForwardedStatus = data.status; if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.webContents.send('service:event', { success: true, @@ -333,6 +587,12 @@ function setupEventForwarding() { backendApp.on('updateDownloadProgress', forward('update.downloadProgress')); + backendApp.on('infoChanged', forward('setting.infoChanged')); + + backendApp.on('frpcStatusChange', forward('frpc.statusChange')); + + backendApp.on('migrationNeeded', forward('setting.migrationNeeded')); + // ─── 主动请求绑定码(替代 WSServer.onConnection),仅首次未绑定时请求一次 ─── let bindCodeRequested = false; const requestBindCode = () => { @@ -371,6 +631,9 @@ function setupEventForwarding() { () => backendApp.off('printerList'), () => backendApp.off('generateCode', generateCodeHandler), () => backendApp.off('updateDownloadProgress'), + () => backendApp.off('infoChanged'), + () => backendApp.off('frpcStatusChange'), + () => backendApp.off('migrationNeeded'), () => backendApp.off('wsClientStatusChange', wsStatusHandler) ]; diff --git a/electron/preload.cjs b/electron/preload.cjs index 219fe93..e66a660 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -44,5 +44,28 @@ contextBridge.exposeInMainWorld('printServerAPI', { const handler = (_event, status) => callback(status); ipcRenderer.on('backend:status', handler); return () => ipcRenderer.removeListener('backend:status', handler); - } + }, + + /** + * 获取后端 HTTP 端口(用于直接调用 HTTP API) + * @returns {Promise} + */ + getHttpPort: () => + ipcRenderer.invoke('service:getHttpPort'), + + /** + * 通过 IPC 代理调用后端 HTTP API + * @param {string} path API 路径,如 '/api/hikvision/files?page=1' + * @param {object} options { method, body } + * @returns {Promise} + */ + callApi: (path, options) => + ipcRenderer.invoke('service:callApi', path, options || {}), + + /** + * 打开文件夹选择对话框 + * @returns {Promise<{canceled: boolean, path?: string}>} + */ + selectFolder: () => + ipcRenderer.invoke('dialog:openFolder') }); diff --git a/frpc/frpc.exe b/frpc/frpc.exe new file mode 100644 index 0000000..406a085 Binary files /dev/null and b/frpc/frpc.exe differ diff --git a/hik_download_debug.py b/hik_download_debug.py new file mode 100644 index 0000000..935e61f --- /dev/null +++ b/hik_download_debug.py @@ -0,0 +1,183 @@ +"""Hikvision NVR WebSocket download tool (debug version with verbose logging)""" +import json,sys,time,os,hashlib,struct,socket,subprocess,shutil +from base64 import b64encode +from xml.etree import ElementTree as ET +import requests + +def main(): + # 支持命令行参数或写死的测试参数 + if len(sys.argv) > 1: + cfg = json.loads(sys.argv[1]) + else: + cfg = { + "ip": "192.168.8.241", + "port": 7681, + "httpPort": 80, + "user": "admin", + "pass": "ky666888", + "channel": 33, + "start": "2026-07-01T08:00:00", + "end": "2026-07-01T08:05:00", + "speed": 4, + "output": "G:/gameauto/recordings/output.ps" + } + IP=cfg.get("ip","192.168.8.241");PORT=cfg.get("port",7681);HTTP=cfg.get("httpPort",80) + USER=cfg["user"];PASS=cfg["pass"];CH=cfg.get("channel",33) + START=cfg["start"];END=cfg["end"];SPEED=cfg.get("speed",4);OUT=cfg["output"] + NS={'h':'http://www.hikvision.com/ver20/XMLSchema'} + + print("="*60+"\n Hikvision NVR WS Download (Debug)\n"+"="*60) + print(f" Device:{IP}:{HTTP} Ch:{CH} Time:{START}->{END} Speed:{SPEED}x\n Output:{OUT}") + + s=requests.Session() + # [1] caps + print("\n[1] Caps...") + rand=str(int(time.time()*1000))[-8:] + caps_url = f"http://{IP}:{HTTP}/ISAPI/Security/sessionLogin/capabilities?username={USER}&random:{rand}" + print(f" >>> GET {caps_url}") + r=s.get(caps_url, timeout=5) + print(f" <<< {r.status_code}") + print(f" <<< Headers: {dict(r.headers)}") + print(f" <<< Body: {r.text}") + rt=ET.fromstring(r.text) + sid=rt.findtext('.//h:sessionID','',NS);ch=rt.findtext('.//h:challenge','',NS) + itr=int(rt.findtext('.//h:iterations','1',NS));slt=rt.findtext('.//h:salt','',NS) + ver=rt.findtext('.//h:sessionIDVersion','1',NS);vl=rt.findtext('.//h:isSessionIDValidLongTerm','false',NS) + st=rt.findtext('.//h:isSupportSessionTag','false',NS);irr=rt.findtext('.//h:isIrreversible','false',NS)=='true' + print(f" v={ver} itr={itr} irrev={irr}") + + # [2] pwd + print("[2] Calc password...") + if irr: + d=hashlib.sha256((USER+slt+PASS).encode()).hexdigest();d=hashlib.sha256((d+ch).encode()).hexdigest() + for _ in range(2,itr):d=hashlib.sha256(d.encode()).hexdigest() + else: + d=hashlib.sha256((PASS+ch).encode()).hexdigest() + for _ in range(1,itr):d=hashlib.sha256(d.encode()).hexdigest() + print(f" digest={d[:16]}...") + + # [3] login + print("[3] Login...") + ts=str(int(time.time()*1000)) + if ver=='2': + xml=f'{USER}{d}{sid}{vl}2{st}' + else: + xml=f'{USER}{d}{sid}' + login_url = f"http://{IP}:{HTTP}/ISAPI/Security/sessionLogin?timeStamp={ts}" + print(f" >>> POST {login_url}") + print(f" >>> Headers: {{'Content-Type': 'text/plain;charset=UTF-8'}}") + print(f" >>> Body: {xml}") + r=s.post(login_url, data=xml.encode(), headers={"Content-Type":"text/plain;charset=UTF-8"}, timeout=5) + print(f" <<< {r.status_code}") + print(f" <<< Headers: {dict(r.headers)}") + print(f" <<< Body: {r.text}") + if r.status_code!=200:print(f" FAIL {r.status_code} {r.text[:200]}");sys.exit(1) + tag=ET.fromstring(r.text).findtext('.//h:sessionTag','',NS);s.headers["SessionTag"]=tag + print(f" OK tag={tag[:16]}...") + + # [4] token + print("[4] Token...") + token_url = f"http://{IP}:{HTTP}/ISAPI/Security/token?format=json" + print(f" >>> GET {token_url}") + print(f" >>> Cookies: {dict(s.cookies)}") + print(f" >>> SessionTag header: {s.headers.get('SessionTag', 'N/A')[:16]}...") + r=s.get(token_url, timeout=5) + print(f" <<< {r.status_code}") + print(f" <<< Body: {r.text[:200]}") + if r.status_code!=200: + print(" SessionTag 方式失败, 尝试 Digest 认证...") + s2=requests.Session();s2.auth=requests.auth.HTTPDigestAuth(USER,PASS) + durl = f"http://{IP}:{HTTP}/ISAPI/System/deviceInfo" + print(f" >>> GET {durl} (Digest Auth)") + r2=s2.get(durl, timeout=5) + print(f" <<< {r2.status_code}") + print(f" >>> GET {token_url} (Digest Auth)") + r=s2.get(token_url, timeout=5) + print(f" <<< {r.status_code}") + print(f" <<< Body: {r.text[:200]}") + tok=r.json()["Token"]["value"] + print(f" token={tok[:40]}...") + + # [5] WS + print("[5] WebSocket...") + key=b64encode(os.urandom(16)).decode() + ws_path = f"/?version=1.0&cipherSuites=1&token={tok}" + hs=(f"GET {ws_path} HTTP/1.1\r\n" + f"Host: {IP}:{PORT}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + f"Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: {key}\r\n" + f"Origin: http://127.0.0.1\r\nUser-Agent: Mozilla/5.0 Chrome/149.0\r\n\r\n") + print(f" >>> WS connect to {IP}:{PORT}") + print(f" >>> WS Handshake:") + for l in hs.split('\r\n'): + if l: print(f" {l}") + sk=socket.socket();sk.settimeout(10);sk.connect((IP,PORT));sk.send(hs.encode()) + resp=b"" + while b"\r\n\r\n" not in resp:resp+=sk.recv(4096) + print(f" <<< WS 握手响应:") + hdr = resp[:resp.find(b"\r\n\r\n")].decode() + for l in hdr.split('\r\n'): + if l: print(f" {l}") + rem=resp[resp.find(b"\r\n\r\n")+4:] + print(f" OK shake: {rem[2:].decode()}" if len(rem)>2 else " OK") + + def ws_send(data): + p=data.encode() if isinstance(data,str) else data + f=bytearray([0x81 if isinstance(data,str) else 0x82]);l=len(p) + if l<126:f.append(l) + elif l<65536:f.extend([126,*struct.pack(">H",l)]) + else:f.extend([127,*struct.pack(">Q",l)]) + f.extend(p);sk.send(bytes(f)) + def ws_recv(): + h=sk.recv(2) + if len(h)<2:return None + op,l=h[0]&0xF,h[1]&0x7F + if l==126:l=struct.unpack(">H",sk.recv(2))[0] + elif l==127:l=struct.unpack(">Q",sk.recv(8))[0] + d=b"" + while len(d)>> WS Playback cmd: {json.dumps(cmd)}") + ws_send(json.dumps(cmd)) + + os.makedirs(os.path.dirname(OUT)or".",exist_ok=True) + f=open(OUT,"wb");total=0;chunks=0;ss=False;t0=time.time();lr=t0;sk.settimeout(120) + while True: + try:msg=ws_recv() + except socket.timeout:print(f"\n timeout");break + if msg is None:print(f"\n closed");break + if isinstance(msg,str): + d=json.loads(msg);sc=d.get("statusCode",0) + print(f"\n <- {sc} {d.get('statusString','')}") + if sc==1:continue + break + elif isinstance(msg,bytes): + chunks+=1;total+=len(msg);f.write(msg) + if not ss and chunks>=10: + spd_cmd = json.dumps({"sequence":0,"cmd":"speed","rate":SPEED}) + print(f"\n -> speed x{SPEED} cmd: {spd_cmd}") + ws_send(spd_cmd);ss=True + if time.time()-lr>0.5: + el=time.time()-t0;print(f"\r [{chunks:5d}] {total/1048576:.2f}MB {total/el/1024:.0f}KB/s {el:.0f}s",end="");lr=time.time() + + sk.close();f.close() + el=time.time()-t0;mb=total/1048576 if total else 0 + print(f"\n[6] Done: {chunks}chunks {mb:.1f}MB {el:.1f}s {mb/el*8 if el>0 else 0:.1f}Mbps") + + if mb==0:return print(json.dumps({"success":False,"output":OUT,"size":0})) + + mp4=OUT.replace(".ps",".mp4") + print(f"[7] Transcode -> {mp4}") + ff=shutil.which("ffmpeg") or os.path.join(os.environ.get("APPDATA",""),"npm","node_modules","@ffmpeg-installer","ffmpeg","node_modules","@ffmpeg-installer","win32-x64","ffmpeg.exe") + if ff and os.path.exists(ff): + subprocess.run([ff,"-i",OUT,"-c","copy",mp4,"-y"],capture_output=True,timeout=60) + ms=os.path.getsize(mp4);os.remove(OUT) + print(f" OK: {ms/1048576:.1f}MB") + print("\n"+"="*60+"\n"+json.dumps({"success":True,"output":mp4,"size":ms,"duration":el,"speed":SPEED})+"\n"+"="*60) + else: + print(f" No ffmpeg, raw PS: {OUT}") + +if __name__=="__main__":main() diff --git a/package-lock.json b/package-lock.json index b61b4c3..843d2a9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,16 +1,21 @@ { "name": "printserver", - "version": "1.0.0", + "version": "1.0.29", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "printserver", - "version": "1.0.0", + "version": "1.0.29", + "hasInstallScript": true, "license": "ISC", "dependencies": { + "@ffmpeg-installer/ffmpeg": "^1.1.0", + "@xmldom/xmldom": "^0.9.10", + "better-sqlite3": "^12.11.1", "iconv-lite": "^0.7.2", "node-windows": "^1.0.0-beta.8", + "onvif": "^0.8.1", "ws": "^8.19.0" }, "devDependencies": { @@ -484,6 +489,132 @@ "node": ">= 10.0.0" } }, + "node_modules/@ffmpeg-installer/darwin-arm64": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/darwin-arm64/-/darwin-arm64-4.1.5.tgz", + "integrity": "sha512-hYqTiP63mXz7wSQfuqfFwfLOfwwFChUedeCVKkBtl/cliaTM7/ePI9bVzfZ2c+dWu3TqCwLDRWNSJ5pqZl8otA==", + "cpu": [ + "arm64" + ], + "hasInstallScript": true, + "license": "https://git.ffmpeg.org/gitweb/ffmpeg.git/blob_plain/HEAD:/LICENSE.md", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@ffmpeg-installer/darwin-x64": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/darwin-x64/-/darwin-x64-4.1.0.tgz", + "integrity": "sha512-Z4EyG3cIFjdhlY8wI9aLUXuH8nVt7E9SlMVZtWvSPnm2sm37/yC2CwjUzyCQbJbySnef1tQwGG2Sx+uWhd9IAw==", + "cpu": [ + "x64" + ], + "hasInstallScript": true, + "license": "LGPL-2.1", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@ffmpeg-installer/ffmpeg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/ffmpeg/-/ffmpeg-1.1.0.tgz", + "integrity": "sha512-Uq4rmwkdGxIa9A6Bd/VqqYbT7zqh1GrT5/rFwCwKM70b42W5gIjWeVETq6SdcL0zXqDtY081Ws/iJWhr1+xvQg==", + "license": "LGPL-2.1", + "optionalDependencies": { + "@ffmpeg-installer/darwin-arm64": "4.1.5", + "@ffmpeg-installer/darwin-x64": "4.1.0", + "@ffmpeg-installer/linux-arm": "4.1.3", + "@ffmpeg-installer/linux-arm64": "4.1.4", + "@ffmpeg-installer/linux-ia32": "4.1.0", + "@ffmpeg-installer/linux-x64": "4.1.0", + "@ffmpeg-installer/win32-ia32": "4.1.0", + "@ffmpeg-installer/win32-x64": "4.1.0" + } + }, + "node_modules/@ffmpeg-installer/linux-arm": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-arm/-/linux-arm-4.1.3.tgz", + "integrity": "sha512-NDf5V6l8AfzZ8WzUGZ5mV8O/xMzRag2ETR6+TlGIsMHp81agx51cqpPItXPib/nAZYmo55Bl2L6/WOMI3A5YRg==", + "cpu": [ + "arm" + ], + "hasInstallScript": true, + "license": "GPLv3", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/linux-arm64": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-arm64/-/linux-arm64-4.1.4.tgz", + "integrity": "sha512-dljEqAOD0oIM6O6DxBW9US/FkvqvQwgJ2lGHOwHDDwu/pX8+V0YsDL1xqHbj1DMX/+nP9rxw7G7gcUvGspSoKg==", + "cpu": [ + "arm64" + ], + "hasInstallScript": true, + "license": "GPLv3", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/linux-ia32": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-ia32/-/linux-ia32-4.1.0.tgz", + "integrity": "sha512-0LWyFQnPf+Ij9GQGD034hS6A90URNu9HCtQ5cTqo5MxOEc7Rd8gLXrJvn++UmxhU0J5RyRE9KRYstdCVUjkNOQ==", + "cpu": [ + "ia32" + ], + "hasInstallScript": true, + "license": "GPLv3", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/linux-x64": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-x64/-/linux-x64-4.1.0.tgz", + "integrity": "sha512-Y5BWhGLU/WpQjOArNIgXD3z5mxxdV8c41C+U15nsE5yF8tVcdCGet5zPs5Zy3Ta6bU7haGpIzryutqCGQA/W8A==", + "cpu": [ + "x64" + ], + "hasInstallScript": true, + "license": "GPLv3", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/win32-ia32": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/win32-ia32/-/win32-ia32-4.1.0.tgz", + "integrity": "sha512-FV2D7RlaZv/lrtdhaQ4oETwoFUsUjlUiasiZLDxhEUPdNDWcH1OU9K1xTvqz+OXLdsmYelUDuBS/zkMOTtlUAw==", + "cpu": [ + "ia32" + ], + "license": "GPLv3", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@ffmpeg-installer/win32-x64": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/win32-x64/-/win32-x64-4.1.0.tgz", + "integrity": "sha512-Drt5u2vzDnIONf4ZEkKtFlbvwj6rI3kxw1Ck9fpudmtgaZIHD4ucsWB2lCZBXRxJgXR+2IMSti+4rtM4C4rXgg==", + "cpu": [ + "x64" + ], + "license": "GPLv3", + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@isaacs/cliui": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", @@ -861,13 +992,12 @@ } }, "node_modules/@xmldom/xmldom": { - "version": "0.8.11", - "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.11.tgz", - "integrity": "sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw==", - "dev": true, + "version": "0.9.10", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.10.tgz", + "integrity": "sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==", "license": "MIT", "engines": { - "node": ">=10.0.0" + "node": ">=14.6" } }, "node_modules/7zip-bin": { @@ -1199,7 +1329,6 @@ "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "dev": true, "funding": [ { "type": "github", @@ -1216,6 +1345,20 @@ ], "license": "MIT" }, + "node_modules/better-sqlite3": { + "version": "12.11.1", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz", + "integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + }, + "engines": { + "node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x" + } + }, "node_modules/binary-extensions": { "version": "2.3.0", "resolved": "https://mirrors.cloud.tencent.com/npm/binary-extensions/-/binary-extensions-2.3.0.tgz", @@ -1229,11 +1372,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, "node_modules/bl": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "dev": true, "license": "MIT", "dependencies": { "buffer": "^5.5.0", @@ -1280,7 +1431,6 @@ "version": "5.7.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "dev": true, "funding": [ { "type": "github", @@ -1849,7 +1999,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", - "dev": true, "license": "MIT", "dependencies": { "mimic-response": "^3.1.0" @@ -1865,7 +2014,6 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=10" @@ -1874,6 +2022,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/defaults": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz", @@ -1949,7 +2106,6 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, "license": "Apache-2.0", "engines": { "node": ">=8" @@ -2391,7 +2547,6 @@ "version": "1.4.5", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", - "dev": true, "license": "MIT", "dependencies": { "once": "^1.4.0" @@ -2494,6 +2649,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, "node_modules/exponential-backoff": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz", @@ -2557,6 +2721,12 @@ "pend": "~1.2.0" } }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, "node_modules/filelist": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz", @@ -2657,6 +2827,12 @@ "node": ">= 6" } }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, "node_modules/fs-extra": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", @@ -2781,6 +2957,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, "node_modules/glob": { "version": "7.2.3", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", @@ -3096,7 +3278,6 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "dev": true, "funding": [ { "type": "github", @@ -3146,7 +3327,12 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true, + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", "license": "ISC" }, "node_modules/ip-address": { @@ -3549,7 +3735,6 @@ "version": "1.2.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -3701,6 +3886,12 @@ "mkdirp": "bin/cmd.js" } }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://mirrors.cloud.tencent.com/npm/ms/-/ms-2.1.3.tgz", @@ -3708,6 +3899,12 @@ "dev": true, "license": "MIT" }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, "node_modules/negotiator": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", @@ -3867,7 +4064,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, "license": "ISC", "dependencies": { "wrappy": "1" @@ -3889,6 +4085,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/onvif": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/onvif/-/onvif-0.8.1.tgz", + "integrity": "sha512-D0VSuTQutZWQsaWWvh7acbengYNJew25kXpXc/stJc6/xYx2MwU1tkIZA23bu12hr5MxstSQ55decY7we2/LWw==", + "license": "MIT", + "dependencies": { + "xml2js": "^0.6.2" + }, + "engines": { + "node": ">=14.0" + } + }, "node_modules/ora": { "version": "5.4.1", "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", @@ -4060,6 +4268,16 @@ "node": ">=10.4.0" } }, + "node_modules/plist/node_modules/@xmldom/xmldom": { + "version": "0.8.13", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz", + "integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/postject": { "version": "1.0.0-alpha.6", "resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz", @@ -4090,6 +4308,45 @@ "node": "^12.20.0 || >=14" } }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/prebuild-install/node_modules/node-abi": { + "version": "3.94.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.94.0.tgz", + "integrity": "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/proc-log": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-5.0.0.tgz", @@ -4147,7 +4404,6 @@ "version": "3.0.4", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", - "dev": true, "license": "MIT", "dependencies": { "end-of-stream": "^1.1.0", @@ -4177,6 +4433,21 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, "node_modules/read-binary-file-arch": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz", @@ -4194,7 +4465,6 @@ "version": "3.6.2", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "dev": true, "license": "MIT", "dependencies": { "inherits": "^2.0.3", @@ -4377,7 +4647,6 @@ "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true, "funding": [ { "type": "github", @@ -4414,7 +4683,6 @@ "version": "1.6.0", "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz", "integrity": "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==", - "dev": true, "license": "BlueOak-1.0.0", "engines": { "node": ">=11.0.0" @@ -4424,7 +4692,6 @@ "version": "7.7.4", "resolved": "https://mirrors.cloud.tencent.com/npm/semver/-/semver-7.7.4.tgz", "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", - "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -4488,6 +4755,51 @@ "dev": true, "license": "ISC" }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, "node_modules/simple-update-notifier": { "version": "2.0.0", "resolved": "https://mirrors.cloud.tencent.com/npm/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", @@ -4614,7 +4926,6 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "dev": true, "license": "MIT", "dependencies": { "safe-buffer": "~5.2.0" @@ -4676,6 +4987,15 @@ "node": ">=8" } }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/sumchecker": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz", @@ -4719,6 +5039,40 @@ "node": ">=18" } }, + "node_modules/tar-fs": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", + "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-fs/node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/tar/node_modules/yallist": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", @@ -4929,6 +5283,18 @@ "utf8-byte-length": "^1.0.1" } }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, "node_modules/type-fest": { "version": "0.13.1", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz", @@ -5014,7 +5380,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "dev": true, "license": "MIT" }, "node_modules/verror": { @@ -5099,7 +5464,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, "license": "ISC" }, "node_modules/ws": { @@ -5129,6 +5493,28 @@ "integrity": "sha512-huCv9IH9Tcf95zuYCsQraZtWnJvBtLVE0QHMOs8bWyZAFZNDcYjsPq1nEx8jKA9y+Beo9v+7OBPRisQTjinQMw==", "license": "MIT" }, + "node_modules/xml2js": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz", + "integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==", + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/xml2js/node_modules/xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", + "license": "MIT", + "engines": { + "node": ">=4.0" + } + }, "node_modules/xmlbuilder": { "version": "15.1.1", "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", diff --git a/package.json b/package.json index aaa38a6..bde705f 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,14 @@ { "name": "printserver", - "version": "1.0.14", + "version": "1.0.23", "main": "electron/main.cjs", "scripts": { "start": "node index.js", "test": "echo \"Error: no test specified\" && exit 1", - "dev": "nodemon index.js", - "desktop:dev": "electron .", + "dev": "chcp 65001 > nul && nodemon index.js", + "desktop:dev": "chcp 65001 > nul && electron .", + "start:linux": "node index.js", + "postinstall": "node -e \"process.env.npm_config_omit!=='dev'&&process.exit(0);require('child_process').execSync('npx @electron/rebuild -f -w better-sqlite3',{stdio:'inherit'})\"", "package:clean": "powershell -NoProfile -File build.ps1 clean", "package:prepare": "powershell -NoProfile -File build.ps1 prepare", "package:app": "powershell -NoProfile -File build.ps1 app", @@ -19,10 +21,15 @@ "license": "ISC", "description": "Windows local print service with HTTP, WebSocket, tray shell and printer component integration", "dependencies": { + "@ffmpeg-installer/ffmpeg": "^1.1.0", + "@xmldom/xmldom": "^0.9.10", + "better-sqlite3": "^12.11.1", "iconv-lite": "^0.7.2", - "node-windows": "^1.0.0-beta.8", "ws": "^8.19.0" }, + "optionalDependencies": { + "node-windows": "^1.0.0-beta.8" + }, "devDependencies": { "electron": "^37.2.0", "electron-builder": "^26.0.12", @@ -36,12 +43,16 @@ "directories": { "output": "dist" }, + "asarUnpack": [ + "node_modules/@ffmpeg-installer/**/*" + ], "files": [ "electron/**/*", "core/**/*", "services/**/*", "utils/**/*", "views/**/*", + "db/**/*", "index.js", "package.json", "!electron/assets/icon-gray.svg", @@ -64,6 +75,10 @@ { "from": "daemon", "to": "daemon" + }, + { + "from": "frpc", + "to": "frpc" } ], "win": { @@ -92,4 +107,3 @@ } } } - diff --git a/printServer.code-workspace b/printServer.code-workspace index 876a149..9d34d51 100644 --- a/printServer.code-workspace +++ b/printServer.code-workspace @@ -4,5 +4,22 @@ "path": "." } ], - "settings": {} + "settings": { + "files.watcherExclude": { + "dist/**": true, + "node_modules/**": true, + "临时/**": true, + "versioning/**": true + }, + "search.exclude": { + "dist/**": true, + "临时/**": true + }, + "codegraph.exclude": { + "dist/**": true, + "node_modules/**": true, + "临时/**": true, + "versioning/**": true + } + } } \ No newline at end of file diff --git a/printserver.db b/printserver.db new file mode 100644 index 0000000..4a3492c Binary files /dev/null and b/printserver.db differ diff --git a/printserver.db-shm b/printserver.db-shm new file mode 100644 index 0000000..8a8c2c7 Binary files /dev/null and b/printserver.db-shm differ diff --git a/printserver.db-wal b/printserver.db-wal new file mode 100644 index 0000000..a34416c Binary files /dev/null and b/printserver.db-wal differ diff --git a/runtime.json b/runtime.json new file mode 100644 index 0000000..7a4d80e --- /dev/null +++ b/runtime.json @@ -0,0 +1,5 @@ +{ + "wsPort": 17301, + "httpPort": 17311, + "startedAt": "2026-07-24T19:39:53.176Z" +} \ No newline at end of file diff --git a/services/frpc.js b/services/frpc.js new file mode 100644 index 0000000..fe0a49c --- /dev/null +++ b/services/frpc.js @@ -0,0 +1,297 @@ +import { spawn } from 'child_process'; +import fs from 'fs'; +import path from 'path'; +import service from '../core/BaseService.js'; +import configUtil from '../utils/config.js'; +import { getProjectRoot, getResourcePath, getAppDataDir, isRecordingMode } from '../utils/runtime.js'; + +const FRPC_EXE = process.platform === 'win32' ? 'frpc.exe' : 'frpc'; + +// 文件日志:写 console + 写入文件(方便打包后排查问题) +function _logFile(...args) { + const msg = args.join(' '); + console.log(msg); + try { + const logDir = getAppDataDir(); + const logPath = path.join(logDir, 'frpc.log'); + const ts = new Date().toISOString().replace('T', ' ').substring(0, 19); + fs.appendFileSync(logPath, `[${ts}] ${msg}\n`, 'utf-8'); + } catch (_) { /* 写日志失败不阻塞主流程 */ } +} + +function _errFile(...args) { + const msg = args.join(' '); + console.error(msg); + try { + const logDir = getAppDataDir(); + const logPath = path.join(logDir, 'frpc.log'); + const ts = new Date().toISOString().replace('T', ' ').substring(0, 19); + fs.appendFileSync(logPath, `[${ts}] [ERR] ${msg}\n`, 'utf-8'); + } catch (_) { /* ignore */ } +} + +class FrpcService extends service { + constructor() { + super(); + this.process = null; + this.status = 'stopped'; // stopped | starting | running | error + this._watchTimer = null; + + this.updateConfig = this.updateConfig.bind(this); + this.getStatus = this.getStatus.bind(this); + this.stop = this.stop.bind(this); + + // 启动时检查是否需要自动拉起 frpc + _logFile('[Frpc] 服务初始化, 当前 frpc 配置:', JSON.stringify(this.config.frpc || null)); + this._autoStart(); + } + + /** + * 应用启动时自动拉起(如果 config.frpc.enabled 为 true,或录制模式下自动启用) + */ + _autoStart() { + const cfg = this.config.frpc || {}; + // 录制模式 + 有 serverAddr 配置 → 自动启用(无论 enabled 字段) + const shouldAutoStart = cfg.enabled || (isRecordingMode(this.config) && cfg.serverAddr); + if (shouldAutoStart) { + _logFile('[Frpc] 自动启动 frpc (enabled=%s, recording=%s)', + !!cfg.enabled, isRecordingMode(this.config)); + if (!cfg.enabled) { + // 补写 enabled 标记,避免后续 updateConfig 判定混乱 + cfg.enabled = true; + this.config.frpc = cfg; + } + this._startFrpc(); + } + } + + /** + * 服务端下发 frpc 配置(通过 WS 调用) + */ + async updateConfig(data) { + if (!data || typeof data !== 'object') { + return { ok: false, message: '配置数据无效' }; + } + + const { config, app } = this; + config.frpc = { + enabled: !!data.enabled, + serverAddr: data.serverAddr || '', + serverPort: Number(data.serverPort) || 6005, + authToken: data.authToken || '', + token: data.token || '', + proxies: Array.isArray(data.proxies) ? data.proxies : [] + }; + + configUtil.write(config); + app.config = config; + _logFile('[Frpc] 配置已更新:', JSON.stringify(config.frpc)); + + // 根据 enabled 决定启动或停止 + if (config.frpc.enabled && config.frpc.serverAddr) { + this._startFrpc(); + return { ok: true, message: 'frpc 配置已更新,正在启动' }; + } else { + this._stopFrpc(); + return { ok: true, message: 'frpc 已停用' }; + } + } + + /** + * 停止 frpc + */ + stop() { + this._stopFrpc(); + return { ok: true, message: 'frpc 已停止' }; + } + + /** + * 获取当前状态 + */ + getStatus() { + return { + status: this.status, + enabled: !!(this.config.frpc && this.config.frpc.enabled) + }; + } + + // ─── frpc 进程管理 ─── + + _findFrpcExe() { + const root = getProjectRoot(); + const exeName = FRPC_EXE; + + if (process.platform === 'win32') { + this._frpcSearchPaths = [ + getResourcePath('frpc', exeName), + getResourcePath(exeName), + path.join(root, exeName), + path.join(root, 'frpc', exeName), + path.join(root, 'bin', exeName), + path.join(process.cwd(), exeName), + exeName + ]; + } else { + // Linux: 优先查找系统 PATH,再查项目目录 + this._frpcSearchPaths = [ + '/usr/bin/frpc', + '/usr/local/bin/frpc', + '/opt/frp/frpc', + path.join(root, 'frpc', exeName), + path.join(root, exeName), + path.join(process.cwd(), exeName), + exeName + ]; + } + + for (const p of this._frpcSearchPaths) { + if (fs.existsSync(p)) return p; + } + return null; + } + + _generateFrpcIni() { + const cfg = this.config.frpc || {}; + const lines = ['[common]']; + lines.push('server_addr = ' + (cfg.serverAddr || '127.0.0.1')); + lines.push('server_port = ' + (cfg.serverPort || 6005)); + + if (cfg.authToken) { + lines.push('token = ' + cfg.authToken); + } + + // 代理配置 + if (Array.isArray(cfg.proxies)) { + for (const p of cfg.proxies) { + if (!p.name) continue; + lines.push(''); + lines.push('[' + p.name + ']'); + lines.push('type = ' + (p.type || 'http')); + lines.push('local_ip = ' + (p.localIp || '127.0.0.1')); + lines.push('local_port = ' + (p.localPort || 0)); + + // http/https 类型用 subdomain,不设 remote_port + if (p.type === 'http' || p.type === 'https') { + if (p.subdomain) { + lines.push('subdomain = ' + p.subdomain); + } + if (p.customDomains) { + lines.push('custom_domains = ' + p.customDomains); + } + } else { + lines.push('remote_port = ' + (p.remotePort || 0)); + } + } + } + + const root = getAppDataDir(); + const iniPath = path.join(root, 'frpc.ini'); + fs.writeFileSync(iniPath, lines.join('\n'), 'utf-8'); + return iniPath; + } + + _startFrpc() { + const hadProcess = !!this.process; + this._stopFrpc(); + + const doSpawn = () => { + + const exePath = this._findFrpcExe(); + if (!exePath) { + _errFile('[Frpc] frpc.exe 未找到,搜索路径:', JSON.stringify(this._frpcSearchPaths)); + for (const p of this._frpcSearchPaths) { + _errFile('[Frpc] 检查:', p, fs.existsSync(p) ? '(存在)' : '(不存在)'); + } + this._setStatus('error'); + return; + } + + const iniPath = this._generateFrpcIni(); + _logFile('[Frpc] 启动 frpc:', exePath, '-c', iniPath); + _logFile('[Frpc] ini 内容:', fs.readFileSync(iniPath, 'utf-8')); + + try { + const spawnOpts = { + stdio: ['ignore', 'pipe', 'pipe'] + }; + if (process.platform === 'win32') { + spawnOpts.windowsHide = true; + } + this.process = spawn(exePath, ['-c', iniPath], spawnOpts); + + this._setStatus('starting'); + + this.process.stdout.on('data', (data) => { + const text = data.toString(); + _logFile('[Frpc][stdout]', text.trim()); + // frpc 输出中包含 "start proxy success" 表示连接成功 + if (text.includes('start proxy success') || text.includes('run success')) { + this._setStatus('running'); + } + }); + + this.process.stderr.on('data', (data) => { + _errFile('[Frpc][stderr]', data.toString().trim()); + }); + + this.process.on('error', (err) => { + _errFile('[Frpc] 进程错误:', err.message); + this._setStatus('error'); + }); + + this.process.on('exit', (code) => { + _logFile('[Frpc] 进程退出, code:', code); + if (this.status !== 'stopped') { + this._setStatus('error'); + } + this.process = null; + }); + + // 超时检测:10 秒内没收到 running 则标记 error + clearTimeout(this._watchTimer); + this._watchTimer = setTimeout(() => { + if (this.status === 'starting') { + _errFile('[Frpc] 启动超时 (10s)'); + this._setStatus('error'); + } + }, 10000); + + } catch (err) { + _errFile('[Frpc] 启动失败:', err.message); + this._setStatus('error'); + } + }; + + if (hadProcess) { + // 延迟 3 秒让 frp 服务端释放旧代理名 + setTimeout(doSpawn, 3000); + } else { + doSpawn(); + } + } + + _stopFrpc() { + clearTimeout(this._watchTimer); + if (this.process) { + // 移除旧进程的所有事件监听,避免退出事件在新进程启动后误设 error + this.process.removeAllListeners(); + try { + this.process.kill(); + } catch (e) { /* ignore */ } + this.process = null; + } + this._setStatus('stopped'); + } + + _setStatus(newStatus) { + const prev = this.status; + this.status = newStatus; + if (prev !== newStatus) { + _logFile('[Frpc] 状态变更: %s -> %s', prev, newStatus); + // 通知本地前端 + this.app.emit('frpcStatusChange', { status: newStatus }); + } + } +} + +export default FrpcService; diff --git a/services/hikvision.js b/services/hikvision.js new file mode 100644 index 0000000..1ff05be --- /dev/null +++ b/services/hikvision.js @@ -0,0 +1,808 @@ +import crypto from 'crypto'; +import net from 'net'; +import http from 'http'; +import https from 'https'; +import fs from 'fs'; +import path from 'path'; +import { execSync } from 'child_process'; +import { createRequire } from 'module'; +import BaseService from '../core/BaseService.js'; + +let _app; // 构造时保存,避免 WS 回调时 this 丢失 + +const _require = createRequire(import.meta.url); +let _ffmpegPath = null; +try { _ffmpegPath = _require('@ffmpeg-installer/ffmpeg').path; } catch { /* */ } +// ffmpeg-static 优先级更高(版本更新) +try { const p = _require('ffmpeg-static'); _ffmpegPath = typeof p === 'string' ? p : p.path || p.default; } catch { /* */ } + +class HikvisionService extends BaseService { + constructor() { + super(); + _app = this.app; + } + + /** + * 向服务器拉取待执行任务 / 处理服务器返回的任务列表 + */ + async fetchTasks(data) { + // 服务器返回了响应(空或非空数组)→ 不要再次拉取 + if (Array.isArray(data)) { + if (data.length > 0) { + // 打印第一条,方便确认服务端实际字段名 + console.log('[Hikvision] fetchTasks 收到', data.length, '个任务, 首条:', JSON.stringify(data[0])); + const ad = _app; + let created = 0; + for (const item of data) { + try { + // 服务端下发嵌套格式: item.server.{internal_ip,username,...}, item.camera.{channel_id} + const srv = item.server || {}; + const cam = item.camera || {}; + const uniqueCode = item.uniqueCode || ''; + + if (uniqueCode) { + const existing = ad.db.get('SELECT id FROM hik_tasks WHERE unique_code = ?', uniqueCode); + if (existing) continue; + } + + const startStr = item.start_time || ''; + const endStr = item.end_time || ''; + if (!startStr) { console.log('[Hikvision] fetchTasks 跳过: 无 start_time'); continue; } + + const startTime = new Date(startStr); + const endTime = endStr ? new Date(endStr) : new Date(startTime.getTime() + 5 * 60 * 1000); + const taskId = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + const now = new Date(); + const dateDir = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(2, '0')}`; + const relOutput = `/${dateDir}/task_${taskId.slice(-12)}.mp4`; + const videoTime = Math.ceil((endTime - startTime) / 1000); + + const pad = n => String(n).padStart(2, '0'); + const fmtStart = `${startTime.getFullYear()}-${pad(startTime.getMonth()+1)}-${pad(startTime.getDate())}T${pad(startTime.getHours())}:${pad(startTime.getMinutes())}:${pad(startTime.getSeconds())}`; + const fmtEnd = `${endTime.getFullYear()}-${pad(endTime.getMonth()+1)}-${pad(endTime.getDate())}T${pad(endTime.getHours())}:${pad(endTime.getMinutes())}:${pad(endTime.getSeconds())}`; + + ad.db.table('hik_tasks').insert({ + task_id: taskId, unique_code: uniqueCode, + task_params: JSON.stringify({ + ip: srv.internal_ip || '', port: 7681, httpPort: srv.internal_port || 80, + user: srv.username || 'admin', pass: srv.password || '', + channel: cam.channel_id || 33, + start: fmtStart, end: fmtEnd, + speed: 4, output: relOutput, videoTime + }), + status: 'pending', retry: 0, + timeout: videoTime + 60, tmp_file_path: relOutput + }); + created++; + } catch (e) { + console.error('[Hikvision] 创建任务失败:', e.message); + } + } + if (created > 0) { + ad._lastFetchTime = null; + ad._scheduleHikTasks(); + } + console.log('[Hikvision] fetchTasks 完成: 创建了', created, '个任务'); + } + return; // 服务器已响应,不再拉取 + } + // 客户端主动拉取:必须等 app.info 就绪(服务端已确认身份)且是录制电脑 + if (!_app.info) { + console.log('[Hikvision] fetchTasks 跳过: app.info 未就绪,稍后重试'); + return; + } + if (!_app.info.is_recording) { + console.log('[Hikvision] fetchTasks 跳过: 非录制电脑 (is_recording=' + _app.info.is_recording + ')'); + return; + } + console.log('[Hikvision] fetchTasks → 向服务器拉取任务'); + if (_app.wsClient && _app.wsClient.status === 'connected') { + _app.wsClient.send({ method: 'hikvision.fetchTasks', data: {} }); + } + } + + _fmtTime(date) { + const pad = n => String(n).padStart(2, '0'); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; + } + + /** + * 接收服务器下发的录制任务(WS 调用) + * 服务器 → 客户端:{ method: "hikvision.receiveTask", data: { uniqueCode, force?, taskId?, ip, user, pass, channel, start, end, speed, outputPrefix } } + */ + async receiveTask(data = {}) { + const app = _app; + console.log('[Hikvision] receiveTask 收到:', JSON.stringify(data)); + + // 支持两种格式:扁平 {ip,user,pass,channel} 或嵌套 {server:{internal_ip,...},camera:{channel_id}} + const srv = data.server || {}; + const cam = data.camera || {}; + const ip = data.ip || srv.internal_ip || ''; + const user = data.user || srv.username || ''; + const pass = data.pass || srv.password || ''; + const channel = data.channel || cam.channel_id || 33; + const start = data.start || data.start_time || ''; + const end = data.end || data.end_time || ''; + const httpPort = data.httpPort || srv.internal_port || 80; + const port = data.port || 7681; + const speed = data.speed || 4; + + if (!ip || !user || !pass || !start || !end) { + return { ok: false, message: '缺少必要参数: ip, user, pass, start, end' }; + } + try { + console.log('[Hikvision] receiveTask 解析: ip=%s user=%s channel=%s', ip, user, channel); + + // receiveTask 是强制推送接口,直接覆盖旧任务 + const uniqueCode = data.uniqueCode || ''; + if (uniqueCode) { + const existing = app.db.get('SELECT id, task_id, tmp_file_path, status FROM hik_tasks WHERE unique_code = ?', uniqueCode); + if (existing) { + console.log('[Hikvision] receiveTask 覆盖旧任务:', uniqueCode, existing.status, '→', existing.task_id); + app.db.run('DELETE FROM hik_tasks WHERE unique_code = ?', uniqueCode); + // 删除旧录像文件 + const oldPath = app._resolvePath ? app._resolvePath(existing.tmp_file_path) : existing.tmp_file_path; + try { + if (oldPath && require('fs').existsSync(oldPath)) { + require('fs').unlinkSync(oldPath); + console.log('[Hikvision] receiveTask 已删除旧文件:', oldPath); + } + } catch (_) { /* 文件可能已不存在 */ } + } + } + + // 服务器可指定 taskId + let taskId = data.taskId || ''; + if (taskId) { + const dup = app.db.get('SELECT id FROM hik_tasks WHERE task_id = ?', taskId); + if (dup) return { ok: false, message: '任务ID重复: ' + taskId }; + } else { + taskId = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + } + const prefix = data.outputPrefix || 'hik'; + const now = new Date(); + const dateDir = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(2, '0')}`; + const relOutput = `/${dateDir}/${prefix}_${taskId.slice(-12)}.mp4`; + const videoTime = Math.ceil((new Date(end) - new Date(start)) / 1000); + + app.db.table('hik_tasks').insert({ + task_id: taskId, + unique_code: uniqueCode, + task_params: JSON.stringify({ + ip, port, httpPort, + user, pass, + channel, start, end, + speed, output: relOutput, videoTime + }), + status: 'pending', + retry: 0, + timeout: videoTime + 60, + tmp_file_path: relOutput + }); + + // 有新任务 → 重置空闲计时 + app._lastFetchTime = null; + app._scheduleHikTasks(); + console.log('[Hikvision] receiveTask 创建成功:', taskId, 'uniqueCode:', uniqueCode); + return { ok: true, taskId, message: '任务已接收' }; + } catch (e) { + console.error('[Hikvision] receiveTask 异常:', e.message); + } + } + + /** + * 服务器确认收到任务结果回执(WS 调用) + * 服务器 → 客户端:{ method: "hikvision.taskAck", data: { taskId } } + */ + taskAck(data = {}) { + const taskId = data.taskId; + if (!taskId) return; + try { + this.app.db.run('UPDATE hik_tasks SET pushed = 1, push_retry = 0, push_next_retry_at = \'\' WHERE task_id = ?', taskId); + console.log('[Hikvision] 服务器已确认任务:', taskId); + } catch (e) { + console.error('[Hikvision] taskAck 更新失败:', e.message); + } + // 不返回值,避免回显 + } + + /** + * 发起下载(由 main.js 调用,传入已创建的 taskId 和 task 对象) + */ + startDownload(cfg, taskId, task) { + const { ip, port = 7681, httpPort = 80, user, pass, channel = 33, start, end, speed = 4, output } = cfg; + if (!user || !pass || !start || !end) { + throw new Error('缺少必要参数: user, pass, start, end'); + } + const outPath = output || task.output || `G:/gameauto/recordings/hik_${taskId.slice(-12)}.mp4`; + + task.id = taskId; + task.status = 'starting'; + task.output = outPath; + task.startTime = Date.now(); + task.progress = { chunks: 0, totalBytes: 0, totalMB: 0, speed }; + task.params = { ip, channel, start, end, speed }; + + const params = { ip, port, httpPort, user, pass, channel, start, end, speed, output: outPath }; + + // 下载超时保护(视频时长/速度 + 120秒兜底) + const downloadTimeout = Math.max(120000, ((new Date(end) - new Date(start)) / 1000 / speed + 60) * 1000); + const timeoutTimer = setTimeout(() => { + if (task.status === 'running' || task.status === 'starting' || task.status === 'downloading') { + const err = new Error(`下载超时(${Math.round(downloadTimeout/1000)}s)`); + task._onError?.(err); + } + }, downloadTimeout); + + process.nextTick(() => { + this._doDownload(task, params).then(() => clearTimeout(timeoutTimer)).catch(err => { + clearTimeout(timeoutTimer); + console.error('[Hikvision] 下载失败:', err.message); + task._onError?.(err); + }); + }); + } + + getTaskStatus(taskId) { + return this._activeDownloads.get(taskId) || null; + } + + /** + * 通用登录认证,返回 { token, cookieJar, sessionTag } + */ + async login(ip, httpPort, user, pass) { + const httpBase = `http://${ip}:${httpPort}`; + const NS = { h: 'http://www.hikvision.com/ver20/XMLSchema' }; + const { DOMParser } = await import('@xmldom/xmldom'); + const cookieJar = {}; + + const capsUrl = `${httpBase}/ISAPI/Security/sessionLogin/capabilities?username=${user}&random:${String(Date.now()).slice(-8)}`; + const capsRes = await this._req('GET', capsUrl, null, {}, cookieJar); + const capsXml = new DOMParser().parseFromString(capsRes.body, 'text/xml'); + const getText = (x) => { const el = capsXml.getElementsByTagNameNS(NS.h, x); return el?.length ? el[0].textContent : ''; }; + const sid = getText('sessionID'), challenge = getText('challenge'), salt = getText('salt'); + const itr = parseInt(getText('iterations')) || 1, ver = getText('sessionIDVersion') || '1'; + const vl = getText('isSessionIDValidLongTerm') || 'false', st = getText('isSupportSessionTag') || 'false'; + const irreversible = getText('isIrreversible') === 'true'; + + let digest; + if (irreversible) { + digest = crypto.createHash('sha256').update(user + salt + pass).digest('hex'); + digest = crypto.createHash('sha256').update(digest + challenge).digest('hex'); + for (let i = 2; i < itr; i++) digest = crypto.createHash('sha256').update(digest).digest('hex'); + } else { + digest = crypto.createHash('sha256').update(pass + challenge).digest('hex'); + for (let i = 1; i < itr; i++) digest = crypto.createHash('sha256').update(digest).digest('hex'); + } + + let loginXml; + if (ver === '2') { + loginXml = `${user}${digest}${sid}${vl}2${st}`; + } else { + loginXml = `${user}${digest}${sid}`; + } + const loginRes = await this._req('POST', `${httpBase}/ISAPI/Security/sessionLogin?timeStamp=${Date.now()}`, loginXml, { 'Content-Type': 'text/plain;charset=UTF-8' }, cookieJar); + if (loginRes.statusCode !== 200) throw new Error(`登录失败: ${loginRes.statusCode}`); + + const loginParsed = new DOMParser().parseFromString(loginRes.body, 'text/xml'); + const _gt = (doc, nsUri, name) => { const el = doc.getElementsByTagNameNS(nsUri, name); return el?.length ? el[0].textContent : ''; }; + const sessionTag = _gt(loginParsed, NS.h, 'sessionTag'); + const tokenHeaders = sessionTag ? { 'SessionTag': sessionTag } : {}; + let tokenRes = await this._req('GET', `${httpBase}/ISAPI/Security/token?format=json`, null, tokenHeaders, cookieJar); + if (!tokenRes.body?.includes('"Token"')) { + tokenRes = await this._digestGet(`${httpBase}/ISAPI/Security/token?format=json`, user, pass, true); + } + const token = JSON.parse(tokenRes.body).Token.value; + await new Promise(r => setTimeout(r, 200)); + return { token, cookieJar, sessionTag, httpBase }; + } + + /** + * 获取通道列表 GET /api/hikvision/channels + */ + async getChannels(ip, httpPort, user, pass) { + const { token, cookieJar, sessionTag, httpBase } = await this.login(ip, httpPort, user, pass); + console.log('[Hikvision] getChannels sessionTag:', sessionTag ? 'present' : 'EMPTY', 'cookies:', Object.keys(cookieJar).join(',')); + + // session cookie + SessionTag header 是经过验证的可用组合 + const headers = sessionTag ? { 'SessionTag': sessionTag } : {}; + + // 主路径: ContentMgmt/InputProxy/channels(XML 格式,最通用) + let res = await this._req('GET', `${httpBase}/ISAPI/ContentMgmt/InputProxy/channels`, null, headers, cookieJar); + console.log('[Hikvision] getChannels path1 status:', res.statusCode); + + // 回退路径: System/Video/inputs/channels + if (res.statusCode !== 200) { + res = await this._req('GET', `${httpBase}/ISAPI/System/Video/inputs/channels`, null, headers, cookieJar); + console.log('[Hikvision] getChannels path2 status:', res.statusCode); + } + + if (res.statusCode === 200) { + return await this._parseChannelXmlAsync(res.body); + } + + throw new Error(`获取通道失败: HTTP ${res.statusCode}`); + } + + async _parseChannelXmlAsync(xml) { + const { DOMParser } = await import('@xmldom/xmldom'); + const doc = new DOMParser().parseFromString(xml, 'text/xml'); + const NS = { h: 'http://www.hikvision.com/ver20/XMLSchema' }; + const items = doc.getElementsByTagNameNS(NS.h, 'InputProxyChannel') || doc.getElementsByTagNameNS(NS.h, 'VideoInputChannel'); + const channels = []; + for (let i = 0; i < (items?.length || 0); i++) { + const el = items[i]; + const t = (name) => { const n = el.getElementsByTagNameNS(NS.h, name); return n?.length ? n[0].textContent : ''; }; + // 嵌套节点查找 + const srcInfo = el.getElementsByTagNameNS(NS.h, 'sourceInputPortDescriptor')?.[0]; + const st = (name) => srcInfo ? (srcInfo.getElementsByTagNameNS(NS.h, name)?.[0]?.textContent || '') : ''; + channels.push({ + id: parseInt(t('id')) || i + 1, + name: t('name')?.trim() || st('ipAddress') || `通道${i + 1}`, + ip: st('ipAddress') || '', + port: parseInt(st('managePortNo')) || 0, + model: st('model') || '', + serialNumber: st('serialNumber') || '', + streamType: st('streamType') || t('streamType') || 'main', + enabled: t('enabled') !== 'false' + }); + } + return channels; + } + + /** + * 获取实时流 WebSocket URL GET /api/hikvision/live-url + */ + async getLiveUrl(ip, httpPort, user, pass, port, channel, streamType = 1) { + const channelCode = 100 * (channel || 33) + streamType; + // 海康 SDK 实时流默认使用 RTSP 协议 + return { + rtspUrl: `rtsp://${encodeURIComponent(user)}:${encodeURIComponent(pass)}@${ip}:554/Streaming/Channels/${channelCode}`, + channel: channel || 33, + streamType, + channelCode + }; + } + + async _doDownload(task, p) { + const { ip, port, httpPort = 80, user, pass, channel = 33, start, end, speed = 4, output } = p; + console.log(`[Hikvision] taskId=${task.id} ${ip} ch=${channel}`); + + const httpBase = `http://${ip}:${httpPort}`; + const NS = { h: 'http://www.hikvision.com/ver20/XMLSchema' }; + const { DOMParser } = await import('@xmldom/xmldom'); + const cookieJar = {}; + + // [1] Caps + const capsUrl = `${httpBase}/ISAPI/Security/sessionLogin/capabilities?username=${user}&random:${String(Date.now()).slice(-8)}`; + const capsRes = await this._req('GET', capsUrl, null, {}, cookieJar); + const capsXml = new DOMParser().parseFromString(capsRes.body, 'text/xml'); + const getText = (x) => { const el = capsXml.getElementsByTagNameNS(NS.h, x); return el?.length ? el[0].textContent : ''; }; + const sid = getText('sessionID'); + const challenge = getText('challenge'); + const itr = parseInt(getText('iterations')) || 1; + const salt = getText('salt'); + const ver = getText('sessionIDVersion') || '1'; + const vl = getText('isSessionIDValidLongTerm') || 'false'; + const st = getText('isSupportSessionTag') || 'false'; + const irreversible = getText('isIrreversible') === 'true'; + + // [2] 密码摘要 + let digest; + if (irreversible) { + digest = crypto.createHash('sha256').update(user + salt + pass).digest('hex'); + digest = crypto.createHash('sha256').update(digest + challenge).digest('hex'); + for (let i = 2; i < itr; i++) digest = crypto.createHash('sha256').update(digest).digest('hex'); + } else { + digest = crypto.createHash('sha256').update(pass + challenge).digest('hex'); + for (let i = 1; i < itr; i++) digest = crypto.createHash('sha256').update(digest).digest('hex'); + } + + // [3] Login + let loginXml; + if (ver === '2') { + loginXml = `${user}${digest}${sid}${vl}2${st}`; + } else { + loginXml = `${user}${digest}${sid}`; + } + const loginRes = await this._req('POST', `${httpBase}/ISAPI/Security/sessionLogin?timeStamp=${Date.now()}`, loginXml, { 'Content-Type': 'text/plain;charset=UTF-8' }, cookieJar); + if (!loginRes.body) throw new Error(`登录失败: ${loginRes.statusCode}`); + + const loginParsed = new DOMParser().parseFromString(loginRes.body, 'text/xml'); + const sessionTagEl = loginParsed.getElementsByTagNameNS(NS.h, 'sessionTag'); + const sessionTag = sessionTagEl?.length ? sessionTagEl[0].textContent : ''; + + // [4] Token + const tokenHeaders = sessionTag ? { 'SessionTag': sessionTag } : {}; + let tokenRes = await this._req('GET', `${httpBase}/ISAPI/Security/token?format=json`, null, tokenHeaders, cookieJar); + if (!tokenRes.body?.includes('"Token"')) { + tokenRes = await this._digestGet(`${httpBase}/ISAPI/Security/token?format=json`, user, pass, true); + } + const token = JSON.parse(tokenRes.body).Token.value; + + // [5] WS 下载 + task.status = 'downloading'; + const result = await this._wsDownload({ ip, port, channel, start, end, speed, output, token, task }); + + // [6] 转码 + if (result.total === 0) { + task._onDone?.({ success: false, output, size: 0 }); + return; + } + + const outputBase = output.replace(/\.ps$/i, '').replace(/\.mp4$/i, ''); + let workFile = outputBase + '.ps'; + const mp4Path = outputBase + '.mp4'; + // 如果 _wsDownload 写到 .mp4 后缀的文件,重命名为 .ps 作为转码输入 + if (output.endsWith('.mp4') && fs.existsSync(output)) { + try { fs.renameSync(output, workFile); } catch { /* already .ps */ } + } else if (!fs.existsSync(workFile)) { + workFile = output; // fallback + } + const ffmpegPath = this._findFfmpeg(); + let finalResult; + if (ffmpegPath && fs.existsSync(ffmpegPath) && fs.existsSync(workFile) && fs.statSync(workFile).size > 0) { + let transcoded = false; + const ffRun = (args, timeout) => { + const cmd = `"${ffmpegPath}" ${args} -y`; + try { + execSync(cmd, { timeout, stdio: 'pipe' }); + if (fs.existsSync(mp4Path) && fs.statSync(mp4Path).size > 0) return true; + return false; + } catch (e) { + const stderr = e.stderr?.toString() || ''; + if (stderr) console.error('[Hikvision] ffmpeg stderr:', stderr.slice(-200)); + return false; + } + }; + transcoded = ffRun(`-i "${workFile}" -c:v copy -an "${mp4Path}"`, 60000); + if (!transcoded) transcoded = ffRun(`-i "${workFile}" -c:v libx264 -preset fast -crf 23 -an "${mp4Path}"`, 120000); + if (transcoded) { + const mp4Size = fs.statSync(mp4Path).size; + try { fs.unlinkSync(workFile); } catch { /* */ } + finalResult = { success: true, output: mp4Path, size: mp4Size, duration: result.elapsed, speed, chunks: result.chunks }; + } else { + // 清理可能产生的 0 字节 mp4 + try { if (fs.existsSync(mp4Path) && fs.statSync(mp4Path).size === 0) fs.unlinkSync(mp4Path); } catch { /* */ } + const psSize = fs.existsSync(workFile) ? fs.statSync(workFile).size : 0; + finalResult = { success: true, output: workFile, size: psSize, duration: result.elapsed, speed, rawPs: true }; + } + } else if (fs.existsSync(workFile)) { + finalResult = { success: true, output: workFile, size: fs.statSync(workFile).size, duration: result.elapsed, speed, rawPs: true }; + } else { + finalResult = { success: true, output, size: result.total, duration: result.elapsed, speed, rawPs: true }; + } + + task._onDone?.(finalResult); + console.log(`[Hikvision] 完成: ${finalResult.output} ${(finalResult.size / 1048576).toFixed(1)}MB`); + } + + _wsDownload({ ip, port, channel, start, end, speed, output, token, task }) { + return new Promise((resolve, reject) => { + // 和 Python hik_download.py 完全一致的流程 + const outDir = path.dirname(output); + if (outDir && outDir !== '.') fs.mkdirSync(outDir, { recursive: true }); + + const wsKey = crypto.randomBytes(16).toString('base64'); + const handshake = `GET /?version=1.0&cipherSuites=1&token=${token} HTTP/1.1\r\n` + + `Host: ${ip}:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` + + `Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: ${wsKey}\r\n` + + `Origin: http://127.0.0.1\r\nUser-Agent: Mozilla/5.0\r\n\r\n`; + + const socket = new net.Socket(); + socket.setTimeout(120000); + socket.connect(port, ip, () => socket.write(handshake)); + + // 累积 buffer + Promise 机制模拟 Python 的 sk.recv() + let buf = Buffer.alloc(0); + let waiter = null; + const notify = () => { if (waiter) { const w = waiter; waiter = null; w(); } }; + + // recvBytes(n): 阻塞式读取 n 字节,对应 Python 的 sk.recv(n) + const recvBytes = (n) => new Promise((resolveRecv) => { + const tryRead = () => { + if (buf.length >= n) { + const data = buf.slice(0, n); + buf = buf.slice(n); + resolveRecv(data); + } else { + waiter = tryRead; + } + }; + tryRead(); + }); + + // recvAll(n): 循环读取直到拿到 n 字节 + const recvAll = async (n) => { + const chunks = []; + let remain = n; + while (remain > 0) { + const part = await recvBytes(Math.min(remain, buf.length || remain)); + chunks.push(part); + remain -= part.length; + // 如果 recvBytes 没给够,等下一次 data 事件 + if (remain > 0) await new Promise(r => { waiter = r; }); + } + return Buffer.concat(chunks); + }; + + // ws_recv: 读一个完整 WS 帧,返回 {op, payload} + const wsRecv = async () => { + const h = await recvBytes(2); + const op = h[0] & 0x0F; + let len = h[1] & 0x7F; + if (len === 126) { const ext = await recvBytes(2); len = ext.readUInt16BE(0); } + else if (len === 127) { const ext = await recvBytes(8); len = Number(ext.readBigUInt64BE(0)); } + const payload = await recvAll(len); + return { op, payload }; + }; + + // ws_send: 发一个 WS 帧 + const wsSend = (data, opcode) => { + const payload = typeof data === 'string' ? Buffer.from(data, 'utf-8') : data; + const len = payload.length; + const head = [opcode | 0x80]; + if (len < 126) head.push(len); + else if (len < 65536) { head.push(126); const b = Buffer.alloc(2); b.writeUInt16BE(len); socket.write(Buffer.from(head)); socket.write(b); socket.write(payload); return; } + else { head.push(127); const b = Buffer.alloc(8); b.writeBigUInt64BE(BigInt(len)); socket.write(Buffer.from(head)); socket.write(b); socket.write(payload); return; } + socket.write(Buffer.concat([Buffer.from(head), payload])); + }; + + socket.on('data', (data) => { + buf = Buffer.concat([buf, data]); + notify(); + }); + socket.on('error', (err) => reject(err)); + socket.on('close', () => notify()); // 唤醒可能正在等待的 recv + + // 主流程 + (async () => { + try { + // ===== 步骤 1: 握手 ===== + // 等待 \r\n\r\n 出现(和 Python 的 while + recv(4096) 一样) + while (buf.indexOf('\r\n\r\n') === -1) await new Promise(r => { waiter = r; }); + // 丢弃握手响应数据 + const he = buf.indexOf('\r\n\r\n'); + buf = buf.slice(he + 4); + + // ===== 步骤 2: 发 playback 命令 ===== + const cmd = { sequence: 0, cmd: 'playback', url: `live://${ip}:${port}/${channel}/0`, startTime: start, endTime: end }; + wsSend(JSON.stringify(cmd), 0x01); + + // ===== 步骤 3: 主循环,和 Python 完全一致 ===== + const ws = fs.createWriteStream(output, { highWaterMark: 256 * 1024 }); + let total = 0, chunks = 0, speedSent = false; + const t0 = Date.now(); + + while (true) { + let msg; + try { msg = await wsRecv(); } catch { break; } + if (!msg) break; + + const { op, payload } = msg; + + if (op === 0x09) { + // Ping -> Pong + wsSend(payload, 0x0A); + } else if (op === 0x01) { + // Text frame + try { + const obj = JSON.parse(payload.toString('utf-8')); + const sc = obj.statusCode || 0; + if (sc === 1) continue; // 心跳/确认,忽略 + if (sc !== 0) { console.log('[Hikvision] NVR text response:', JSON.stringify(obj), 'startTime:', start, 'endTime:', end, 'ch:', channel); break; } + } catch { /* non-JSON text */ } + } else if (op === 0x02) { + // Binary frame → 和 Python 一样,收到数据后再发 speed + if (!speedSent && chunks >= 10) { + wsSend(JSON.stringify({ sequence: 0, cmd: 'speed', rate: speed }), 0x01); + speedSent = true; + } + chunks++; total += payload.length; + ws.write(payload); + if (task) { + task.progress.chunks = chunks; + task.progress.totalBytes = total; + task.progress.totalMB = Math.round(total / 1048576 * 10) / 10; + } + } + // 其他 opcode 忽略(Python 也直接 return d 但不处理) + } + + ws.end(); + const elapsed = (Date.now() - t0) / 1000; + resolve({ total, chunks, elapsed }); + } catch (e) { + reject(e); + } + })(); + }); + } + + /** + * WebSocket 实时预览(公网可用,走 7681 端口,绕过 RTSP 554) + * @param {{ ip, port, channel, streamType, token, onData, onError }} opts + * @returns {Promise<{ close: function }>} + */ + _wsLiveView({ ip, port, channel, streamType, token, onData, onError }) { + return new Promise((resolve, reject) => { + const wsKey = crypto.randomBytes(16).toString('base64'); + const handshake = `GET /?version=1.0&cipherSuites=1&token=${token} HTTP/1.1\r\n` + + `Host: ${ip}:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` + + `Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: ${wsKey}\r\n` + + `Origin: http://127.0.0.1\r\nUser-Agent: Mozilla/5.0\r\n\r\n`; + + const socket = new net.Socket(); + socket.setTimeout(300000); + socket.connect(port, ip, () => socket.write(handshake)); + + let buf = Buffer.alloc(0); + let waiter = null; + const notify = () => { if (waiter) { const w = waiter; waiter = null; w(); } }; + + const recvBytes = (n) => new Promise((resolveRecv) => { + const tryRead = () => { + if (buf.length >= n) { const d = buf.slice(0, n); buf = buf.slice(n); resolveRecv(d); } + else { waiter = tryRead; } + }; + tryRead(); + }); + + const recvAll = async (n) => { + const chunks = []; let remain = n; + while (remain > 0) { + if (buf.length > 0) { const take = Math.min(remain, buf.length); chunks.push(buf.slice(0, take)); buf = buf.slice(take); remain -= take; } + if (remain > 0) await new Promise(r => { waiter = r; }); + } + return Buffer.concat(chunks); + }; + + const wsRecv = async () => { + const h = await recvBytes(2); + const op = h[0] & 0x0F; + let len = h[1] & 0x7F; + if (len === 126) { const ext = await recvBytes(2); len = ext.readUInt16BE(0); } + else if (len === 127) { const ext = await recvBytes(8); len = Number(ext.readBigUInt64BE(0)); } + return { op, payload: await recvAll(len) }; + }; + + const wsSend = (data, opcode) => { + const payload = typeof data === 'string' ? Buffer.from(data, 'utf-8') : data; + const len = payload.length; + if (len < 126) { + socket.write(Buffer.concat([Buffer.from([opcode | 0x80, len]), payload])); + } else if (len < 65536) { + const b = Buffer.alloc(2); b.writeUInt16BE(len); + socket.write(Buffer.from([opcode | 0x80, 126])); socket.write(b); socket.write(payload); + } else { + const b = Buffer.alloc(8); b.writeBigUInt64BE(BigInt(len)); + socket.write(Buffer.from([opcode | 0x80, 127])); socket.write(b); socket.write(payload); + } + }; + + socket.on('data', (data) => { buf = Buffer.concat([buf, data]); notify(); }); + socket.on('error', (err) => { onError?.(err); reject(err); }); + socket.on('close', () => notify()); + + let closed = false; + const close = () => { if (closed) return; closed = true; try { socket.destroy(); } catch {} }; + + (async () => { + try { + while (buf.indexOf('\r\n\r\n') === -1) await new Promise(r => { waiter = r; }); + const he = buf.indexOf('\r\n\r\n'); + const respHeader = buf.slice(0, he).toString(); + buf = buf.slice(he + 4); + if (!respHeader.includes('101')) throw new Error('WebSocket 握手失败: ' + respHeader.split('\r\n')[0]); + + const cmd = { sequence: 0, cmd: 'liveview', url: `live://${ip}:${port}/${channel}/${streamType}` }; + wsSend(JSON.stringify(cmd), 0x01); + resolve({ close, socket }); + + while (!closed) { + let msg; try { msg = await wsRecv(); } catch { break; } + if (!msg || closed) break; + const { op, payload } = msg; + if (op === 0x09) { wsSend(payload, 0x0A); } + else if (op === 0x02) { onData?.(payload); } + else if (op === 0x01) { + try { const obj = JSON.parse(payload.toString('utf-8')); if (obj.statusCode && obj.statusCode !== 0 && obj.statusCode !== 1) break; } catch {} + } + } + } catch (e) { onError?.(e); } + finally { close(); } + })(); + }); + } + async _req(method, url, body, headers, cookieJar, binary = false) { + const u = new URL(url); + const bodyBuf = body ? Buffer.from(typeof body === 'string' ? body : body, 'utf-8') : null; + const cookies = Object.entries(cookieJar || {}).map(([k, v]) => `${k}=${v}`).join('; '); + const hdrs = { 'Accept': '*/*', 'User-Agent': 'Mozilla/5.0', ...headers }; + if (cookies) hdrs['Cookie'] = cookies; + if (bodyBuf) hdrs['Content-Length'] = bodyBuf.length; + + return new Promise((resolve, reject) => { + const mod = u.protocol === 'https:' ? https : http; + const req = mod.request({ hostname: u.hostname, port: u.port || 80, path: u.pathname + u.search, method, headers: hdrs, timeout: 10000 }, (res) => { + const ck = []; + res.on('data', c => ck.push(c)); + res.on('end', () => { + req.destroy(); + const raw = Buffer.concat(ck); + const body = binary ? raw : raw.toString('utf-8'); + if (res.headers['set-cookie'] && cookieJar) { + (Array.isArray(res.headers['set-cookie']) ? res.headers['set-cookie'] : [res.headers['set-cookie']]).forEach(sc => { + const m = sc.match(/^([^=;]+)=([^;]*)/); if (m) cookieJar[m[1]] = m[2]; + }); + } + resolve({ statusCode: res.statusCode, headers: res.headers, body }); + }); + }); + req.on('error', reject); + req.on('timeout', () => { req.destroy(); reject(new Error('请求超时')); }); + if (bodyBuf) req.write(bodyBuf); + req.end(); + }); + } + + async _digestGet(url, user, pass, returnBody) { + const u = new URL(url); + const first = await this._req('GET', url, null, {}, {}); + const ah = first.statusCode === 401 ? this._digestParse(first.body, first) : null; + if (!ah && first.statusCode === 200 && returnBody) return first; + if (!ah) throw new Error('无法获取 Digest 认证信息'); + + const ha1 = crypto.createHash('md5').update(`${user}:${ah.realm}:${pass}`).digest('hex'); + const ha2 = crypto.createHash('md5').update(`GET:${u.pathname + u.search}`).digest('hex'); + const nc = '00000001', cnonce = '0a4f113b'; + const resp = crypto.createHash('md5').update(`${ha1}:${ah.nonce}:${nc}:${cnonce}:${ah.qop || 'auth'}:${ha2}`).digest('hex'); + let authStr = `Digest username="${user}", realm="${ah.realm}", nonce="${ah.nonce}", uri="${u.pathname + u.search}", response="${resp}", algorithm=MD5`; + if (ah.qop) authStr += `, qop=${ah.qop}, nc=${nc}, cnonce="${cnonce}"`; + if (ah.opaque) authStr += `, opaque="${ah.opaque}"`; + return this._req('GET', url, null, { 'Authorization': authStr }, {}); + } + + _digestParse(resBody, res) { + const hdr = res?.headers?.['www-authenticate']; + if (hdr) { const m = hdr.match(/^Digest\s+(.+)/i); if (m) return this._digestParams(m[1]); } + if (typeof resBody === 'string') { const m = resBody.match(/WWW-Authenticate:\s*Digest\s+(.+)/i); if (m) return this._digestParams(m[1]); } + return null; + } + + _digestParams(str) { + const p = {}; for (const m of str.matchAll(/(\w+)\s*=\s*(?:"([^"]*)"|([^,\s]+))/g)) p[m[1]] = m[2] !== undefined ? m[2] : m[3]; return p; + } + + _findFfmpeg() { + // 0) Electron 打包后:asar.unpacked 中的 ffmpeg(可执行) + if (process.versions?.electron && process.resourcesPath) { + const unpackedExe = path.join(process.resourcesPath, 'app.asar.unpacked', 'node_modules', '@ffmpeg-installer', 'win32-x64', 'ffmpeg.exe'); + if (fs.existsSync(unpackedExe)) return unpackedExe; + } + // 1) 项目内 npm 包(最可靠,开发/打包都可用) + if (_ffmpegPath && fs.existsSync(_ffmpegPath)) return _ffmpegPath; + // 2) 全局 npm 安装路径 + for (const base of [process.env.APPDATA, process.env.LOCALAPPDATA].filter(Boolean)) { + const p = path.join(base, 'npm', 'node_modules', '@ffmpeg-installer', 'ffmpeg', 'node_modules', '@ffmpeg-installer', 'win32-x64', 'ffmpeg.exe'); + if (fs.existsSync(p)) return p; + } + // 3) 系统 PATH + try { const r = execSync('where ffmpeg 2>nul', { encoding: 'utf-8', stdio: 'pipe' }).trim().split(/\r?\n/).filter(Boolean); if (r.length) return r[0]; } catch { /* */ } + // 4) winget 路径 + try { + const wb = path.join(process.env.LOCALAPPDATA || '', 'Microsoft', 'WinGet', 'Packages'); + for (const d of fs.readdirSync(wb)) { + if (d.startsWith('Gyan.FFmpeg')) { + const p = path.join(wb, d, 'ffmpeg-8.1.2-full_build', 'bin', 'ffmpeg.exe'); + if (fs.existsSync(p)) return p; + } + } + } catch { /* */ } + return null; + } +} + +export default HikvisionService; + + // DEBUG diff --git a/services/printer.js b/services/printer.js index 751c760..9ec50cc 100644 --- a/services/printer.js +++ b/services/printer.js @@ -4,6 +4,8 @@ import fs from 'fs'; import path from 'path'; import { pathToFileURL } from 'url'; import lodopUtil from '../utils/lodop.js'; +import { isRecordingMode } from '../utils/runtime.js'; + // 打印机服务类 class PrinterService extends service { constructor() { @@ -12,8 +14,16 @@ class PrinterService extends service { this.print = this.print.bind(this); // 确保上下文绑定 } + // 录制模式守卫:非 Windows 或纯录制模式拒绝打印相关操作 + _guardRecordingMode() { + if (isRecordingMode(this.config)) { + throw new Error('当前运行在录制模式,不支持打印相关操作'); + } + } + // 读取 Windows 打印服务的打印机列表,返回 Promise async getWindowsPrinters() { + this._guardRecordingMode(); const res = new Promise((resolve, reject) => { const command = `powershell -NoProfile -Command "$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[System.Text.Encoding]::UTF8; Get-CimInstance Win32_Printer | Select-Object Name,WorkOffline | ConvertTo-Json -Compress"`; exec(command, { encoding: 'buffer', maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => { @@ -44,6 +54,7 @@ class PrinterService extends service { }); } print(data) { + this._guardRecordingMode(); console.log("打印服务收到打印请求,数据:", data); const { printerComponents } = this.app; console.log("所有打印组件", printerComponents.components); diff --git a/services/printerComponent.js b/services/printerComponent.js index 0e1ea5a..bab43e4 100644 --- a/services/printerComponent.js +++ b/services/printerComponent.js @@ -1,4 +1,5 @@ import service from '../core/BaseService.js'; +import { isRecordingMode } from '../utils/runtime.js'; class PrinterComponentService extends service { constructor() { @@ -7,8 +8,15 @@ class PrinterComponentService extends service { this.getStatus = this.getStatus.bind(this); } + _guardRecordingMode() { + if (isRecordingMode(this.config)) { + throw new Error('当前运行在录制模式,不支持打印组件操作'); + } + } + // 获取所有打印组件 getAll() { + this._guardRecordingMode(); const { app } = this; if (app && app.printerComponents) { const components = app.printerComponents.getAllPorts(); @@ -21,6 +29,7 @@ class PrinterComponentService extends service { // 获取指定组件状态 getStatus(name) { + this._guardRecordingMode(); const { app } = this; if (app && app.printerComponents) { return app.printerComponents.getStatus(name); diff --git a/services/setting.js b/services/setting.js index ed49d94..5d43e81 100644 --- a/services/setting.js +++ b/services/setting.js @@ -32,15 +32,25 @@ class SettingService extends service { this.restartBackend = this.restartBackend.bind(this); this.setToken = this.setToken.bind(this); this.setInfo = this.setInfo.bind(this); + this.frpcDisconnect = this.frpcDisconnect.bind(this); + this.setCameraOSD = this.setCameraOSD.bind(this); + this.clearCameraOSD = this.clearCameraOSD.bind(this); } // 判断是否已绑定 info() { const {config} = this; + const hik = config.hikvision || {}; return { isBind: !!config.token, name: config.name || '', isService: !!config.isService, - wsPort: Number(config.wsPort) || 3001 + wsPort: Number(config.wsPort) || 17301, + recording: { + isRecording: !!hik.isRecording, + maxStorage: hik.maxStorage || '50GB', + downloadDir: hik.downloadDir || '', + remotePlayUrl: hik.remotePlayUrl || '' + } }; } @@ -69,7 +79,7 @@ class SettingService extends service { async restartBackend(data = {}) { const { app } = this; - const targetWsPort = Number(data.wsPort) || Number(app.config?.wsPort) || 3001; + const targetWsPort = Number(data.wsPort) || Number(app.config?.wsPort) || 17301; if (isManagedBackendRunnerProcess()) { scheduleCurrentProcessExit(); @@ -111,6 +121,12 @@ class SettingService extends service { config.token = ''; configUtil.write(config); app.isBind = false; + + // 停止 frpc + if (app.services.frpc && typeof app.services.frpc.stop === 'function') { + app.services.frpc.stop(); + } + // 解绑后主动请求新绑定码 if (app.wsClient?.status === 'connected') { app.wsClient.send({ method: 'bind.generateCode', data: {} }); @@ -198,10 +214,75 @@ class SettingService extends service { } async setInfo(data) { const { config, app } = this; + // 更新名称 config.name = data.computerInfo?.name || data.name || ''; console.log("设置打印台信息", data); app.info = data; + + // 身份就绪 → 重置空闲计时,立即触发任务拉取 + app._lastFetchTime = null; + app._scheduleHikTasks(); + + // 服务器下发的录制配置 → 覆盖 config.hikvision + if (!config.hikvision) config.hikvision = {}; + const hik = config.hikvision; + if (data.hasOwnProperty('is_recording')) { + hik.isRecording = !!data.is_recording; + } + if (data.hasOwnProperty('recording_size_value')) { + const val = Number(data.recording_size_value) || 0; + const unit = data.recording_size_unit || 'GB'; + hik.maxStorage = val > 0 ? String(val) + unit : hik.maxStorage || '50GB'; + } + if (data.hasOwnProperty('recording_directory')) { + const newDir = data.recording_directory || ''; + const oldDir = hik.downloadDir || ''; + if (newDir && oldDir && newDir !== oldDir) { + // 目录变更,通知前端询问是否迁移 + app.emit('migrationNeeded', { oldDir, newDir }); + } + hik.downloadDir = newDir; + } + // 忽视服务端下发的 remote_play_url,使用本地 /recordings/ 直接访问 + configUtil.write(config); + + // 服务端下发的 frp 配置 → 转换为 frpc 配置并驱动启停 + if (data.frp && app.services.frpc && typeof app.services.frpc.updateConfig === 'function') { + const frp = data.frp; + // 读取运行时实际绑定的 HTTP 端口 + let localPort = this.config.httpPort || 17311; + try { + const { readRuntimeState } = await import('../utils/runtime.js'); + const rt = readRuntimeState(); + if (rt.httpPort) localPort = rt.httpPort; + } catch (_) { /* use config fallback */ } + const frpcCfg = { + enabled: true, + serverAddr: frp.server_addr || '', + serverPort: Number(frp.server_port) || 6005, + authToken: frp.auth_token || '', + token: frp.token || '', + proxies: [{ + name: frp.subdomain || 'printer', + type: 'http', + localIp: '127.0.0.1', + localPort: localPort, + subdomain: frp.subdomain || '' + }] + }; + + if (data.is_recording) { + // 录制开启:强制更新配置并启动 frpc(不比对 key,直接重启) + app.services.frpc.updateConfig(frpcCfg); + } else { + // 录制关闭:停止 frpc + if (typeof app.services.frpc.stop === 'function') { + app.services.frpc.stop(); + } + } + } + // 登录成功后主动全量同步一次组件状态,避免服务端只收到后续增量变化 if (app.wsClient && app.printerComponents) { const allStatus = app.printerComponents.getAllStatus(); @@ -210,7 +291,123 @@ class SettingService extends service { } } - return { ok: true }; + // 通知本地 Web 客户端信息已更新(名称 + 录制配置) + app.emit('infoChanged', { + name: config.name, + isRecording: hik.isRecording, + maxStorage: hik.maxStorage, + downloadDir: hik.downloadDir + }); + + // 不返回值,避免 wsClient 将服务端推送回显为请求 + } + + // 服务端通知断开 frpc(录制电脑被替换时) + frpcDisconnect() { + const { app } = this; + if (app.services.frpc && typeof app.services.frpc.stop === 'function') { + app.services.frpc.stop(); + } + // 不返回值,避免回显 + } + + /** + * 服务端下发 OSD 设置 WS method: camera.osd.set + * data: { rtspUrl, text, x?, y? } + */ + async setCameraOSD(data) { + if (!data || !data.rtspUrl || !data.text) return; + try { + const { setCameraOSD } = await import('../utils/cameraOsd.js'); + await setCameraOSD(data.rtspUrl, data.text, data.x, data.y); + } catch (e) { + console.error('[CameraOSD] set 执行失败:', e.message); + } + } + + /** + * 服务端下发 OSD 清空 WS method: camera.osd.clear + * data: { rtspUrl } + */ + async clearCameraOSD(data) { + if (!data || !data.rtspUrl) return; + try { + const { clearCameraOSD } = await import('../utils/cameraOsd.js'); + await clearCameraOSD(data.rtspUrl); + } catch (e) { + console.error('[CameraOSD] clear 执行失败:', e.message); + } + } + + /** + * 迁移录制文件到新目录 + 更新 DB 路径 + * 前端确认迁移后调用 + */ + async migrateFiles(data = {}) { + const { app } = this; + const oldDirRaw = data.oldDir || ''; + const newDirRaw = data.newDir || ''; + if (!oldDirRaw || !newDirRaw || oldDirRaw === newDirRaw) { + return { ok: false, message: '目录未变化,无需迁移' }; + } + + // 规范化目录(裸盘符 → 路径) + const normDir = (d) => { + d = (d || '').replace(/[\\\/]+$/, ''); + if (/^[A-Za-z]$/.test(d)) d = d + ':/hikvision_recordings'; + return d.replace(/\\/g, '/'); + }; + const oldDir = normDir(oldDirRaw); + const newDir = normDir(newDirRaw); + + const fs = await import('fs'); + const path = await import('path'); + const db = app.db; + + try { + if (!fs.existsSync(newDir)) fs.mkdirSync(newDir, { recursive: true }); + const rows = db.all('SELECT id, output_path FROM hik_downloads WHERE deleted = 0'); + let migrated = 0, skipped = 0; + + for (const row of rows) { + const storedPath = row.output_path || ''; + if (!storedPath) { skipped++; continue; } + + // 解析为绝对路径 + let absPath; + if (storedPath.startsWith('/')) { + // 相对路径:拼接到旧目录 + absPath = path.join(oldDir, storedPath).replace(/\\/g, '/'); + } else { + // 旧格式绝对路径 + absPath = storedPath.replace(/\\/g, '/'); + } + + if (!fs.existsSync(absPath)) { skipped++; continue; } + + // 计算相对于旧目录的路径,拼接到新目录 + let relPath; + if (absPath.startsWith(oldDir + '/')) { + relPath = absPath.slice(oldDir.length); // "/2026/07/26/xxx.mp4" + } else { + relPath = '/' + path.basename(absPath); + } + const newAbsPath = (newDir + relPath).replace(/\\/g, '/'); + + // 复制文件 + const newParent = path.dirname(newAbsPath); + if (!fs.existsSync(newParent)) fs.mkdirSync(newParent, { recursive: true }); + fs.copyFileSync(absPath, newAbsPath); + + // 更新 DB 为相对路径 + db.run('UPDATE hik_downloads SET output_path = ? WHERE id = ?', relPath, row.id); + migrated++; + } + + return { ok: true, message: `迁移完成:${migrated} 个文件,跳过 ${skipped} 个`, migrated, skipped }; + } catch (e) { + return { ok: false, message: `迁移失败:${e.message}` }; + } } } diff --git a/test_batch.mjs b/test_batch.mjs new file mode 100644 index 0000000..7cb0d48 --- /dev/null +++ b/test_batch.mjs @@ -0,0 +1,46 @@ +import http from 'http'; +const PORT = 17311; + +async function callApi(path, options = {}) { + const m = options.method || 'GET'; + const body = options.body ? JSON.stringify(options.body) : null; + const h = body ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } : {}; + return new Promise((resolve, reject) => { + const req = http.request(`http://127.0.0.1:${PORT}${path}`, { method: m, headers: h }, (res) => { + const c = []; res.on('data', x => c.push(x)); + res.on('end', () => { try { resolve(JSON.parse(Buffer.concat(c).toString('utf-8'))); } catch { resolve({}); } }); + }); + req.on('error', reject); + if (body) req.write(body); + req.end(); + }); +} + +// 连续提交 4 个任务 +const tasks = []; +for (let i = 1; i <= 4; i++) { + const body = { + ip: '192.168.8.241', port: 7681, httpPort: 80, + user: 'admin', pass: 'ky666888', channel: 33, + start: '2026-07-08T10:00:00', end: '2026-07-08T10:00:10', + speed: 4, outputPrefix: `batch${i}` + }; + const r = await callApi('/api/hikvision/download', { method: 'POST', body }); + console.log(`#${i} ${r.taskId.slice(-10)} ${r.status}`); + tasks.push(r.taskId); +} + +console.log('\n=== 调度状态(并发上限 2) ==='); +const start = Date.now(); +for (let round = 0; round < 60; round++) { + await new Promise(r => setTimeout(r, 1500)); + const list = await callApi('/api/hikvision/tasks?pageSize=10'); + const t = ((Date.now() - start) / 1000).toFixed(0) + 's'; + const statuses = (list.data?.list || []).filter(x => tasks.includes(x.task_id)) + .map(x => `${x.task_id.slice(-8)}:${x.status}`).join(' | '); + console.log(`[${t}] ${statuses}`); + + const running = (list.data?.list || []).filter(x => tasks.includes(x.task_id) && x.status === 'running').length; + const done = (list.data?.list || []).filter(x => tasks.includes(x.task_id) && (x.status === 'completed' || x.status === 'done')).length; + if (done === 4) { console.log('\n全部完成!'); break; } +} diff --git a/test_cfg.json b/test_cfg.json new file mode 100644 index 0000000..d62dea5 --- /dev/null +++ b/test_cfg.json @@ -0,0 +1 @@ +{"ip":"192.168.8.241","port":7681,"httpPort":80,"user":"admin","pass":"ky666888","channel":33,"start":"2026-07-01T08:00:00","end":"2026-07-01T08:05:00","speed":4,"output":"G:/gameauto/recordings/output.ps"} diff --git a/test_channels.mjs b/test_channels.mjs new file mode 100644 index 0000000..96f2ee2 --- /dev/null +++ b/test_channels.mjs @@ -0,0 +1,92 @@ +import crypto from 'crypto'; +import http from 'http'; +import { DOMParser } from '@xmldom/xmldom'; + +const _req = (method, url, body, headers, cookieJar) => new Promise((resolve, reject) => { + const u = new URL(url); + const bodyBuf = body ? Buffer.from(typeof body === 'string' ? body : body, 'utf-8') : null; + const cookies = Object.entries(cookieJar || {}).map(([k, v]) => `${k}=${v}`).join('; '); + const hdrs = { 'Accept': '*/*', 'User-Agent': 'Mozilla/5.0', ...headers }; + if (cookies) hdrs['Cookie'] = cookies; + if (bodyBuf) hdrs['Content-Length'] = bodyBuf.length; + const req = http.request({ hostname: u.hostname, port: u.port || 80, path: u.pathname + u.search, method, headers: hdrs, timeout: 10000 }, (res) => { + const ck = []; + res.on('data', c => ck.push(c)); + res.on('end', () => { + req.destroy(); + const body = Buffer.concat(ck).toString('utf-8'); + if (res.headers['set-cookie'] && cookieJar) { + (Array.isArray(res.headers['set-cookie']) ? res.headers['set-cookie'] : [res.headers['set-cookie']]).forEach(sc => { + const m = sc.match(/^([^=;]+)=([^;]*)/); if (m) cookieJar[m[1]] = m[2]; + }); + } + resolve({ statusCode: res.statusCode, headers: res.headers, body }); + }); + }); + req.on('error', reject); + req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); }); + if (bodyBuf) req.write(bodyBuf); + req.end(); +}); + +const ip = '192.168.8.241', httpPort = 80, user = 'admin', pass = 'ky666888'; +const httpBase = `http://${ip}:${httpPort}`; +const ns = { h: 'http://www.hikvision.com/ver20/XMLSchema' }; +const cookieJar = {}; + +// [1] Caps +const capsUrl = `${httpBase}/ISAPI/Security/sessionLogin/capabilities?username=${user}&random:12345678`; +const capsRes = await _req('GET', capsUrl, null, {}, cookieJar); +console.log('caps:', capsRes.statusCode); +const capsXml = new DOMParser().parseFromString(capsRes.body, 'text/xml'); +const gt = (x) => { const el = capsXml.getElementsByTagNameNS(ns.h, x); return el?.length ? el[0].textContent : ''; }; +const sid = gt('sessionID'), ch = gt('challenge'), salt = gt('salt'); +const itr = parseInt(gt('iterations')) || 1, ver = gt('sessionIDVersion') || '1'; +const vl = gt('isSessionIDValidLongTerm') || 'false', st = gt('isSupportSessionTag') || 'false'; +const irr = gt('isIrreversible') === 'true'; + +// [2] Password +let digest; +if (irr) { + digest = crypto.createHash('sha256').update(user + salt + pass).digest('hex'); + digest = crypto.createHash('sha256').update(digest + ch).digest('hex'); + for (let i = 2; i < itr; i++) digest = crypto.createHash('sha256').update(digest).digest('hex'); +} else { + digest = crypto.createHash('sha256').update(pass + ch).digest('hex'); + for (let i = 1; i < itr; i++) digest = crypto.createHash('sha256').update(digest).digest('hex'); +} + +// [3] Login +let loginXml; +if (ver === '2') { + loginXml = `${user}${digest}${sid}${vl}2${st}`; +} else { + loginXml = `${user}${digest}${sid}`; +} +const loginRes = await _req('POST', `${httpBase}/ISAPI/Security/sessionLogin?timeStamp=${Date.now()}`, loginXml, { 'Content-Type': 'text/plain;charset=UTF-8' }, cookieJar); +console.log('login:', loginRes.statusCode, 'set-cookie:', JSON.stringify(loginRes.headers['set-cookie'])); +console.log('cookieJar:', JSON.stringify(cookieJar)); + +const loginParsed = new DOMParser().parseFromString(loginRes.body, 'text/xml'); +const sessionTag = (() => { const el = loginParsed.getElementsByTagNameNS(ns.h, 'sessionTag'); return el?.length ? el[0].textContent : ''; })(); +console.log('sessionTag:', sessionTag?.slice(0, 16) + '...'); + +// [4] Test channels with cookie + SessionTag +const headers = sessionTag ? { 'SessionTag': sessionTag } : {}; +console.log('\n--- Request channels with headers:', JSON.stringify(headers), 'cookies:', JSON.stringify(cookieJar)); +const channelsRes = await _req('GET', `${httpBase}/ISAPI/ContentMgmt/InputProxy/channels`, null, headers, cookieJar); +console.log('channels status:', channelsRes.statusCode); +console.log('channels body:', channelsRes.body.slice(0, 800)); + +// 测试解析 +console.log('\n--- Parse test ---'); +const doc = new DOMParser().parseFromString(channelsRes.body, 'text/xml'); +const items = doc.getElementsByTagNameNS(ns.h, 'InputProxyChannel'); +console.log('items found:', items?.length || 0); +if (items) { + for (let i = 0; i < Math.min(items.length, 5); i++) { + const el = items[i]; + const t = (name) => { const n = el.getElementsByTagNameNS(ns.h, name); return n?.length ? n[0].textContent : ''; }; + console.log(` [${i}] id=${t('id')} name="${t('name')}" ip="${el.getElementsByTagNameNS(ns.h, 'ipAddress')?.[0]?.textContent || ''}"`); + } +} diff --git a/test_frame.jpg b/test_frame.jpg new file mode 100644 index 0000000..8a2a5b5 Binary files /dev/null and b/test_frame.jpg differ diff --git a/test_hik_storage.mjs b/test_hik_storage.mjs new file mode 100644 index 0000000..9f91042 --- /dev/null +++ b/test_hik_storage.mjs @@ -0,0 +1,44 @@ +import http from 'http'; +const PORT = 17311; + +async function callApi(path, options = {}) { + const method = options.method || 'GET'; + const body = options.body ? JSON.stringify(options.body) : null; + const headers = body ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } : {}; + return new Promise((resolve, reject) => { + const req = http.request(`http://127.0.0.1:${PORT}${path}`, { method, headers }, (res) => { + const chunks = []; + res.on('data', c => chunks.push(c)); + res.on('end', () => { try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf-8'))); } catch { resolve({}); } }); + }); + req.on('error', reject); + if (body) req.write(body); + req.end(); + }); +} + +const body = { + ip: '192.168.8.241', port: 7681, httpPort: 80, + user: 'admin', pass: 'ky666888', channel: 33, + start: '2026-07-08T10:00:00', end: '2026-07-08T10:04:00', + speed: 4, outputPrefix: 'test_4min' +}; + +const dlRes = await callApi('/api/hikvision/download', { method: 'POST', body }); +console.log('taskId:', dlRes.taskId, dlRes.status); + +const start = Date.now(); +for (let i = 0; i < 300; i++) { + await new Promise(r => setTimeout(r, 2000)); + const s = await callApi(`/api/hikvision/status?taskId=${dlRes.taskId}`); + const t = ((Date.now() - start) / 1000).toFixed(0); + if (s.status === 'done' || s.status === 'completed') { + console.log(`[${t}s] ✅ ${(s.result?.size/1024/1024).toFixed(1)}MB ${s.result?.output}`); + break; + } + if (s.status === 'failed' || s.status === 'timeout') { + console.log(`[${t}s] ❌ ${s.status}: ${s.message}`); + break; + } + console.log(`[${t}s] ${s.status} chunks=${s.progress?.chunks || 0}`); +} diff --git a/utils/cameraOsd.js b/utils/cameraOsd.js new file mode 100644 index 0000000..d4f37fa --- /dev/null +++ b/utils/cameraOsd.js @@ -0,0 +1,175 @@ +/** + * 摄像头 OSD(屏幕叠加文字)处理工具 + * + * 用法: + * import { setCameraOSD } from '../utils/cameraOsd.js'; + * await setCameraOSD('rtsp://admin:pass@192.168.1.100:554/stream', '通道名称'); + */ + +import { createRequire } from 'module'; +import { promisify } from 'util'; +import fs from 'fs'; +import path from 'path'; +import os from 'os'; + +const require = createRequire(import.meta.url); +const { Cam } = require('onvif'); + +// ─── 文件日志 ─── +function _logDir() { + const appData = process.env.ProgramData || path.join(process.env.SystemDrive || 'C:', 'ProgramData'); + const dir = path.join(appData, 'printServer'); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + return dir; +} +function _writeLog(level, ...args) { + const msg = args.join(' '); + console.log(`[CameraOSD] ${msg}`); + try { + const ts = new Date().toISOString().replace('T', ' ').substring(0, 19); + fs.appendFileSync(path.join(_logDir(), 'cameraOsd.log'), `[${ts}] [${level}] ${msg}\n`, 'utf-8'); + } catch (_) { /* ignore */ } +} +const _log = (...a) => _writeLog('INFO', ...a); +const _err = (...a) => _writeLog('ERR', ...a); + +/** + * 解析 RTSP URL 提取 [用户名, 密码, 主机] + * 格式: rtsp://username:password@host:port/path + */ +function extractRTSPInfo(rtspUrl) { + const match = rtspUrl.match(/^rtsp:\/\/([^:]+):(.+)@([^:/]+)/); + if (!match) { + throw new Error('RTSP URL 格式无效,期望: rtsp://用户名:密码@主机:端口/路径'); + } + return { username: match[1], password: match[2], host: match[3] }; +} + +/** + * 给摄像头设置 OSD 文字 + * @param {string} rtspUrl - 摄像头 RTSP 地址 + * @param {string} osdText - 要显示的 OSD 文字 + * @returns {Promise<{ok: boolean, message: string}>} + */ +export async function setCameraOSD(rtspUrl, osdText, posX = -0.9, posY = 0.8) { + return _osdAction(rtspUrl, osdText, posX, posY, 'replace'); +} + +/** + * 清空 OSD(删除全部文本 OSD,不创建新的) + */ +export async function clearCameraOSD(rtspUrl) { + return _osdAction(rtspUrl, '', 0, 0, 'clear'); +} + +/** + * OSD 核心操作 + * @param {string} mode - 'replace'=删旧建新, 'append'=叠加追加, 'clear'=只删不建 + */ +async function _osdAction(rtspUrl, osdText, posX, posY, mode) { + _log('收到 OSD 请求, rtspUrl:', rtspUrl.replace(/:[^:@]+@/, ':****@'), 'text:', osdText, 'pos:', posX, posY, 'mode:', mode); + const info = extractRTSPInfo(rtspUrl); + _log('连接摄像头:', info.host, '用户:', info.username); + + return new Promise((resolve) => { + new Cam({ + hostname: info.host, + username: info.username, + password: info.password, + port: 2020, + timeout: 10000, + preserveAddress: true + }, async function (err) { + if (err) { + _err('连接失败:', err.message); + return resolve({ ok: false, message: `连接摄像头失败: ${err.message}` }); + } + + const cam = this; + try { + // 转为 Promise 风格 + const getOSDs = promisify(cam.getOSDs).bind(cam); + const createOSD = promisify(cam.createOSD).bind(cam); + const setOSD = promisify(cam.setOSD).bind(cam); + + const token = cam.defaultProfile.videoSourceConfiguration.$.token; + _log('videoSourceConfigurationToken:', token); + + // 检查是否已有文本 OSD(过滤掉时间 OSD 等非 Plain 类型) + let osdList = []; + try { + const resp = await getOSDs(token); + osdList = resp?.getOSDsResponse?.OSDs || []; + _log('已有 OSD 数量:', osdList.length, JSON.stringify(osdList)); + } catch (e) { + _err('获取已有 OSD 失败:', e.message); + } + + // 只取 Plain 类型的文本 OSD token + const textOSD = osdList.find(o => o.textString?.type === 'Plain'); + const osdToken = textOSD?.$?.token; + const createOptions = { + videoSourceConfigurationToken: token, + plaintext: osdText, + position: { x: posX, y: posY } + }; + + if (mode === 'clear') { + // clear 模式:只删不建 + _log('clear 模式,删除所有文本 OSD'); + const deleteOSD = promisify(cam.deleteOSD).bind(cam); + for (const o of osdList.filter(x => x.textString?.type === 'Plain')) { + try { await deleteOSD(o.$.token); _log('已删除:', o.$.token); } catch (e) { _err('删除失败:', e.message); } + } + _log('clear 完成'); + resolve({ ok: true, message: 'OSD 已清空', count: 0 }); + return; + } + + // replace 模式:删除已有文本 OSD,再创建新的 + if (osdToken) { + _log('replace 模式,删除已有文本 OSD'); + const deleteOSD = promisify(cam.deleteOSD).bind(cam); + for (const o of osdList.filter(x => x.textString?.type === 'Plain')) { + try { await deleteOSD(o.$.token); _log('已删除:', o.$.token); } catch (e) { _err('删除失败:', e.message); } + } + } + + // 创建新 OSD,最多重试 3 次 + _log('创建新 OSD, text:', osdText, 'pos:', posX, posY); + for (let i = 0; i < 3; i++) { + try { + await createOSD(createOptions); + _log('第', i + 1, '次尝试成功'); + break; + } catch (e) { + _err('第', i + 1, '次尝试失败:', e.message); + if (i === 2) throw e; + } + } + + // 验证写入 + const verifyResp = await getOSDs(token); + const verifyList = verifyResp?.getOSDsResponse?.OSDs || []; + const textOSDs = verifyList.filter(o => o.textString?.type === 'Plain'); + const verifyTexts = textOSDs.map(o => o.textString?.plainText || '').join(','); + _log('验证读取 OSD: 共', textOSDs.length, '个文本, texts=[', verifyTexts, ']'); + + const found = textOSDs.some(o => { + const txt = String(o?.textString?.plainText ?? ''); + return txt === String(osdText) || txt.includes(String(osdText)); + }); + if (found) { + _log('OK OSD 写入成功:', osdText); + resolve({ ok: true, message: 'OSD 设置成功: ' + osdText, count: textOSDs.length }); + } else { + _err('FAIL OSD 写入失败: 期望="' + osdText + '" 实际=[' + verifyTexts + ']'); + resolve({ ok: false, message: 'OSD 写入验证失败' }); + } + } catch (e) { + _err('操作失败:', e.message); + resolve({ ok: false, message: `OSD 操作失败: ${e.message}` }); + } + }); + }); +} diff --git a/utils/db.js b/utils/db.js new file mode 100644 index 0000000..430620e --- /dev/null +++ b/utils/db.js @@ -0,0 +1,342 @@ +/** + * SQLite 通用轻量存储工具 + * + * 特性: + * - 自动创建 DB 文件在应用数据目录(开发态在项目根,打包态在 ProgramData/printServer) + * - WAL 模式,支持并发读写 + * - 同步 API,简单直接 + * - 表辅助器(TableHelper):insert / update / delete / find / count + * + * 用法: + * import db from '../utils/db.js'; + * db.exec('CREATE TABLE IF NOT EXISTS logs (id INTEGER PRIMARY KEY AUTOINCREMENT, msg TEXT, ts INTEGER)'); + * db.table('logs').insert({ msg: 'hello', ts: Date.now() }); + * const rows = db.table('logs').where({ msg: 'hello' }).orderBy('ts', 'desc').limit(10).find(); + */ + +import Database from 'better-sqlite3'; +import path from 'path'; +import fs from 'fs'; +import { getAppDataDir, isElectronRuntime } from './runtime.js'; + +let _instance = null; + +class DB { + constructor() { + if (_instance) return _instance; + _instance = this; + + this._db = null; + this._stmtCache = new Map(); + this._open(); + } + + // ─── 生命周期 ─── + + _open() { + const dir = getAppDataDir(); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + const dbPath = path.join(dir, 'printserver.db'); + this._db = new Database(dbPath); + this._db.pragma('journal_mode = WAL'); + this._db.pragma('foreign_keys = ON'); + console.log('[DB] 已打开:', dbPath); + } + + /** + * 关闭数据库(进程退出前调用) + */ + close() { + if (this._db) { + this._stmtCache.clear(); + this._db.close(); + this._db = null; + _instance = null; + console.log('[DB] 已关闭'); + } + } + + /** + * 获取底层 better-sqlite3 实例(高级用法) + */ + raw() { + return this._db; + } + + // ─── 原生 SQL ─── + + /** + * 执行一条或多条 SQL(不返回行) + */ + exec(sql) { + return this._db.exec(sql); + } + + /** + * 执行 INSERT / UPDATE / DELETE / DDL + * @returns {{ changes: number, lastInsertRowid: number|bigint }} + */ + run(sql, ...params) { + const stmt = this._prepare(sql); + return stmt.run(...params); + } + + /** + * 查询单行 + * @returns {object|undefined} + */ + get(sql, ...params) { + const stmt = this._prepare(sql); + return stmt.get(...params); + } + + /** + * 查询多行 + * @returns {object[]} + */ + all(sql, ...params) { + const stmt = this._prepare(sql); + return stmt.all(...params); + } + + /** + * 迭代查询(大数据集) + */ + iterate(sql, ...params) { + const stmt = this._prepare(sql); + return stmt.iterate(...params); + } + + /** + * 事务包装 + */ + transaction(fn) { + const txn = this._db.transaction(fn); + return txn(); + } + + // ─── 表辅助器 ─── + + /** + * 获取表辅助器,提供链式 CRUD + * @param {string} tableName + * @returns {TableHelper} + */ + table(tableName) { + return new TableHelper(this, tableName); + } + + // ─── 内部 ─── + + _prepare(sql) { + let stmt = this._stmtCache.get(sql); + if (!stmt) { + stmt = this._db.prepare(sql); + this._stmtCache.set(sql, stmt); + } + return stmt; + } +} + +// ─── 表辅助器 ─── + +class TableHelper { + constructor(db, tableName) { + this._db = db; + this._table = tableName; + this._where = []; + this._whereParams = []; + this._order = ''; + this._limitVal = null; + this._offsetVal = null; + this._selectCols = '*'; + } + + /** + * 等值条件:.where({ name: 'foo', status: 1 }) + */ + where(conditions) { + for (const [key, value] of Object.entries(conditions)) { + this._where.push(`${key} = ?`); + this._whereParams.push(value); + } + return this; + } + + /** + * 自定义条件:.whereRaw('age > ? AND name LIKE ?', 18, '%张%') + */ + whereRaw(clause, ...params) { + this._where.push(clause); + this._whereParams.push(...params); + return this; + } + + /** + * 排序:.orderBy('id', 'desc') 或 .orderBy('name') + */ + orderBy(column, direction = 'asc') { + const dir = direction.toUpperCase() === 'DESC' ? 'DESC' : 'ASC'; + this._order = `ORDER BY ${column} ${dir}`; + return this; + } + + /** + * 限制行数 + */ + limit(n) { + this._limitVal = n; + return this; + } + + /** + * 偏移 + */ + offset(n) { + this._offsetVal = n; + return this; + } + + /** + * 指定查询列:.select('id, name') + */ + select(cols) { + this._selectCols = cols; + return this; + } + + // ─── 查询方法 ─── + + /** + * 查询多行 + */ + find() { + const { sql, params } = this._buildSelect(); + return this._db.all(sql, ...params); + } + + /** + * 查询单行 + */ + first() { + this._limitVal = 1; + const rows = this.find(); + return rows[0] || null; + } + + /** + * 计数 + */ + count() { + let whereClause = ''; + const params = [...this._whereParams]; + if (this._where.length > 0) { + whereClause = 'WHERE ' + this._where.join(' AND '); + } + const sql = `SELECT COUNT(*) as cnt FROM ${this._table} ${whereClause}`; + const row = this._db.get(sql, ...params); + return row ? row.cnt : 0; + } + + /** + * 是否存在 + */ + exists() { + return this.count() > 0; + } + + // ─── 写入方法 ─── + + /** + * 插入一行 + * @returns {{ changes: number, lastInsertRowid: number|bigint }} + */ + insert(data) { + const keys = Object.keys(data); + const values = Object.values(data); + const placeholders = keys.map(() => '?').join(', '); + const sql = `INSERT INTO ${this._table} (${keys.join(', ')}) VALUES (${placeholders})`; + return this._db.run(sql, ...values); + } + + /** + * 批量插入 + */ + insertMany(rows) { + if (rows.length === 0) return 0; + const keys = Object.keys(rows[0]); + const placeholders = keys.map(() => '?').join(', '); + const sql = `INSERT INTO ${this._table} (${keys.join(', ')}) VALUES (${placeholders})`; + const stmt = this._db._prepare(sql); + const insertAll = this._db.raw().transaction((items) => { + for (const row of items) { + stmt.run(...keys.map(k => row[k])); + } + }); + insertAll(rows); + return rows.length; + } + + /** + * 更新满足条件的行 + */ + update(data) { + const setClauses = Object.keys(data).map(k => `${k} = ?`); + const setParams = Object.values(data); + const whereClause = this._where.length > 0 ? 'WHERE ' + this._where.join(' AND ') : ''; + const sql = `UPDATE ${this._table} SET ${setClauses.join(', ')} ${whereClause}`; + return this._db.run(sql, ...setParams, ...this._whereParams); + } + + /** + * 删除满足条件的行 + */ + delete() { + const whereClause = this._where.length > 0 ? 'WHERE ' + this._where.join(' AND ') : ''; + const sql = `DELETE FROM ${this._table} ${whereClause}`; + return this._db.run(sql, ...this._whereParams); + } + + /** + * UPSERT:存在则更新,不存在则插入 + * 需要表有 UNIQUE 约束 + */ + upsert(data, conflictColumns) { + const keys = Object.keys(data); + const values = Object.values(data); + const placeholders = keys.map(() => '?').join(', '); + const updates = keys.map(k => `${k} = excluded.${k}`).join(', '); + const conflict = conflictColumns ? conflictColumns.join(', ') : keys[0]; + const sql = `INSERT INTO ${this._table} (${keys.join(', ')}) VALUES (${placeholders}) + ON CONFLICT(${conflict}) DO UPDATE SET ${updates}`; + return this._db.run(sql, ...values); + } + + // ─── 内部 ─── + + _buildSelect() { + let sql = `SELECT ${this._selectCols} FROM ${this._table}`; + const params = [...this._whereParams]; + + if (this._where.length > 0) { + sql += ' WHERE ' + this._where.join(' AND '); + } + if (this._order) { + sql += ' ' + this._order; + } + if (this._limitVal !== null) { + sql += ' LIMIT ?'; + params.push(this._limitVal); + } + if (this._offsetVal !== null) { + sql += ' OFFSET ?'; + params.push(this._offsetVal); + } + + return { sql, params }; + } +} + +export default new DB(); diff --git a/utils/runtime.js b/utils/runtime.js index 59382c3..bd181af 100644 --- a/utils/runtime.js +++ b/utils/runtime.js @@ -14,6 +14,30 @@ export function isPackagedElectron() { return isElectronRuntime() && !process.defaultApp; } +/** + * 判断当前是否为"录制专用"模式 + * - Linux/非 Windows 平台:强制录制模式(无打印能力) + * - config.mode === 'recording':显式指定录制模式 + * - config.mode === 'minimal':最简模式(仅 HTTP+WS) + */ +export function isRecordingMode(config) { + // 非 Windows 平台强制录制模式 + if (process.platform !== 'win32') { + return true; + } + // Windows 平台按配置决定 + const mode = (config && config.mode) || 'full'; + return mode === 'recording' || mode === 'minimal'; +} + +/** + * 获取当前运行模式标签 + */ +export function getRunMode(config) { + if (process.platform !== 'win32') return 'recording'; + return (config && config.mode) || 'full'; +} + export function getProjectRoot() { return projectRoot; } @@ -106,4 +130,58 @@ export function ensureWritableConfigFile() { } return writableConfigPath; +} + +/** + * 运行时状态文件路径(记录后端实际选中的端口等动态信息) + */ +export function getRuntimeStatePath() { + if (!isElectronRuntime()) { + return path.join(projectRoot, 'runtime.json'); + } + return path.join(getAppDataDir(), 'runtime.json'); +} + +export function readRuntimeState() { + try { + const p = getRuntimeStatePath(); + if (fs.existsSync(p)) { + return JSON.parse(fs.readFileSync(p, 'utf-8')); + } + } catch (_) { /* ignore */ } + return {}; +} + +export function writeRuntimeState(state) { + try { + const p = getRuntimeStatePath(); + fs.writeFileSync(p, JSON.stringify(state, null, 2), 'utf-8'); + } catch (_) { /* ignore */ } +} + +/** + * 解析端口配置,支持单端口(Number)或端口数组([Number]) + * @param {number|number[]} raw + * @returns {number[]} + */ +export function resolvePortCandidates(raw) { + if (Array.isArray(raw)) { + return raw.filter(p => Number.isFinite(p) && p > 0 && p < 65536); + } + if (Number.isFinite(raw) && raw > 0 && raw < 65536) { + return [raw]; + } + return []; +} + +/** + * 从服务构造函数参数中提取安全端口候选(兼容旧字段名与新字段名) + */ +export function extractPortCandidates(config, key, fallbackKey, defaultPorts) { + const raw = config[key] || config[fallbackKey]; + const candidates = resolvePortCandidates(raw); + if (candidates.length > 0) { + return candidates; + } + return resolvePortCandidates(defaultPorts); } \ No newline at end of file diff --git a/views/index.html b/views/index.html index ca76f9a..ac13336 100644 --- a/views/index.html +++ b/views/index.html @@ -542,6 +542,7 @@
+
@@ -590,6 +591,98 @@ +
+
+
+
+

海康 NVR 下载任务

+
+
+ 存储 {{ formatBytes(hikStorageUsed) }} / {{ formatBytes(hikStorageMax) }} +
+ +
+
暂无任务
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
任务ID状态通道时长倍速输出文件重试创建时间录制开始录制结束操作
{{ t.unique_code || '-' }} + {{ taskStatusText(t.status) }} +
+
+
+
{{ t.ip || '-' }}
ch{{ t.channel }}
{{ fmtDuration(t.videoTime) }}{{ t.speed }}x +
{{ getFileName(t.output) }}
+
{{ formatBytes((t.result && t.result.size) || 0) }}
+
{{ t.error_message }}
+
-
+
{{ t.retry || 0 }}{{ (t.created_at || '').substring(0,16) || '-' }}{{ (t.rec_start || '').substring(0,16) || '-' }}{{ (t.rec_end || '').substring(0,16) || '-' }} + + + +
+
+ +
+ + + 第 + + / {{ hikTotalPages }} 页(共 {{ hikTotal }} 条) + + + +
+
+
+
+
+

录像预览

+
+ +
视频加载失败
+
+ {{ getFileName(previewFile.output_path) }}
+ {{ formatBytes(previewFile.file_size || 0) }} · {{ previewFile.duration || 0 }}s +
+
+
+
+
+
+

应用更新

@@ -613,6 +706,36 @@
+ +
+

录制设置(由服务器下发)

+
+ + {{ recording.isRecording ? '已启用' : '未启用' }} +
+
+ + {{ recording.maxStorage || '-' }} +
+
+ + {{ recording.downloadDir || '-' }} +
+
+ + {{ recording.remotePlayUrl }} +
+
+
+

内网穿透(frpc)

+
+ + {{ frpcStatusText }} +
+
+ + frpc 配置由服务器下发,自动管理启停 +
@@ -633,6 +756,10 @@ +
+ + 穿透:{{ frpcStatusText }} +
@@ -688,6 +815,35 @@ 'connected': { title: '已连接', color: 'green' }, 'error': { title: '连接错误', color: 'red' }, }, + // 海康录像回放 + hikFiles: [], + hikFilePage: 1, + hikFileTotal: 0, + hikFileTotalPages: 1, + hikStorageUsed: 0, + hikStorageMax: 0, + hikStoragePercent: 0, + previewFile: null, + previewError: false, + // 海康任务 + hikTasks: [], + hikPage: 1, + hikPageSize: 20, + hikTotal: 0, + hikJumpPage: 1, + // 海康配置 + hikConfig: { downloadDir: '', maxStorageNum: 50, maxStorageUnit: 'GB', circularRecording: true }, + hikConfigSaving: false, + hikConfigSaved: false, + // 服务器下发的录制配置(只读) + recording: { + isRecording: false, + maxStorage: '-', + downloadDir: '-', + remotePlayUrl: '' + }, + // frpc 内网穿透状态 + frpcStatus: 'stopped', }, computed: { updateProgressPercent() { @@ -707,6 +863,17 @@ failed: '失败' }; return map[this.updateState.status] || '空闲'; + }, + frpcStatusText() { + const map = { stopped: '未启动', starting: '启动中', running: '已连接', error: '异常' }; + return map[this.frpcStatus] || this.frpcStatus; + }, + frpcStatusColor() { + const map = { stopped: '#888', starting: '#f59f00', running: '#107c10', error: '#c42b1c' }; + return map[this.frpcStatus] || '#888'; + }, + hikTotalPages() { + return Math.max(1, Math.ceil(this.hikTotal / this.hikPageSize)); } }, methods: { @@ -726,6 +893,159 @@ return `${size.toFixed(idx === 0 ? 0 : 2)} ${units[idx]}`; }, + getFileName(filePath) { + if (!filePath) return ''; + return filePath.replace(/\\/g, '/').split('/').pop() || filePath; + }, + // ─── 海康录像回放 ─── + loadHikFiles(page) { + page = page || 1; + var self = this; + window.printServerAPI.callApi('/api/hikvision/files?page=' + page + '&pageSize=20') + .then(function(res) { + if (res.success) { + self.hikFiles = res.data.list || []; + self.hikFilePage = res.data.page || 1; + self.hikFileTotal = res.data.total || 0; + self.hikFileTotalPages = Math.ceil(self.hikFileTotal / (res.data.pageSize || 20)) || 1; + self.hikStorageUsed = res.data.storage.used || 0; + self.hikStorageMax = res.data.storage.max || 0; + self.hikStoragePercent = res.data.storage.percent || 0; + } + }) + .catch(function(e) { console.error('加载录像列表失败:', e); }); + }, + loadHikTasks(page) { + var self = this; + if (typeof page === 'number') self.hikPage = page; + else page = self.hikPage; + self.hikJumpPage = page; + var url = '/api/hikvision/tasks?page=' + page + '&pageSize=' + self.hikPageSize; + window.printServerAPI.callApi(url) + .then(function(res) { + if (res.success) { + self.hikTasks = res.data.list || []; + self.hikTotal = res.data.total || 0; + } + }) + .catch(function(e) { console.error('加载任务列表失败:', e); }); + // 同时刷新存储统计 + window.printServerAPI.callApi('/api/hikvision/files?pageSize=1') + .then(function(res) { + if (res.success && res.data) { + self.hikStorageUsed = res.data.storage.used || 0; + self.hikStorageMax = res.data.storage.max || 0; + self.hikStoragePercent = res.data.storage.percent || 0; + } + }).catch(function(){}); + }, + previewHikTask(t) { + var result = t.result || {}; + var outputPath = t.output || (result.output || ''); + var downloadUrl = result.downloadUrl || ''; + // 如果没有 downloadUrl(来自 DB 查询),构造一个 + if (!downloadUrl && outputPath) { + downloadUrl = 'http://127.0.0.1:17311/api/hikvision/file?path=' + encodeURIComponent(outputPath); + } + this.previewFile = { + output_path: outputPath, + downloadUrl: downloadUrl, + file_size: result.size || 0, + duration: result.duration || 0 + }; + this.previewError = false; + }, + retryHikTask(taskId) { + var self = this; + window.printServerAPI.callApi('/api/hikvision/retry', { method: 'POST', body: { taskId: taskId } }) + .then(function(res) { + if (res.success) self.loadHikTasks(); + else alert('重试失败: ' + (res.message || '')); + }); + }, + taskStatusText(status) { + var map = { pending: '⏳ 等待中', running: '⬇ 下载中', completed: '✅ 完成', done: '✅ 完成', failed: '❌ 失败', timeout: '⏰ 超时' }; + return map[status] || status; + }, + taskStatusColor(status) { + var map = { pending: '#f59f00', running: '#0b69c7', completed: '#107c10', done: '#107c10', failed: '#c42b1c', timeout: '#c42b1c' }; + return map[status] || '#888'; + }, + fmtDuration(seconds) { + var s = parseInt(seconds) || 0; + if (s < 60) return s + 's'; + var m = Math.floor(s / 60); + var sec = s % 60; + return m + ':' + (sec < 10 ? '0' : '') + sec; + }, + previewHikFile(file) { + this.previewFile = file; + this.previewError = false; + }, + // ─── 海康配置 ─── + selectDownloadDir() { + var self = this; + window.printServerAPI.selectFolder().then(function(result) { + if (!result.canceled && result.path) { + self.hikConfig.downloadDir = result.path; + } + }); + }, + loadHikConfig() { + var self = this; + window.printServerAPI.callApi('/api/hikvision/config') + .then(function(res) { + if (res.success && res.hikvision) { + var c = res.hikvision; + self.hikConfig.downloadDir = c.downloadDir || ''; + self.hikConfig.circularRecording = c.circularRecording !== false; + // 解析 "50GB" → num=50, unit=GB + var m = String(c.maxStorage || '50GB').match(/^([\d.]+)\s*(TB|GB|MB|KB)$/i); + if (m) { + self.hikConfig.maxStorageNum = parseFloat(m[1]) || 50; + self.hikConfig.maxStorageUnit = m[2].toUpperCase(); + } + } + }); + }, + saveHikConfig() { + var self = this; + self.hikConfigSaving = true; + self.hikConfigSaved = false; + var payload = { + downloadDir: self.hikConfig.downloadDir, + maxStorage: String(self.hikConfig.maxStorageNum || 50) + (self.hikConfig.maxStorageUnit || 'GB'), + circularRecording: self.hikConfig.circularRecording + }; + window.printServerAPI.callApi('/api/hikvision/config', { + method: 'POST', + body: payload + }) + .then(function(res) { + self.hikConfigSaving = false; + if (res.success) { + self.hikConfigSaved = true; + // 用服务器返回的实际值更新本地状态 + if (res.hikvision) { + var c = res.hikvision; + self.hikConfig.downloadDir = c.downloadDir || ''; + self.hikConfig.circularRecording = c.circularRecording !== false; + var m2 = String(c.maxStorage || '50GB').match(/^([\d.]+)\s*(TB|GB|MB|KB)$/i); + if (m2) { + self.hikConfig.maxStorageNum = parseFloat(m2[1]) || 50; + self.hikConfig.maxStorageUnit = m2[2].toUpperCase(); + } + } + setTimeout(function() { self.hikConfigSaved = false; }, 3000); + } else { + alert('保存失败: ' + (res.message || '未知错误')); + } + }) + .catch(function(e) { + self.hikConfigSaving = false; + alert('保存失败: ' + e.message); + }); + }, loadComponents() { window.printServerAPI.callService('printerComponent.getAll', {}).then((data) => { console.log('获取组件列表:', data); @@ -770,6 +1090,15 @@ if (data.success) { this.isBind = data.result.isBind || false; this.name = data.result.name || ''; + if (data.result.recording) { + const r = data.result.recording; + this.recording = { + isRecording: !!r.isRecording, + maxStorage: r.maxStorage || '-', + downloadDir: r.downloadDir || '-', + remotePlayUrl: r.remotePlayUrl || '' + }; + } } else { alert(data.message || '获取绑定状态失败!'); } @@ -960,6 +1289,15 @@ if (data.success) { this.isBind = data.result.isBind || false; this.name = data.result.name || ''; + if (data.result.recording) { + const r = data.result.recording; + this.recording = { + isRecording: !!r.isRecording, + maxStorage: r.maxStorage || '-', + downloadDir: r.downloadDir || '-', + remotePlayUrl: r.remotePlayUrl || '' + }; + } } }) ); @@ -1032,6 +1370,27 @@ } }) ); + this._unsubFns.push( + window.printServerAPI.onEvent('setting.infoChanged', (data) => { + if (data.success && data.result) { + const r = data.result; + if (r.name !== undefined) this.name = r.name; + this.recording = { + isRecording: !!r.isRecording, + maxStorage: r.maxStorage || '-', + downloadDir: r.downloadDir || '-', + remotePlayUrl: r.remotePlayUrl || '' + }; + } + }) + ); + this._unsubFns.push( + window.printServerAPI.onEvent('frpc.statusChange', (data) => { + if (data.success && data.result) { + this.frpcStatus = data.result.status || 'stopped'; + } + }) + ); } }, watch: { @@ -1062,6 +1421,13 @@ this.refreshBindStatus(); this.loadComponents(); this.loadPrinters(); + this.loadHikConfig(); + // 拉取 frpc 初始状态 + window.printServerAPI.callService('frpc.getStatus', {}).then((data) => { + if (data.success && data.result) { + this.frpcStatus = data.result.status || 'stopped'; + } + }); // 主动拉取远端服务器连接状态(弥补 IPC 事件早于监听注册的时序问题) window.printServerAPI.callService('wsClient.getStatus', {}).then((data) => { if (data.success && data.result) { @@ -1093,6 +1459,13 @@ this.refreshBindStatus(); }, 10000); + // 录像回放 Tab 快速轮询(2秒) + this._hikPollTimer = setInterval(() => { + if (this.activeTab === 'playback') { + this.loadHikTasks(); + } + }, 2000); + // 延迟检查更新 setTimeout(() => { this.checkUpdate(false); @@ -1126,6 +1499,7 @@ this._unsubFns = []; } if (this._qrTimer) { clearInterval(this._qrTimer); this._qrTimer = null; } + if (this._hikPollTimer) { clearInterval(this._hikPollTimer); this._hikPollTimer = null; } } }); })();