printServer/services/hikvision.js
liufumingren 37e7b8ddaa feat(hikvision): 任务权重与普通/加急双通道调度,修复录制进程崩溃与 frpc 孤儿问题
feat: hik_tasks 新增 weight(0=普通 1=加急),三处下发入口(fetchTasks/receiveTask/HTTP download)解析落库,老库启动 ALTER 自动补列+索引

feat: 调度器拆双通道——普通通道只跑 weight=0、加急通道只跑 weight=1,每 NVR 各 1 路,两通道互不排斥、加急通道自身互斥;任务启动抽成 _startHikTaskDownload

fix: fetchTasks 对已排队任务同步权重复下发(此前直接 continue,服务端把排队任务转加急不生效)

fix(hikvision): _httpPlaybackDownload 的 ws.on('finish') 裸调 fs.statSync,临时文件被 cleanupTmp 删除后抛 ENOENT 未捕获导致整个进程退出(2026-09-11 平台离线约 48 分钟);加 settled 守卫 + try/catch

feat(index): 增加 uncaughtException/unhandledRejection 兜底,未捕获异常只记日志不退出进程

feat(frpc): 启动前清理使用同一 ini 的遗留/孤儿 frpc(孤儿长期占着 frp 代理名,导致平台经隧道进来的调用全部失败);新增启动代际守卫,避免并发调用产生多个 frpc 抢同一代理名;修正日志占位符未格式化问题
2026-09-11 18:14:12 +08:00

1144 lines
55 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, spawn } 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 || '';
// 权重:服务端不下发 weight 即为 0(普通);下发 1 = 加急(走加急通道)
const weight = Number(item.weight) === 1 ? 1 : 0;
if (uniqueCode) {
const existing = ad.db.get('SELECT id, status, weight FROM hik_tasks WHERE unique_code = ?', uniqueCode);
if (existing) {
// 同一任务再次下发:仍排队中则同步权重(服务端转加急 → 改表为 1,转入加急通道等待)
if (Number(existing.weight) !== weight && existing.status === 'pending') {
ad.db.run(
`UPDATE hik_tasks SET weight=?, task_params=json_set(COALESCE(task_params,'{}'), '$.weight', ?) WHERE id=?`,
weight, weight, existing.id
);
console.log('[Hikvision] fetchTasks 排队任务权重变更: %s %d → %d', uniqueCode, Number(existing.weight) || 0, weight);
// 权重变化立即触发调度,不必等 3 秒定时器(加急可立刻占用加急通道)
ad._lastFetchTime = null;
ad._scheduleHikTasks();
}
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, weight
}),
status: 'pending', retry: 0, weight,
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;
// 权重:0=普通(默认),1=加急(优先调度)
const weight = Number(data.weight) === 1 ? 1 : 0;
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, weight
}),
status: 'pending',
retry: 0,
weight,
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 下载(7681 连接失败时自动降级 RTSP 回放下载,兼容无 ISAPI WebSocket 的老固件)
task.status = 'downloading';
let result;
try {
result = await this._wsDownload({ ip, port, channel, start, end, speed, output, token, task });
} catch (e) {
const msg = (e && (e.message || e.code)) || '';
const connErr = /ECONNREFUSED|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|ECONNRESET/.test(msg);
if (!connErr) throw e;
console.log('[Hikvision] 7681 连接失败(%s),降级 HTTP 回放下载 %s ch=%d', msg.split('\n')[0], ip, channel);
// 原下载超时按 4x 速计算,HTTP 回放下载耗时不定,需清除改用降级自身超时
if (task._downloadTimer) { clearTimeout(task._downloadTimer); task._downloadTimer = null; }
result = await this._httpPlaybackDownload({ ip, httpPort, user, pass, channel, start: origStart, end: origEnd, speed, output, task, session: loginResult });
}
// [6] 转码(HTTP 回放降级已直接输出 mp4,跳过转码)
if (result.httpFallback) {
const size = fs.existsSync(result.mp4Path) ? fs.statSync(result.mp4Path).size : 0;
const finalResult = { success: true, output: result.mp4Path, size, duration: result.elapsed, speed, httpFallback: true };
task._onDone?.(finalResult);
console.log(`[Hikvision] HTTP回放完成: ${finalResult.output} ${(size / 1048576).toFixed(1)}MB`);
return;
}
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 和 bsf 让 ffmpeg 自动处理
transcoded = await ffRun(`-i "${workFile}" -c:v copy -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分钟)自然过期
}
/**
* HTTP 回放下载(兜底):NVR 没有 ISAPI WebSocket(7681) 时使用(老固件,如 HNVR5116 V4.75)
* 链路:ISAPI 搜索录像 → GET /ISAPI/ContentMgmt/download(token+playbackURI 原样)→
* ffmpeg 以 HTTP 流为输入,-ss 靠设备 Range 支持定位到工单窗口,-t 切片落盘 mp4
* @returns {Promise<{total, chunks, elapsed, httpFallback:true, mp4Path}>}
* 无录像时抛错「录像机无此时间视频」(与 WS 路径语义一致)
*/
_httpPlaybackDownload({ ip, httpPort, user, pass, channel, start, end, speed, output, task, session }) {
const trackId = channel * 100 + 1; // 主码流(与 WS playback 通道编号一致)
const parseDate = (iso) => { const d = new Date(iso); return isNaN(d) ? null : d; };
const sD = parseDate(start), eD = parseDate(end);
const isoUtc = (d) => d.toISOString().replace(/\.\d{3}Z$/, 'Z');
if (!sD || !eD) return Promise.reject(new Error('HTTP回放: 时间格式无效 ' + start + ' ~ ' + end));
// 搜索窗口前后放宽 30 秒(防边界缺失;搜索 body 时间用 ISO 带横线 UTC)
const sFrom = isoUtc(new Date(sD.getTime() - 30000)), sTo = isoUtc(new Date(eD.getTime() + 30000));
const doSearch = async () => {
const searchId = `{${crypto.randomUUID().toUpperCase()}}`;
const searchXml = `<?xml version="1.0" encoding="UTF-8"?>\n` +
`<CMSearchDescription><searchID>${searchId}</searchID>` +
`<trackIDList><trackID>${trackId}</trackID></trackIDList>` +
`<timeSpanList><timeSpan><startTime>${sFrom}</startTime><endTime>${sTo}</endTime></timeSpan></timeSpanList>` +
`<maxResults>50</maxResults><searchResultPostion>0</searchResultPostion>` +
`<metadataList><metadataDescriptor>//recordType.meta.hikvision.com/timing</metadataDescriptor></metadataList>` +
`</CMSearchDescription>`;
const headers = { 'Content-Type': 'application/xml' };
if (session.sessionTag) headers['SessionTag'] = session.sessionTag;
return this._req('POST', `http://${ip}:${httpPort}/ISAPI/ContentMgmt/search`, searchXml, headers, session.cookieJar);
};
// 紧凑时间解码(playbackURI 内的时间格式: YYYYMMDDTHHMMSSZ)
const decodeCompact = (s) => {
const m = String(s || '').match(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/);
return m ? new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6])) : null;
};
return doSearch().then(async (searchRes) => {
if (searchRes.statusCode !== 200) throw new Error(`HTTP回放: 搜索录像失败 HTTP ${searchRes.statusCode}`);
const uriList = [...String(searchRes.body || '').matchAll(/<playbackURI>([\s\S]*?)<\/playbackURI>/g)]
.map((m) => m[1].replace(/&amp;/g, '&').trim())
.filter(Boolean);
if (uriList.length === 0) {
console.log('[Hikvision] HTTP回放: 录像机无此时间视频 ch=%d %s ~ %s', channel, start, end);
throw new Error('录像机无此时间视频');
}
// 选与工单窗口相交的段:优先完全覆盖,否则取相交长度最长者
let best = null;
for (const u of uriList) {
const segS = decodeCompact(u.match(/starttime=([0-9A-Za-z]+)/i)?.[1]);
const segE = decodeCompact(u.match(/endtime=([0-9A-Za-z]+)/i)?.[1]);
if (!segS || !segE) continue;
const ovS = segS > sD ? segS : sD;
const ovE = segE < eD ? segE : eD;
const overlap = ovE - ovS;
if (overlap <= 0) continue;
if (!best || overlap > best.overlap) best = { uri: u, segS, segE, ovS, ovE, overlap };
}
if (!best) {
console.log('[Hikvision] HTTP回放: 录像机无此时间视频 ch=%d %s ~ %s', channel, start, end);
throw new Error('录像机无此时间视频');
}
// 输入侧偏移 = 工单窗口起点相对段起点的秒数(下载接口返回整段流)
const offsetSec = Math.floor((best.ovS - best.segS) / 1000);
const durSec = Math.ceil((best.ovE - best.ovS) / 1000);
return new Promise((resolve, reject) => {
const ffmpegPath = this._findFfmpeg();
if (!ffmpegPath) { reject(new Error('HTTP回放: 未找到 ffmpeg')); return; }
const outFile = output.endsWith('.mp4') ? output : output.replace(/\.ps$/i, '') + '.mp4';
const outDir = path.dirname(outFile);
if (outDir && outDir !== '.') fs.mkdirSync(outDir, { recursive: true });
const tmpFile = outFile + '.imkh';
const t0 = Date.now();
const cookieStr = Object.entries(session.cookieJar || {}).map(([k, v]) => `${k}=${v}`).join('; ');
console.log('[Hikvision] HTTP回放: 整段下载 ch=%d 段偏移 %ds 时长 %ds', channel, offsetSec, durSec);
// 阶段1:流式下载整段 IMKH 到本地临时文件(ffmpeg 对 IMKH 流的 Range 切片在老版本不可靠)
// 阶段2:本地文件切片(-ss 输入侧精确 seek,任何 ffmpeg 版本均可靠)
let settled = false;
const finishErr = (err) => { if (!settled) { settled = true; reject(err); } };
const cleanupTmp = () => { try { if (fs.existsSync(tmpFile)) fs.unlinkSync(tmpFile); } catch { /* */ } };
const req = http.request({
hostname: ip, port: httpPort,
path: `/ISAPI/ContentMgmt/download?token=${session.token}&playbackURI=${best.uri}`,
method: 'GET',
headers: cookieStr ? { 'User-Agent': 'Mozilla/5.0', 'Cookie': cookieStr } : { 'User-Agent': 'Mozilla/5.0' }
}, (res) => {
if (res.statusCode !== 200) {
let b = '';
res.on('data', (c) => { b += c; });
res.on('end', () => finishErr(new Error(`HTTP回放: 下载失败 HTTP ${res.statusCode} ${String(b).slice(0, 200)}`)));
return;
}
const contentLen = parseInt(res.headers['content-length'] || '0', 10) || 0;
// 下载超时按段大小保底 2MB/s 估算(段最大约 1GB),并设总上限 20 分钟
const dlTimeoutMs = Math.min(20 * 60 * 1000, Math.max(120000, (contentLen / 2097152) * 1000 + 60000));
const ws = fs.createWriteStream(tmpFile, { highWaterMark: 512 * 1024 });
res.pipe(ws);
res.on('data', () => {
if (task) {
const sz = ws.bytesWritten || 0;
task.progress.totalBytes = sz;
task.progress.totalMB = Math.round(sz / 1048576 * 10) / 10;
}
});
const dlTimer = setTimeout(() => {
req.destroy(); cleanupTmp();
finishErr(new Error(`HTTP回放: 整段下载超时(${Math.round(dlTimeoutMs / 1000)}s)`));
}, dlTimeoutMs);
res.on('close', () => clearTimeout(dlTimer));
ws.on('error', (e) => { req.destroy(); finishErr(new Error('HTTP回放: 写临时文件失败 ' + e.message)); });
res.on('error', (e) => { finishErr(new Error('HTTP回放: 下载中断 ' + e.message)); });
ws.on('finish', () => {
// 已被超时/中止分支结束(settled=true,临时文件可能已被 cleanupTmp 删除)→ 不能再读文件,
// 否则 statSync 抛 ENOENT 成为未捕获异常,直接让整个录制服务进程退出(2026-09-11 实际发生)
if (settled) return;
if (task && task._aborted) { cleanupTmp(); finishErr(new Error('任务已中止')); return; }
let dlSize = 0;
try {
dlSize = fs.statSync(tmpFile).size;
} catch (e) {
cleanupTmp();
finishErr(new Error('HTTP回放: 临时文件不可读(已清理或写入失败) ' + e.message));
return;
}
console.log('[Hikvision] HTTP回放: 整段下载完成 (%.1fMB)', dlSize / 1048576);
// 阶段2:本地切片
// 用输出侧 -ss:对无索引的 IMKH 流,老版 ffmpeg 输入侧 seek 无效,
// 输出侧 -ss 顺序读+丢弃到窗口起点(本地文件读取快),窗口截取正确
const sliceArgs = ['-hide_banner', '-loglevel', 'warning',
'-i', tmpFile, '-ss', String(offsetSec), '-t', String(durSec),
'-c:v', 'copy', '-an', '-y', outFile];
const child = spawn(ffmpegPath, sliceArgs, { stdio: ['ignore', 'ignore', 'pipe'] });
let stderrTail = '';
child.stderr.on('data', (d) => { stderrTail = (stderrTail + d.toString()).slice(-800); });
const sliceTimer = setTimeout(() => {
try { child.kill('SIGKILL'); } catch { /* */ }
cleanupTmp(); finishErr(new Error('HTTP回放: 切片超时(60s)'));
}, 60000);
child.on('error', (err) => { clearTimeout(sliceTimer); cleanupTmp(); finishErr(new Error('HTTP回放: ffmpeg 启动失败 ' + err.message)); });
child.on('close', (code) => {
clearTimeout(sliceTimer);
cleanupTmp();
if (task && task._aborted) { finishErr(new Error('任务已中止')); return; }
const size = fs.existsSync(outFile) ? fs.statSync(outFile).size : 0;
if (code === 0 && size > 0) {
const elapsed = (Date.now() - t0) / 1000;
console.log('[Hikvision] HTTP回放: 切片完成 %s (%.1fMB, %.1fs)', outFile, size / 1048576, elapsed);
resolve({ total: size, chunks: 0, elapsed, httpFallback: true, mp4Path: outFile });
} else {
finishErr(new Error(`HTTP回放: 切片失败(exit=${code}) ${stderrTail.slice(-300)}`));
}
});
});
});
req.on('error', (e) => { cleanupTmp(); finishErr(new Error('HTTP回放: 下载请求失败 ' + e.message)); });
if (task) {
task._abortDownload = () => { req.destroy(); cleanupTmp(); };
}
req.end();
});
});
}
_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) {
console.log('[Hikvision] liveview cmd 响应错误:', payload.toString('utf-8'));
break;
}
} catch {}
}
}
} catch (e) { onError?.(e); }
finally { close(); }
})();
});
}
async _req(method, url, body, headers, cookieJar, binary = false, agent = null) {
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 reqOpts = { hostname: u.hostname, port: u.port || 80, path: u.pathname + u.search, method, headers: hdrs, timeout: 10000 };
if (agent) reqOpts.agent = agent;
const req = mod.request(reqOpts, (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