2019 lines
90 KiB
JavaScript
2019 lines
90 KiB
JavaScript
import WSServer from './wsServer.js';
|
||
import configUtil from '../utils/config.js';
|
||
import PrinterComponentCore from './printerComponentCore.js';
|
||
import PrinterComponentMessageHandler from './printerComponentMessageHandler.js';
|
||
import WSClient from './wsClient.js';
|
||
import fs from 'fs';
|
||
import { pathToFileURL, fileURLToPath } from 'url';
|
||
import path from 'path';
|
||
import EventEmitter from 'events';
|
||
import { getResourcePath, getProjectRoot, extractPortCandidates, writeRuntimeState, isRecordingMode, getRunMode } from '../utils/runtime.js';
|
||
import db from '../utils/db.js';
|
||
import http from 'http';
|
||
import net from 'net';
|
||
|
||
function hasProcessArg(flag) {
|
||
return process.argv.includes(flag);
|
||
}
|
||
|
||
// 框架基础类 Main
|
||
class Main extends EventEmitter {
|
||
constructor() {
|
||
super();
|
||
if (Main.instance) {
|
||
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._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('框架初始化完成');
|
||
//console.log('初始化services完成,当前服务列表:', Object.keys(this.services));
|
||
this.wsClient = new WSClient(this.config.remoteWs.url, {
|
||
reconnectInterval: this.config.remoteWs.reconnectInterval || 3000
|
||
}, this);
|
||
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();
|
||
});
|
||
}
|
||
});
|
||
|
||
// 初始化 HTTP 服务器(用于海康 NVR 下载等 HTTP 出口)
|
||
this._initHttpServer();
|
||
|
||
if (!this._isRecording) {
|
||
this.app.on("kuaishouMessage", (data) => {
|
||
console.log("收到快手打印组件消息,数据:", data);
|
||
});
|
||
}
|
||
Main.instance = this;
|
||
return this;
|
||
}
|
||
|
||
async _initWmiPrinterMonitor() {
|
||
// Use child_process to start PowerShell polling script, listen for printer status changes
|
||
const { spawn } = await import('child_process');
|
||
const scriptPath = getResourcePath('printer.ps1');
|
||
try {
|
||
let lastStatus = {};
|
||
const startMonitor = (useBypass = false) => {
|
||
const args = useBypass
|
||
? ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptPath]
|
||
: ['-NoProfile', '-File', scriptPath];
|
||
const ps = spawn('powershell.exe', args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
||
|
||
ps.stdout.on('data', (data) => {
|
||
const lines = data.toString().split(/\r?\n/).filter(Boolean);
|
||
for (const line of lines) {
|
||
// Parse format: 15:15:46 PrinterName: Status (Online/Offline)
|
||
const match = line.match(/^(\d{2}:\d{2}:\d{2}) (.+?): (.+?) \((Online|Offline)\)$/);
|
||
if (match) {
|
||
const [, time, name, status, online] = match;
|
||
const key = name;
|
||
if (lastStatus[key] !== status + online) {
|
||
lastStatus[key] = status + online;
|
||
this.app.emit('printerWmiStatusChange', { name, status, online, time });
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
ps.stderr.on('data', (data) => {
|
||
console.error('[WMI Printer Monitor][stderr]', data.toString());
|
||
});
|
||
|
||
ps.on('error', (err) => {
|
||
console.error('[WMI Printer Monitor][error]', err);
|
||
});
|
||
|
||
ps.on('exit', (code) => {
|
||
if (!useBypass && code !== 0) {
|
||
console.warn('[WMI Printer Monitor] no-bypass launch failed, retrying with ExecutionPolicy Bypass once');
|
||
startMonitor(true);
|
||
return;
|
||
}
|
||
|
||
console.warn(`[WMI Printer Monitor] exited with code ${code}`);
|
||
});
|
||
};
|
||
|
||
startMonitor(false);
|
||
} catch (e) {
|
||
console.error('[WMI Printer Monitor] failed to start:', e);
|
||
}
|
||
}
|
||
|
||
async init() {
|
||
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 图片(用于 <img> 标签直连时显示错误信息)
|
||
*/
|
||
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: 'failed', 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
|
||
);
|
||
|
||
// SQLite created_at 是 UTC,转北京时间显示
|
||
const toLocal = (ts) => {
|
||
if (!ts) return ts;
|
||
const m = String(ts).match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})/);
|
||
if (!m) return ts;
|
||
// 直接用 UTC 算术加 8 小时,处理跨日
|
||
const h = parseInt(m[4]) + 8;
|
||
const extraDay = Math.floor(h / 24);
|
||
const localH = h % 24;
|
||
const pad = n => String(n).padStart(2, '0');
|
||
// 简化:用 Date.UTC 构造后加 8h 的毫秒数,再用 UTC getter 格式化
|
||
const utcMs = Date.UTC(+m[1], +m[2]-1, +m[3], +m[4], +m[5], +m[6]) + 8*3600000;
|
||
const d = new Date(utcMs);
|
||
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth()+1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}`;
|
||
};
|
||
|
||
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);
|
||
// 内存状态 'error' → API 对外统一返回 'failed',与 DB 一致
|
||
const apiStatus = mem ? (mem.status === 'error' ? 'failed' : mem.status) : r.status;
|
||
return {
|
||
id: r.id, task_id: r.task_id, unique_code: r.unique_code || '',
|
||
status: apiStatus,
|
||
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: toLocal(r.start_time), end_time: toLocal(r.end_time),
|
||
created_at: toLocal(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
|
||
* 支持单任务 taskId 或批量 taskIds,支持 failed/timeout/completed 状态
|
||
*/
|
||
async _handleHikvisionRetry(res, body) {
|
||
const taskId = body && body.taskId;
|
||
const taskIds = body && body.taskIds;
|
||
const ids = taskId ? [taskId] : (Array.isArray(taskIds) ? taskIds : []);
|
||
if (ids.length === 0) {
|
||
this._sendJson(res, 400, { success: false, message: '缺少 taskId 或 taskIds' });
|
||
return;
|
||
}
|
||
try {
|
||
let okCount = 0, skipCount = 0;
|
||
for (const tid of ids) {
|
||
const task = this.db.get('SELECT status, tmp_file_path FROM hik_tasks WHERE task_id = ?', tid);
|
||
if (!task) { skipCount++; continue; }
|
||
if (task.status === 'completed' || task.status === 'done') {
|
||
console.log('[Retry] 重录已完成任务:', tid);
|
||
if (task.tmp_file_path) {
|
||
try { const fp = this._resolvePath(task.tmp_file_path); if (fp && fs.existsSync(fp)) { fs.unlinkSync(fp); console.log('[Retry] 已删除旧文件:', fp); } } catch (e) {}
|
||
}
|
||
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=?`, tid);
|
||
okCount++;
|
||
} else if (task.status === 'failed' || task.status === 'timeout' || task.status === 'error') {
|
||
console.log('[Retry] 手动重试失败/异常任务:', tid);
|
||
this.db.run(`UPDATE hik_tasks SET status='pending', retry=0, error_message=NULL WHERE task_id=?`, tid);
|
||
okCount++;
|
||
} else {
|
||
skipCount++;
|
||
}
|
||
}
|
||
this._scheduleHikTasks();
|
||
this._sendJson(res, 200, { success: true, message: `已处理: ${okCount}个加入队列, ${skipCount}个跳过`, okCount, skipCount });
|
||
} 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','error') 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','error') 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 {}
|
||
}
|
||
|
||
// ③b 失败记录:每次重试耗尽(retry>=3,与 notice 无关)写入一条失败记录
|
||
this.db.run(`
|
||
INSERT INTO hik_task_fail_log (task_id)
|
||
SELECT task_id FROM hik_tasks
|
||
WHERE status IN ('failed','timeout','error') AND retry >= 3 AND fail_logged = 0
|
||
`);
|
||
this.db.run(`
|
||
UPDATE hik_tasks SET fail_logged = 1
|
||
WHERE status IN ('failed','timeout','error') AND retry >= 3 AND fail_logged = 0
|
||
`);
|
||
|
||
// ④ 每个录像机(IP)最多 maxPerNvr 个并发 worker
|
||
const maxPerNvr = 3; // 每个 NVR 最多 3 个并发
|
||
const maxTotal = 4; // 总并发上限
|
||
|
||
// 获取正在运行的 IP 及其并发数
|
||
const runningRows = this.db.all(`SELECT json_extract(task_params, '$.ip') as ip, COUNT(*) as cnt FROM hik_tasks WHERE status = 'running' GROUP BY ip`);
|
||
const runningCount = new Map();
|
||
for (const r of runningRows) { if (r.ip) runningCount.set(r.ip, r.cnt); }
|
||
|
||
// 获取待处理任务,按 IP 分组取最早的多条
|
||
const pendingRows = this.db.all(`SELECT * FROM hik_tasks WHERE status = 'pending' ORDER BY id ASC`);
|
||
const pendingByIp = new Map();
|
||
for (const pt of pendingRows) {
|
||
const tp = JSON.parse(pt.task_params || '{}');
|
||
const ip = tp.ip;
|
||
if (!ip || !tp.start || !tp.end) {
|
||
this.db.run(`UPDATE hik_tasks SET status='failed', error_message='参数不完整' WHERE id = ?`, pt.id);
|
||
continue;
|
||
}
|
||
if (!pendingByIp.has(ip)) pendingByIp.set(ip, []);
|
||
if (pendingByIp.get(ip).length < maxPerNvr) pendingByIp.get(ip).push(pt);
|
||
}
|
||
|
||
let started = 0;
|
||
for (const [ip, tasks] of pendingByIp) {
|
||
const current = runningCount.get(ip) || 0;
|
||
if (current >= maxPerNvr) continue; // 该 NVR 已达并发上限
|
||
if (started >= maxTotal) break;
|
||
// 最多启动 maxPerNvr - current 个新任务
|
||
const slots = Math.min(tasks.length, maxPerNvr - current, maxTotal - started);
|
||
for (let i = 0; i < slots; i++) {
|
||
const pt = tasks[i];
|
||
const downloadCfg = { ...JSON.parse(pt.task_params || '{}'), output: this._resolvePath(JSON.parse(pt.task_params || '{}').output) };
|
||
const wid = ip; // 用 IP 作为 worker_id
|
||
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 tp = JSON.parse(pt.task_params || '{}');
|
||
const self = this;
|
||
const task = {
|
||
startTime: Date.now(),
|
||
progress: { chunks: 0, totalBytes: 0, totalMB: 0, speed: tp.speed || 4 },
|
||
params: tp, status: 'running',
|
||
unique_code: pt.unique_code || '', // 服务器下发的任务编号
|
||
_aborted: false, // receiveTask 强制覆盖时设为 true
|
||
abort() {
|
||
task._aborted = true;
|
||
if (typeof task._abortDownload === 'function') {
|
||
try { task._abortDownload(); } catch {}
|
||
}
|
||
},
|
||
_onDone: (result) => {
|
||
if (task._aborted) return; // 已被强制终止,跳过所有后续处理
|
||
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;
|
||
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(() => {});
|
||
self._pushTaskResult(taskId, relResult);
|
||
setTimeout(() => self._hikTasks.delete(taskId), 5 * 60 * 1000);
|
||
self._scheduleHikTasks();
|
||
},
|
||
_onError: (err) => {
|
||
if (task._aborted) return; // 已被强制终止,跳过所有后续处理
|
||
task.status = 'error'; task.error = err.message;
|
||
// 录像机无此时间视频 → 永久失败,不再重试
|
||
const permanent = err.message === '录像机无此时间视频';
|
||
self.db.run(
|
||
permanent
|
||
? `UPDATE hik_tasks SET status='failed', retry=3, notice=1, end_time=datetime('now'), error_message=? WHERE task_id=?`
|
||
: `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 {}
|
||
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);
|
||
runningCount.set(ip, (runningCount.get(ip) || 0) + 1);
|
||
started++;
|
||
}
|
||
}
|
||
// 空闲拉取
|
||
const pendingCount = pendingByIp.size;
|
||
if (pendingCount === 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分钟)');
|
||
|
||
// 每 3 分钟 1 次:录制开启时,无进行中任务且最近结束 <5 分钟时,重置最早 20 个失败任务
|
||
if (!this._hikSweepTimer) {
|
||
this._hikSweepTimer = setInterval(() => this._sweepOldFailedTasks(), 3 * 60 * 1000);
|
||
console.log('[Hikvision] 失败任务重扫器已启动(每3分钟1次,仅录制模式;无running且最近结束<5分钟时重置最早20个失败任务)');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 每 3 分钟执行:仅录制模式(isRecording)下,
|
||
* 触发条件:当前无 running 任务,且上一个任务结束时间距现在 < 5 分钟
|
||
* 重置范围:按创建时间升序最早 20 个失败任务(排除失败记录 >10 条的 task_id),
|
||
* retry 重置为 0,由现有调度器(每3秒)自动重新启动
|
||
*/
|
||
_sweepOldFailedTasks() {
|
||
try {
|
||
const hik = this.config && this.config.hikvision;
|
||
if (!hik || !hik.isRecording) {
|
||
return; // 非录制模式,跳过
|
||
}
|
||
|
||
// 触发条件 1:当前无进行中任务
|
||
const running = this.db.get(`SELECT COUNT(*) AS c FROM hik_tasks WHERE status = 'running'`);
|
||
if (running && running.c > 0) {
|
||
return;
|
||
}
|
||
|
||
// 触发条件 2:上一个任务结束时间距现在 < 5 分钟
|
||
const lastEnd = this.db.get(`
|
||
SELECT (strftime('%s','now') - strftime('%s', MAX(end_time))) AS age
|
||
FROM hik_tasks WHERE end_time IS NOT NULL AND end_time != ''
|
||
`);
|
||
if (!lastEnd || lastEnd.age === null || lastEnd.age >= 300) {
|
||
return;
|
||
}
|
||
|
||
// 范围:按创建时间升序最早的 20 个失败任务;排除失败记录 > 10 条的 task_id
|
||
const res = this.db.run(`
|
||
UPDATE hik_tasks SET retry = 0, fail_logged = 0
|
||
WHERE status IN ('failed','timeout','error')
|
||
AND task_id NOT IN (
|
||
SELECT task_id FROM hik_task_fail_log GROUP BY task_id HAVING COUNT(*) > 10
|
||
)
|
||
AND id IN (
|
||
SELECT id FROM hik_tasks
|
||
WHERE status IN ('failed','timeout','error')
|
||
AND task_id NOT IN (
|
||
SELECT task_id FROM hik_task_fail_log GROUP BY task_id HAVING COUNT(*) > 10
|
||
)
|
||
ORDER BY created_at ASC
|
||
LIMIT 20
|
||
)
|
||
`);
|
||
|
||
if (res.changes > 0) {
|
||
console.log(`[Hikvision] 失败任务重扫: ${res.changes} 个 retry 已重置为 0,等待调度器自动重启`);
|
||
}
|
||
} catch (e) {
|
||
console.error('[Hikvision] 失败任务重扫异常:', e.message);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取 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 stRaw = Number(body.streamType);
|
||
const st = Number.isNaN(stRaw) ? 1 : stRaw;
|
||
const info = await hikvisionService.getLiveUrl(body.ip, body.httpPort || 80, body.user, body.pass, body.port || 7681, body.channel || 33, st);
|
||
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;
|
||
// 0=子码流/1=主码流(海康标准),NaN 才回退默认,避免 0 被 || 吞掉拉成高清流
|
||
const rawStreamType = parseInt(params.get('streamType'));
|
||
const streamType = Number.isNaN(rawStreamType) ? 1 : rawStreamType;
|
||
const mode = params.get('mode') || 'auto'; // auto=RTSP优先→失败降级HTTP
|
||
// 输出帧率:默认 25fps 与源帧率一致(不抽帧,保持流畅);背压丢帧保护负责防内存泄漏,无需靠限帧
|
||
const rawFps = parseInt(params.get('fps'));
|
||
const fps = Number.isNaN(rawFps) ? 25 : Math.min(30, Math.max(1, rawFps));
|
||
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, fps });
|
||
}
|
||
|
||
// 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 });
|
||
}
|
||
|
||
// auto 模式:快速预检 RTSP 端口,不通直接降级(避免 ffmpeg 长等待造成“连不上”假象)
|
||
if (mode === 'auto' && ffmpegPath) {
|
||
const rtspPort = parseInt(params.get('rtspPort')) || 554;
|
||
const rtspReachable = await new Promise((resolve) => {
|
||
const s = net.createConnection({ host: ip, port: rtspPort });
|
||
s.setTimeout(1500);
|
||
s.once('connect', () => { s.destroy(); resolve(true); });
|
||
s.once('timeout', () => { s.destroy(); resolve(false); });
|
||
s.once('error', () => { resolve(false); });
|
||
});
|
||
if (!rtspReachable) {
|
||
console.log('[Hikvision] RTSP 端口 %d 预检不通,直接降级 HTTP 快照', rtspPort);
|
||
return this._handleHikvisionLiveStreamHttp(res, { ip, user, pass, channel, streamType, channelCode, hikvisionService, params });
|
||
}
|
||
}
|
||
|
||
// RTSP 模式(默认)
|
||
const rtspPort = parseInt(params.get('rtspPort')) || 554;
|
||
// RTSP 通道编码:海康 RTSP 1=主码流、2=子码流;streamType 0/1 均按主码流(601),2 按子码流(602)
|
||
const rtspStreamType = streamType === 2 ? 2 : 1;
|
||
const rtspChannelCode = 100 * channel + rtspStreamType;
|
||
const rtspUrl = `rtsp://${encodeURIComponent(user)}:${encodeURIComponent(pass)}@${ip}:${rtspPort}/Streaming/Channels/${rtspChannelCode}`;
|
||
console.log('[Hikvision] live-stream RTSP channel=%d code=%d url=%s', channel, rtspChannelCode,
|
||
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 快照模式(WS 模式加密协商未实现,仅 mode=ws 显式使用)
|
||
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 错误
|
||
|
||
const rtspTransport = params.get('transport') === 'udp' ? 'udp' : 'tcp';
|
||
// 主码流可能是 4K:缩放到 1280 宽降低编码数据量与浏览器解码压力;fps < 源帧率时才限帧
|
||
const vf = fps >= 25 ? 'scale=1280:-2' : `scale=1280:-2,fps=${fps}`;
|
||
ffmpeg = spawn(ffmpegPath, [
|
||
'-rtsp_transport', rtspTransport,
|
||
'-timeout', '3000000', // RTSP 连接超时 3s(微秒)
|
||
'-fflags', 'nobuffer', // 低延迟:不缓冲输入
|
||
'-flags', 'low_delay',
|
||
'-max_delay', '200000', // demuxer 缓冲上限 200ms
|
||
'-i', rtspUrl,
|
||
'-vf', vf,
|
||
'-f', 'mjpeg',
|
||
'-q:v', '6',
|
||
'-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 缓冲无限堆积导致内存持续增长
|
||
if (res.writableLength < 512 * 1024) {
|
||
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, fps }) {
|
||
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 输出)
|
||
const vfArgsWs = fps >= 25 ? [] : ['-vf', 'fps=' + fps];
|
||
ffmpeg = spawn(ffmpegPath, [
|
||
'-f', 'mpeg', // 海康 ISAPI WS 推送的是 MPEG-PS 流(非 TS)
|
||
'-fflags', 'nobuffer', // 低延迟:不缓冲输入
|
||
'-flags', 'low_delay',
|
||
'-max_delay', '200000', // demuxer 缓冲上限 200ms
|
||
'-i', 'pipe:0',
|
||
...vfArgsWs,
|
||
'-f', 'mjpeg',
|
||
'-q:v', '6',
|
||
'-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 缓冲无限堆积导致内存持续增长
|
||
if (res.writableLength < 512 * 1024) {
|
||
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;
|
||
// 最小拉取间隔:默认 200ms(5fps 均匀节奏,与旧版一致的兜底体验);可用 &interval= 覆盖(0=连续)
|
||
const interval = Number.isFinite(parseInt(params.get('interval'))) ? Math.max(0, parseInt(params.get('interval'))) : 200;
|
||
|
||
let closed = false;
|
||
let frameCount = 0;
|
||
const startTime = Date.now();
|
||
let cookieJar = {};
|
||
let sessionTag = '';
|
||
let agent = null;
|
||
|
||
const doCleanup = () => {
|
||
if (closed) return;
|
||
closed = true;
|
||
if (agent) { try { agent.destroy(); } catch {} }
|
||
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);
|
||
|
||
// 连接复用:避免每帧 TCP 握手开销
|
||
agent = new http.Agent({ keepAlive: true, maxSockets: 2 });
|
||
|
||
// 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: 单路轮询(均匀节奏,避免并发乱序导致的画面跳帧)
|
||
const fetchFrame = async () => {
|
||
try {
|
||
const hdrs = sessionTag ? { 'SessionTag': sessionTag } : {};
|
||
const result = await hikvisionService._req('GET', snapshotUrl, null, hdrs, cookieJar, true, agent);
|
||
if (result.statusCode === 200 && result.body && result.body.length > 500) {
|
||
return result.body;
|
||
}
|
||
if (result.statusCode === 401) {
|
||
// Session 过期,重新登录(login 内部有锁)
|
||
const relogin = await hikvisionService.login(ip, httpPort, user, pass);
|
||
cookieJar = relogin.cookieJar;
|
||
sessionTag = relogin.sessionTag;
|
||
}
|
||
} catch (e) { /* 单次失败忽略 */ }
|
||
return null;
|
||
};
|
||
|
||
const writeFrame = (jpeg) => {
|
||
if (!jpeg || closed || res.destroyed) return;
|
||
// 背压保护:客户端消费慢(如浏览器后台标签页)时丢帧,避免内存持续增长
|
||
if (res.writableLength < 512 * 1024) {
|
||
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++;
|
||
}
|
||
};
|
||
|
||
while (!closed) {
|
||
const loopStart = Date.now();
|
||
const jpeg = await fetchFrame();
|
||
writeFrame(jpeg);
|
||
if (interval > 0) {
|
||
const delay = Math.max(0, interval - (Date.now() - loopStart));
|
||
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: 'failed', 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 (_) {}
|
||
try { this.db.exec('ALTER TABLE hik_tasks ADD COLUMN fail_logged INTEGER DEFAULT 0'); } catch (_) {}
|
||
this.db.exec(`
|
||
CREATE TABLE IF NOT EXISTS hik_task_fail_log (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
task_id TEXT NOT NULL,
|
||
created_at TEXT DEFAULT (datetime('now'))
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_hik_fail_log_task ON hik_task_fail_log(task_id);
|
||
`);
|
||
|
||
// 优先读取 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')),
|
||
fail_logged INTEGER DEFAULT 0
|
||
);
|
||
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);
|
||
|
||
CREATE TABLE IF NOT EXISTS hik_task_fail_log (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
task_id TEXT NOT NULL,
|
||
created_at TEXT DEFAULT (datetime('now'))
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_hik_fail_log_task ON hik_task_fail_log(task_id);
|
||
`);
|
||
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) || 17301;
|
||
|
||
// 托管后端进程由桌面壳监管,当前进程不直接执行本地热重启。
|
||
if (hasProcessArg('--backend-runner')) {
|
||
return { wsPort };
|
||
}
|
||
|
||
this.config.wsPort = wsPort;
|
||
|
||
if (this.wsClient) {
|
||
this.wsClient.close();
|
||
if (typeof this.wsClient._connect === 'function') {
|
||
this.wsClient._connect();
|
||
}
|
||
}
|
||
|
||
return { wsPort };
|
||
}
|
||
|
||
getConfig() {
|
||
return this.config;
|
||
}
|
||
|
||
setConfig(newConfig) {
|
||
this.config = newConfig;
|
||
return this.configUtil.write(newConfig);
|
||
}
|
||
|
||
getService(name) {
|
||
return this.ctx.services[name];
|
||
}
|
||
|
||
// 可扩展更多框架基础能力
|
||
async _loadServices() {
|
||
const walk = async (dir) => {
|
||
const result = {};
|
||
const files = fs.readdirSync(dir);
|
||
for (const file of files) {
|
||
const fullPath = path.resolve(path.join(dir, file));
|
||
const stat = fs.statSync(fullPath);
|
||
if (stat.isDirectory()) {
|
||
result[file] = await walk(fullPath);
|
||
} else if (file.endsWith('.js')) {
|
||
const name = path.basename(file, '.js');
|
||
const fileUrl = pathToFileURL(fullPath).href;
|
||
console.log('[WSServer] 动态 import 路径:', fullPath, fileUrl);
|
||
try {
|
||
const mod = await import(fileUrl);
|
||
// 自动实例化导出的类
|
||
if (mod.default && typeof mod.default === 'function') {
|
||
result[name] = new mod.default();
|
||
} else {
|
||
result[name] = mod.default;
|
||
}
|
||
} catch (e) {
|
||
console.error('[WSServer] import try/catch 错误:', fileUrl, e);
|
||
}
|
||
}
|
||
}
|
||
return result;
|
||
};
|
||
// 使用 fileURLToPath 正确解析跨平台路径
|
||
const __filename = fileURLToPath(import.meta.url);
|
||
const __dirname = path.dirname(__filename);
|
||
this.services = await walk(path.join(__dirname, '../services'));
|
||
console.log('[WSServer] 已加载服务:', Object.keys(this.services));
|
||
}
|
||
|
||
}
|
||
|
||
export default new Main();
|