printServer/services/hikvision.js
liufumingren f56ca33a8d feat: 每NVR 3并发 + ffmpeg纯复制修复 + onvif依赖 + OSD日志
- 调度器: maxPerNvr 1→3, running追踪从Set改Map计数
- ffmpeg: 移除libx264重编码兜底, 修正-f mpegps→自动检测
- 新增 onvif 依赖用于摄像头OSD
- setting.setCameraOSD 增加入口/参数/结果日志
- wsClient 心跳更新
2026-07-31 23:31:33 +08:00

935 lines
43 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 { exec } from 'child_process';
import { createRequire } from 'module';
import { promisify } from 'util';
import BaseService from '../core/BaseService.js';
const execAsync = promisify(exec);
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;
/** @type {Map<string, {token:string, cookieJar:object, sessionTag:string, httpBase:string, ts:number}>} */
this._loginCache = new Map();
/** @type {Map<string, Promise>} 防止同一服务器并发登录 */
this._loginLocks = new Map();
}
/**
* 向服务器拉取待执行任务 / 处理服务器返回的任务列表
*/
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);
// 终止正在运行的旧下载(断开 WS,防止同一 NVR 双下载)
const runningTask = app._hikTasks?.get(existing.task_id);
if (runningTask && (runningTask.status === 'running' || runningTask.status === 'starting' || runningTask.status === 'downloading')) {
console.log('[Hikvision] receiveTask 终止进行中的旧下载:', existing.task_id);
runningTask.abort?.();
}
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);
task._downloadTimer = setTimeout(() => {
if (task._aborted) return;
if (task.status === 'running' || task.status === 'starting' || task.status === 'downloading') {
const err = new Error(`下载超时(${Math.round(downloadTimeout/1000)}s)`);
task._onError?.(err);
}
}, downloadTimeout);
// 增强 abort:同时清除下载超时定时器
const origAbort = task.abort?.bind(task);
task.abort = () => {
if (task._downloadTimer) { clearTimeout(task._downloadTimer); task._downloadTimer = null; }
origAbort?.();
};
process.nextTick(() => {
this._doDownload(task, params).then(() => {
if (task._downloadTimer) { clearTimeout(task._downloadTimer); task._downloadTimer = null; }
}).catch(err => {
if (task._downloadTimer) { clearTimeout(task._downloadTimer); task._downloadTimer = null; }
if (task._aborted) return; // 被强制终止,不报错
console.error('[Hikvision] 下载失败:', err.message);
task._onError?.(err);
});
});
}
getTaskStatus(taskId) {
return this._activeDownloads.get(taskId) || null;
}
/**
* 通用登录认证,返回 { token, cookieJar, sessionTag, httpBase }
* token 每次全新获取(不可重用),session 缓存 20 分钟
*/
async login(ip, httpPort, user, pass) {
const key = `${ip}:${httpPort}`;
const CACHE_TTL = 20 * 60 * 1000;
// ① 命中缓存 → 复用 session,但重新获取一次性 token
const cached = this._loginCache.get(key);
if (cached && (Date.now() - cached.ts) < CACHE_TTL) {
console.log('[Hikvision] login 命中缓存 key=%s age=%ds(重新获取 token)', key, Math.round((Date.now() - cached.ts) / 1000));
try {
const token = await this._getToken(cached.httpBase, cached.sessionTag, cached.cookieJar, user, pass);
return { token, cookieJar: cached.cookieJar, sessionTag: cached.sessionTag, httpBase: cached.httpBase };
} catch (e) {
// 获取 token 失败(403 session 过期)→ 清除缓存,走完整登录
console.log('[Hikvision] 缓存 session 获取 token 失败(%s),清除缓存重新登录', e.message?.substring(0, 50));
this._loginCache.delete(key);
}
}
// ② 防止并发登录
if (this._loginLocks.has(key)) {
console.log('[Hikvision] login 等待并发锁 key=%s', key);
return this._loginLocks.get(key);
}
// ③ 完整登录
const promise = this._doLogin(ip, httpPort, user, pass);
this._loginLocks.set(key, promise);
try {
const result = await promise;
// 缓存 session(不含 token,token 每次单独获取)
const session = { cookieJar: result.cookieJar, sessionTag: result.sessionTag, httpBase: result.httpBase, ts: Date.now() };
this._loginCache.set(key, session);
console.log('[Hikvision] login 成功并缓存 session key=%s token=%s...', key, result.token?.substring(0, 16));
return result;
} finally {
this._loginLocks.delete(key);
}
}
/** 获取一次性 token(需要已有的 session) */
async _getToken(httpBase, sessionTag, cookieJar, user, pass) {
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"')) {
// session cookie 失效 → 抛错让上层清除缓存重新登录,不用 digest 降级
const preview = (tokenRes.body || '').substring(0, 100);
console.log('[Hikvision][DEBUG] token 获取失败(session可能过期), body前100:', preview);
throw new Error(`Token获取失败(session失效,status=${tokenRes.statusCode}): ${preview}`);
}
try {
return JSON.parse(tokenRes.body).Token.value;
} catch (e) {
throw new Error(`Token解析失败(NVR认证被拒,status=${tokenRes.statusCode}): ${(tokenRes.body||'').substring(0,150)}`);
}
}
/** 内部:完整登录(返回完整结果含 token) */
async _doLogin(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 = `<SessionLogin><userName>${user}</userName><password>${digest}</password><sessionID>${sid}</sessionID><isSessionIDValidLongTerm>${vl}</isSessionIDValidLongTerm><sessionIDVersion>2</sessionIDVersion><isNeedSessionTag>${st}</isNeedSessionTag></SessionLogin>`;
} else {
loginXml = `<SessionLogin><userName>${user}</userName><password>${digest}</password><sessionID>${sid}</sessionID></SessionLogin>`;
}
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 Object.assign(new Error(`登录失败: HTTP ${loginRes.statusCode}`), { statusCode: 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');
await new Promise(r => setTimeout(r, 100));
const token = await this._getToken(httpBase, sessionTag, cookieJar, user, pass);
await new Promise(r => setTimeout(r, 100));
return { token, cookieJar, sessionTag, httpBase };
}
/** 清除指定服务器的登录缓存(触发 403 后调用) */
invalidateLogin(ip, httpPort) {
const key = `${ip}:${httpPort}`;
const had = this._loginCache.has(key);
this._loginCache.delete(key);
if (had) console.log('[Hikvision] invalidateLogin 已清除缓存 key=%s', key);
}
/**
* 获取通道列表 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) {
let { ip, port, httpPort = 80, user, pass, channel = 33, start, end, speed = 4, output } = p;
// 时间格式规范化:NVR WebSocket playback 只接受 "YYYY-MM-DDTHH:MM:SS"
const normTime = (t) => {
if (!t) return t;
const m = String(t).match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})/);
return m ? m[1] : t;
};
const origStart = start, origEnd = end;
start = normTime(start);
end = normTime(end);
if (start !== origStart || end !== origEnd) {
console.log(`[Hikvision] 时间已规范化: ${origStart} → ${start}, ${origEnd} → ${end}`);
}
console.log(`[Hikvision] taskId=${task.id} ${ip} ch=${channel}`);
// [1-4] 登录认证(session 缓存复用,token 每次全新,403 自动重新登录)
const loginResult = await this.login(ip, httpPort, user, pass);
const { token, cookieJar, sessionTag, httpBase } = loginResult;
// [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';
if (output.endsWith('.mp4') && fs.existsSync(output)) {
try { fs.renameSync(output, workFile); } catch { /* already .ps */ }
} else if (!fs.existsSync(workFile)) {
workFile = output;
}
const ffmpegPath = this._findFfmpeg();
let finalResult;
if (ffmpegPath && fs.existsSync(ffmpegPath) && fs.existsSync(workFile) && fs.statSync(workFile).size > 0) {
let transcoded = false;
const ffRun = async (args, timeout) => {
const cmd = `"${ffmpegPath}" ${args} -y`;
try {
await execAsync(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;
}
};
// PS → MP4 纯复制(视频流 copy,丢弃音频),不指定 -f 让 ffmpeg 自动检测
transcoded = await ffRun(`-i "${workFile}" -c:v copy -bsf:v h264_mp4toannexb -an "${mp4Path}"`, 60000);
// copy 失败直接保留 PS 原文件,不再使用 libx264 重编码(多 worker 时 CPU 不可接受)
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 {
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`);
// 使用缓存 session 时不注销,避免影响其他正在使用同一 session 的任务
// session 由缓存 TTL(20分钟)自然过期
}
_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`;
console.log('[Hikvision][DEBUG] WS握手请求(下载):\n%s', handshake.replace(/Sec-WebSocket-Key: \S+/, 'Sec-WebSocket-Key: ***'));
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;
let socketClosed = false;
const notify = () => { if (waiter) { const w = waiter; waiter = null; w(); } };
// recvBytes(n): 阻塞式读取 n 字节,对应 Python 的 sk.recv(n)
// socket 关闭时返回 null,调用方据此判断是否正常退出
const recvBytes = (n) => new Promise((resolveRecv) => {
const tryRead = () => {
if (socketClosed) return resolveRecv(null);
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));
if (part === null) return null; // socket 已关闭,信号退出
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},socket 关闭返回 null
const wsRecv = async () => {
const h = await recvBytes(2);
if (h === null) return null;
const op = h[0] & 0x0F;
let len = h[1] & 0x7F;
if (len === 126) { const ext = await recvBytes(2); if (ext === null) return null; len = ext.readUInt16BE(0); }
else if (len === 127) { const ext = await recvBytes(8); if (ext === null) return null; len = Number(ext.readBigUInt64BE(0)); }
const payload = await recvAll(len);
if (payload === null) return null;
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) => {
if (!socketClosed) reject(err);
});
socket.on('close', () => { socketClosed = true; notify(); });
// 主流程
(async () => {
try {
// ===== 步骤 1: 握手 =====
console.log('[Hikvision][DEBUG] WS握手已发送, 等待响应... ip=%s port=%d token_len=%d', ip, port, token.length);
// 等待 \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');
const respHeader = buf.slice(0, he).toString();
console.log('[Hikvision][DEBUG] WS握手响应: %s', respHeader.split('\r\n')[0] || respHeader.substring(0,80));
buf = buf.slice(he + 4);
// 打印 NVR 握手后第一个 WS 帧(Python 显示为 {"version":"1.0","cipherSuite":"1"})
if (buf.length > 2) {
const firstOp = buf[0] & 0x0F;
const firstLen = buf[1] & 0x7F;
const firstPayload = buf.slice(2, 2 + firstLen);
console.log('[Hikvision][DEBUG] WS首帧 op=%d len=%d payload=%s', firstOp, firstLen, firstPayload.toString('utf-8').substring(0, 200));
}
// ===== 步骤 2: 发 playback 命令 =====
const cmd = { sequence: 0, cmd: 'playback', url: `live://${ip}:${port}/${channel}/0`, startTime: start, endTime: end };
console.log('[Hikvision][DEBUG] 发送playback: %s', JSON.stringify(cmd));
wsSend(JSON.stringify(cmd), 0x01);
// NVR 接受了 WS 但不发视频数据 → 录像机在该时间段无录像,直接标记失败不再重试
let dataTimeout = setTimeout(() => {
const errMsg = '录像机无此时间视频';
console.log('[Hikvision] %s,主动断开 task=%s ch=%d', errMsg, task?.unique_code || task?.id, channel);
try { socket.destroy(); } catch {}
reject(new Error(errMsg));
}, 10000);
// ===== 步骤 3: 主循环,和 Python 完全一致 =====
const ws = fs.createWriteStream(output, { highWaterMark: 256 * 1024 });
let total = 0, chunks = 0, speedSent = false, dataReceived = false, silenceTimer = null, streamDone = false;
const t0 = Date.now();
// 暴露中止方法供 receiveTask 强制覆盖时调用(必须在 dataTimeout / silenceTimer 作用域内)
if (task) {
task._abortDownload = () => {
if (silenceTimer) clearTimeout(silenceTimer);
if (dataTimeout) clearTimeout(dataTimeout);
socketClosed = true;
try { socket.destroy(); } catch {}
notify();
};
}
while (true) {
if (streamDone) break;
let msg;
try { msg = await wsRecv(); } catch { break; }
if (!msg) break;
const { op, payload } = msg;
// 首次收到二进制数据 → 清除 10s 超时(ping/状态消息不算)
if (!dataReceived && op === 0x02) { dataReceived = true; clearTimeout(dataTimeout); }
// 调试:仅打印非视频帧(op=0x02 视频帧量大,跳过防日志膨胀)
if (op !== 0x02) {
const preview = payload.length > 10 ? payload.slice(0, 10).toString('hex') + '...' : payload.toString('hex');
const tag = task?.unique_code || task?.id || '?';
console.log('[Hikvision][DEBUG] WS recv task=%s op=%d len=%d hex=%s txt=%s',
tag, op, payload.length, preview,
op === 0x01 ? payload.toString('utf-8') : (payload.length > 0 ? payload.slice(0, 20).toString('utf-8') : '(empty)'));
}
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);
// 每次收到视频数据,重置 5s 空闲定时器
if (silenceTimer) clearTimeout(silenceTimer);
silenceTimer = setTimeout(() => {
console.log('[Hikvision] 视频流 5s 无新数据,视为传输完成 task=%s ch=%d chunks=%d', task?.unique_code || task?.id, channel, chunks);
streamDone = true;
socketClosed = true;
try { socket.destroy(); } catch {}
notify(); // 唤醒 wsRecv → 返回 null → 主循环退出
}, 5000);
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;
// 日志:只对敏感路径打印请求信息
if (u.pathname.includes('sessionLogin') || u.pathname.includes('token')) {
console.log('[Hikvision][DEBUG] _req %s %s%s headers=%s body_len=%d',
method, u.hostname, u.pathname,
JSON.stringify(Object.keys(hdrs)), (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 });
if (u.pathname.includes('sessionLogin') || u.pathname.includes('token')) {
console.log('[Hikvision][DEBUG] _req RESP %d len=%d type=%s',
res.statusCode, body.length,
res.headers['content-type'] || 'unknown');
}
});
});
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