feat(hikvision): WS下载稳定性与任务调度优化

- WS下载: 5s静默超时自动完成(socketClosed标志避免死锁)
- WS下载: 视频帧日志跳过(op=0x02)防止日志膨胀
- 10s无数据: 直接标记永久失败(录像机无此时间视频),不再重试
- receiveTask: 强制推送时终止进行中的旧下载,防止同一NVR双下载
- API层: 内存error状态统一映射为failed,与DB一致
- 调度器: per-IP槽位+全局并发上限
- UI: 新增完成时间列,输出显示文件大小/时长
This commit is contained in:
liufumingren 2026-07-30 04:31:37 +08:00
parent 35fefaeddf
commit 1c8f945773
7 changed files with 369 additions and 235 deletions

View File

@ -1,25 +0,0 @@
{
"wsPort": 17301,
"wsPorts": [17301, 17302, 17303],
"httpPort": 17311,
"httpPorts": [17311, 17312, 17313],
"logLevel": "info",
"printerDefault": "",
"maxPrintJobs": 10,
"isService": false,
"remoteWs": {
"url": "ws://printer.wms.gztbyc.com/ws",
"reconnectInterval": 3000
},
"hikvision": {
"downloadDir": "/home/wwwroot/hikvision_recordings",
"maxStorage": "500GB",
"circularRecording": true
},
"mode": "recording",
"refreshTokenExpireTime": 0,
"tokenExpireTime": 0,
"token": "",
"refreshToken": "",
"name": "linux-recorder"
}

View File

@ -416,7 +416,7 @@ class Main extends EventEmitter {
}
this._sendJson(res, 200, { success: true, taskId, status: 'done', result: resultWithUrl });
} else if (memTask.status === 'error') {
this._sendJson(res, 200, { success: false, taskId, status: 'error', message: memTask.error || '下载失败' });
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 });
}
@ -467,6 +467,22 @@ class Main extends EventEmitter {
...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: {
@ -475,15 +491,17 @@ class Main extends EventEmitter {
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: mem ? mem.status : r.status,
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: r.start_time, end_time: r.end_time,
created_at: r.created_at,
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
};
@ -520,9 +538,9 @@ class Main extends EventEmitter {
}
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') {
console.log('[Retry] 重试失败任务:', tid);
this.db.run(`UPDATE hik_tasks SET status='pending', retry=retry+1, error_message=NULL WHERE task_id=?`, tid);
} 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++;
@ -554,91 +572,112 @@ class Main extends EventEmitter {
WHERE status='running' AND (strftime('%s','now') - strftime('%s',start_time)) > (timeout + 30)
`);
// ② 重试失败任务
// ② 重试失败/异常任务
this.db.run(`
UPDATE hik_tasks SET status='pending', worker_id=NULL, retry=retry+1
WHERE status IN ('failed','timeout') AND retry < 3
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') AND retry >= 3 AND notice = 0`);
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 {}
}
// ④ while 循环填满 worker
let started = 0;
while (started < MAX_WORKERS) {
const running = this.db.all(`SELECT DISTINCT worker_id FROM hik_tasks WHERE status = 'running' AND worker_id IS NOT NULL`);
const used = running.map(r => r.worker_id);
let wid = null;
for (let i = 1; i <= MAX_WORKERS; i++) { if (!used.includes(i)) { wid = i; break; } }
if (wid === null) break;
// ④ 每个录像机(IP)独占一个 worker,避免不同 NVR 互相阻塞
const maxPerNvr = 1; // 每个 NVR 最多 1 个并发
const maxTotal = 4; // 总并发上限
const pt = this.db.get(`SELECT * FROM hik_tasks WHERE status = 'pending' ORDER BY id ASC LIMIT 1`);
if (!pt) break;
// 获取正在运行的 NVR IP
const runningRows = this.db.all(`SELECT DISTINCT json_extract(task_params, '$.ip') as ip FROM hik_tasks WHERE status = 'running'`);
const runningIps = new Set(runningRows.map(r => r.ip).filter(Boolean));
const tp = JSON.parse(pt.task_params || '{}');
if (!tp.ip || !tp.start || !tp.end) {
this.db.run(`UPDATE hik_tasks SET status='failed', error_message='参数不完整' WHERE id = ?`, pt.id);
continue;
}
// 将相对路径解析为绝对路径以供下载使用
const downloadCfg = { ...tp, output: this._resolvePath(tp.output) };
this.db.run(`UPDATE hik_tasks SET status='running', worker_id=?, start_time=datetime('now') WHERE id=?`, wid, pt.id);
const taskId = pt.task_id;
const self = this;
const task = {
startTime: Date.now(),
progress: { chunks: 0, totalBytes: 0, totalMB: 0, speed: tp.speed || 4 },
params: tp, status: 'running',
_onDone: (result) => {
// 0 字节或标记失败 → 转为失败处理
if (result.success === false || (result.size || 0) === 0) {
const errMsg = result.success === false ? '录制返回失败' : '录制文件大小为 0';
task._onError(new Error(errMsg));
return;
}
task.status = 'done'; task.result = result;
// 结果中的 output 是绝对路径,转为相对路径存储
const relResult = { ...result, output: self._relativizePath(result.output || '') };
self.db.run(`UPDATE hik_tasks SET status='completed', end_time=datetime('now'), error_message=NULL, result=? WHERE task_id=?`, JSON.stringify(relResult), taskId);
try { self.db.table('hik_downloads').insert({ task_id: taskId, ip: tp.ip || '', channel: tp.channel || 0, output_path: relResult.output || tp.output || '', file_size: result.size || 0, duration: result.duration || 0, resolution: result.resolution || '', status: 'done' }); } catch (e) {}
self.checkHikStorageQuota().catch(() => {});
// Push 任务结果到远程服务器
self._pushTaskResult(taskId, relResult);
setTimeout(() => self._hikTasks.delete(taskId), 5 * 60 * 1000);
self._scheduleHikTasks();
},
_onError: (err) => {
task.status = 'error'; task.error = err.message;
self.db.run(`UPDATE hik_tasks SET status='failed', end_time=datetime('now'), error_message=? WHERE task_id=?`, err.message, taskId);
try { const fp = self._resolvePath(tp.output); if (fp && fs.existsSync(fp)) fs.unlinkSync(fp); } catch {}
// Push 失败信息到远程服务器
self._pushTaskFailed(taskId, err.message);
setTimeout(() => self._hikTasks.delete(taskId), 5 * 60 * 1000);
self._scheduleHikTasks();
}
};
this._hikTasks.set(taskId, task);
hikvisionService.startDownload(downloadCfg, taskId, task);
started++;
// 获取待处理任务,按 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, pt);
}
// 空闲拉取:有空闲 worker 且无 pending 任务,距上次拉取 >5分钟则触发
if (started < MAX_WORKERS) {
const pending = this.db.get('SELECT COUNT(*) as c FROM hik_tasks WHERE status = ?', 'pending');
if (!pending || pending.c === 0) {
const now = Date.now();
if (!this._lastFetchTime || (now - this._lastFetchTime) > 5 * 60 * 1000) {
this._lastFetchTime = now;
this.services.hikvision?.fetchTasks();
}
let started = 0;
for (const [ip, pt] of pendingByIp) {
if (runningIps.has(ip)) continue; // 该 NVR 已有下载中
if (started >= maxTotal) break;
if (runningIps.size + started >= maxTotal) break;
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);
runningIps.add(ip);
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();
}
}
// ⑤ 推送重试:已完成/失败但服务端未确认的任务,按退避间隔重试
@ -1180,7 +1219,7 @@ class Main extends EventEmitter {
}
this._sendJson(res, 200, { success: true, taskId, status: 'done', message: '下载完成', result: resultWithUrl });
} else if (task.status === 'error') {
this._sendJson(res, 200, { success: false, taskId, status: 'error', message: task.error || '下载失败' });
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 });
}

0
py_ch11_test.ps Normal file
View File

20
q.mjs
View File

@ -1,20 +0,0 @@
import Database from 'better-sqlite3';
import { existsSync } from 'fs';
const dbPath = existsSync('printserver.db') ? 'printserver.db' : '/opt/printserver/printserver.db';
const db = new Database(dbPath);
console.log('=== 成功任务(completed/done) ===');
const done = db.prepare(`SELECT task_id,status,json_extract(task_params,'$.ip') as ip,json_extract(task_params,'$.channel') as ch,json_extract(task_params,'$.start') as st,json_extract(task_params,'$.end') as et,json_extract(task_params,'$.port') as port, result FROM hik_tasks WHERE status IN ('completed','done') ORDER BY id DESC LIMIT 10`).all();
done.forEach(r => {
const res = r.result ? JSON.parse(r.result) : {};
console.log(` ${r.task_id.slice(-12)} | ${r.status} | ${r.ip} ch${r.ch} | ${r.st}→${r.et} | port=${r.port} | output=${res.output||'-'} | size=${res.size||0}`);
});
console.log('\n=== 失败任务(最近10条) ===');
const failed = db.prepare(`SELECT task_id,status,json_extract(task_params,'$.ip') as ip,json_extract(task_params,'$.channel') as ch,json_extract(task_params,'$.start') as st,json_extract(task_params,'$.end') as et,json_extract(task_params,'$.port') as port, error_message, retry FROM hik_tasks WHERE status='failed' ORDER BY id DESC LIMIT 10`).all();
failed.forEach(r => {
console.log(` ${r.task_id.slice(-12)} | ${r.status} | ${r.ip} ch${r.ch} | ${r.st}→${r.et} | port=${r.port} | retry=${r.retry} | ${r.error_message}`);
});
console.log(`\n总任务: ${db.prepare('SELECT count(*) as c FROM hik_tasks').get().c}`);
db.close();

16
run_ch11_test.py Normal file
View File

@ -0,0 +1,16 @@
import json, subprocess, sys, os
cfg = {
"ip": "192.168.8.241",
"port": 7681,
"httpPort": 80,
"user": "admin",
"pass": "ky666888",
"channel": 11,
"start": "2026-07-29T21:35:00",
"end": "2026-07-29T21:35:25",
"speed": 4,
"output": os.path.join(os.path.dirname(__file__), "py_ch11_test.ps")
}
script = os.path.join(os.path.dirname(__file__), "hik_download_debug.py")
subprocess.run([sys.executable, script, json.dumps(cfg)], timeout=180)

View File

@ -4,9 +4,11 @@ import http from 'http';
import https from 'https';
import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';
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 丢失
@ -20,6 +22,10 @@ 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();
}
/**
@ -139,6 +145,12 @@ class HikvisionService extends BaseService {
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;
@ -227,16 +239,27 @@ class HikvisionService extends BaseService {
// 下载超时保护(视频时长/速度 + 120秒兜底)
const downloadTimeout = Math.max(120000, ((new Date(end) - new Date(start)) / 1000 / speed + 60) * 1000);
const timeoutTimer = setTimeout(() => {
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(() => clearTimeout(timeoutTimer)).catch(err => {
clearTimeout(timeoutTimer);
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);
});
@ -248,9 +271,67 @@ class HikvisionService extends BaseService {
}
/**
* 通用登录认证,返回 { token, cookieJar, sessionTag }
* 通用登录认证,返回 { 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');
@ -282,21 +363,28 @@ class HikvisionService extends BaseService {
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 new Error(`登录失败: ${loginRes.statusCode}`);
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');
const tokenHeaders = sessionTag ? { 'SessionTag': sessionTag } : {};
let tokenRes = await this._req('GET', `${httpBase}/ISAPI/Security/token?format=json`, null, tokenHeaders, cookieJar);
if (!tokenRes.body?.includes('"Token"')) {
tokenRes = await this._digestGet(`${httpBase}/ISAPI/Security/token?format=json`, user, pass, true);
}
const token = JSON.parse(tokenRes.body).Token.value;
await new Promise(r => setTimeout(r, 200));
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
*/
@ -368,7 +456,6 @@ class HikvisionService extends BaseService {
let { ip, port, httpPort = 80, user, pass, channel = 33, start, end, speed = 4, output } = p;
// 时间格式规范化:NVR WebSocket playback 只接受 "YYYY-MM-DDTHH:MM:SS"
// 服务器下发可能带毫秒和时区如 "2026-07-28T22:10:32.000+08:00",需裁剪
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})/);
@ -383,72 +470,9 @@ class HikvisionService extends BaseService {
console.log(`[Hikvision] taskId=${task.id} ${ip} ch=${channel}`);
const httpBase = `http://${ip}:${httpPort}`;
const NS = { h: 'http://www.hikvision.com/ver20/XMLSchema' };
const { DOMParser } = await import('@xmldom/xmldom');
const cookieJar = {};
// [1] Caps
const capsUrl = `${httpBase}/ISAPI/Security/sessionLogin/capabilities?username=${user}&random:${String(Date.now()).slice(-8)}`;
const capsRes = await this._req('GET', capsUrl, null, {}, cookieJar);
const capsXml = new DOMParser().parseFromString(capsRes.body, 'text/xml');
const getText = (x) => { const el = capsXml.getElementsByTagNameNS(NS.h, x); return el?.length ? el[0].textContent : ''; };
const sid = getText('sessionID');
const challenge = getText('challenge');
const itr = parseInt(getText('iterations')) || 1;
const salt = getText('salt');
const ver = getText('sessionIDVersion') || '1';
const vl = getText('isSessionIDValidLongTerm') || 'false';
const st = getText('isSupportSessionTag') || 'false';
const irreversible = getText('isIrreversible') === 'true';
// [2] 密码摘要
let digest;
if (irreversible) {
digest = crypto.createHash('sha256').update(user + salt + pass).digest('hex');
digest = crypto.createHash('sha256').update(digest + challenge).digest('hex');
for (let i = 2; i < itr; i++) digest = crypto.createHash('sha256').update(digest).digest('hex');
} else {
digest = crypto.createHash('sha256').update(pass + challenge).digest('hex');
for (let i = 1; i < itr; i++) digest = crypto.createHash('sha256').update(digest).digest('hex');
}
// [3] Login
let loginXml;
if (ver === '2') {
loginXml = `<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>`;
}
console.log('[Hikvision][DEBUG] login XML: %s', loginXml);
// 登录重试:403 表示会话冲突,延迟重试一次
let loginRes, loginRetry = 0;
do {
loginRes = await this._req('POST', `${httpBase}/ISAPI/Security/sessionLogin?timeStamp=${Date.now()}`, loginXml, { 'Content-Type': 'text/plain;charset=UTF-8' }, cookieJar);
console.log('[Hikvision][DEBUG] login response status=%d body(前200): %s (retry=%d)', loginRes.statusCode, (loginRes.body||'').substring(0,200), loginRetry);
if (loginRes.statusCode === 403 && loginRetry < 2) {
console.log('[Hikvision][DEBUG] login 403, 延迟重试...');
await new Promise(r => setTimeout(r, 1500));
loginRetry++;
// 清除旧 cookie 后重试
for (const k of Object.keys(cookieJar)) delete cookieJar[k];
} else {
break;
}
} while (true);
if (loginRes.statusCode !== 200 || !loginRes.body) throw new Error(`登录失败: ${loginRes.statusCode}`);
const loginParsed = new DOMParser().parseFromString(loginRes.body, 'text/xml');
const sessionTagEl = loginParsed.getElementsByTagNameNS(NS.h, 'sessionTag');
const sessionTag = sessionTagEl?.length ? sessionTagEl[0].textContent : '';
// [4] Token
const tokenHeaders = sessionTag ? { 'SessionTag': sessionTag } : {};
let tokenRes = await this._req('GET', `${httpBase}/ISAPI/Security/token?format=json`, null, tokenHeaders, cookieJar);
if (!tokenRes.body?.includes('"Token"')) {
tokenRes = await this._digestGet(`${httpBase}/ISAPI/Security/token?format=json`, user, pass, true);
}
const token = JSON.parse(tokenRes.body).Token.value;
// [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';
@ -463,20 +487,19 @@ class HikvisionService extends BaseService {
const outputBase = output.replace(/\.ps$/i, '').replace(/\.mp4$/i, '');
let workFile = outputBase + '.ps';
const mp4Path = outputBase + '.mp4';
// 如果 _wsDownload 写到 .mp4 后缀的文件,重命名为 .ps 作为转码输入
if (output.endsWith('.mp4') && fs.existsSync(output)) {
try { fs.renameSync(output, workFile); } catch { /* already .ps */ }
} else if (!fs.existsSync(workFile)) {
workFile = output; // fallback
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 = (args, timeout) => {
const ffRun = async (args, timeout) => {
const cmd = `"${ffmpegPath}" ${args} -y`;
try {
execSync(cmd, { timeout, stdio: 'pipe' });
await execAsync(cmd, { timeout, stdio: 'pipe' });
if (fs.existsSync(mp4Path) && fs.statSync(mp4Path).size > 0) return true;
return false;
} catch (e) {
@ -485,17 +508,14 @@ class HikvisionService extends BaseService {
return false;
}
};
// 海康 WS playback 输出的是 PS/TS 格式,需要指定输入格式+bitstream filter
// -f mpegts 强制按 TS 解析,-bsf:v h264_mp4toannexb 转换 AnnexB → MP4 格式
transcoded = ffRun(`-f mpegts -i "${workFile}" -c:v copy -bsf:v h264_mp4toannexb -an "${mp4Path}"`, 60000);
if (!transcoded) transcoded = ffRun(`-f mpegps -i "${workFile}" -c:v copy -bsf:v h264_mp4toannexb -an "${mp4Path}"`, 60000);
if (!transcoded) transcoded = ffRun(`-i "${workFile}" -c:v libx264 -preset fast -crf 23 -an "${mp4Path}"`, 120000);
transcoded = await ffRun(`-f mpegts -i "${workFile}" -c:v copy -bsf:v h264_mp4toannexb -an "${mp4Path}"`, 60000);
if (!transcoded) transcoded = await ffRun(`-f mpegps -i "${workFile}" -c:v copy -bsf:v h264_mp4toannexb -an "${mp4Path}"`, 60000);
if (!transcoded) transcoded = await ffRun(`-i "${workFile}" -c:v libx264 -preset fast -crf 23 -an "${mp4Path}"`, 120000);
if (transcoded) {
const mp4Size = fs.statSync(mp4Path).size;
try { fs.unlinkSync(workFile); } catch { /* */ }
finalResult = { success: true, output: mp4Path, size: mp4Size, duration: result.elapsed, speed, chunks: result.chunks };
} else {
// 清理可能产生的 0 字节 mp4
try { if (fs.existsSync(mp4Path) && fs.statSync(mp4Path).size === 0) fs.unlinkSync(mp4Path); } catch { /* */ }
const psSize = fs.existsSync(workFile) ? fs.statSync(workFile).size : 0;
finalResult = { success: true, output: workFile, size: psSize, duration: result.elapsed, speed, rawPs: true };
@ -508,6 +528,9 @@ class HikvisionService extends BaseService {
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 }) {
@ -530,11 +553,14 @@ class HikvisionService extends BaseService {
// 累积 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);
@ -552,6 +578,7 @@ class HikvisionService extends BaseService {
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 事件
@ -560,14 +587,16 @@ class HikvisionService extends BaseService {
return Buffer.concat(chunks);
};
// ws_recv: 读一个完整 WS 帧,返回 {op, payload}
// 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); len = ext.readUInt16BE(0); }
else if (len === 127) { const ext = await recvBytes(8); len = Number(ext.readBigUInt64BE(0)); }
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 };
};
@ -586,8 +615,10 @@ class HikvisionService extends BaseService {
buf = Buffer.concat([buf, data]);
notify();
});
socket.on('error', (err) => reject(err));
socket.on('close', () => notify()); // 唤醒可能正在等待的 recv
socket.on('error', (err) => {
if (!socketClosed) reject(err);
});
socket.on('close', () => { socketClosed = true; notify(); });
// 主流程
(async () => {
@ -601,23 +632,60 @@ class HikvisionService extends BaseService {
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;
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
@ -638,6 +706,15 @@ class HikvisionService extends BaseService {
}
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;

View File

@ -607,8 +607,12 @@
<option value="completed">已完成</option>
<option value="failed">失败</option>
<option value="timeout">超时</option>
<option value="error">异常</option>
</select>
<button @click="loadHikTasks" class="refresh-btn">刷新</button>
<button @click="toggleAutoRefresh" class="refresh-btn" :style="hikAutoRefresh ? {background:'#e8f5e9',color:'#107c10',borderColor:'#107c10'} : {}" style="white-space:nowrap;">{{ hikAutoRefresh ? '⏸ 停止刷新' : '▶ 自动刷新' }}</button>
<input v-if="!hikAutoRefresh" v-model.number="hikAutoRefreshInterval" type="number" min="1" max="300" style="width:40px;font-size:11px;padding:2px 4px;border:1px solid #ccc;border-radius:3px;text-align:center;" title="刷新间隔(秒)" />
<span v-if="!hikAutoRefresh" style="font-size:11px;color:#888;">秒</span>
<button @click="batchRetryHikTasks" class="refresh-btn" style="border-color:#f59f00;color:#f59f00;background:#fff8f0;" :disabled="!hikTasks.some(function(t){return t._checked})">批量强制重录</button>
<span v-if="batchRetryMsg" style="font-size:11px;color:#107c10;">{{ batchRetryMsg }}</span>
</div>
@ -630,6 +634,7 @@
<th style="padding:5px 6px;text-align:left;white-space:nowrap;border-bottom:2px solid #ddd;">创建时间</th>
<th style="padding:5px 6px;text-align:left;white-space:nowrap;border-bottom:2px solid #ddd;">录制开始</th>
<th style="padding:5px 6px;text-align:left;white-space:nowrap;border-bottom:2px solid #ddd;">录制结束</th>
<th style="padding:5px 6px;text-align:left;white-space:nowrap;border-bottom:2px solid #ddd;">完成时间</th>
<th style="padding:5px 6px;text-align:center;white-space:nowrap;border-bottom:2px solid #ddd;">操作</th>
</tr>
</thead>
@ -648,14 +653,15 @@
<td style="padding:4px 6px;white-space:nowrap;">{{ t.speed }}x</td>
<td style="padding:4px 6px;max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" :title="getFileName(t.output)">
<div v-if="t.status === 'completed' || t.status === 'done'" style="color:#333;">{{ getFileName(t.output) }}</div>
<div v-if="t.status === 'completed' || t.status === 'done'" style="font-size:9px;color:#888;">{{ formatBytes((t.result && t.result.size) || 0) }}</div>
<div v-if="(t.status === 'failed' || t.status === 'timeout') && t.error_message" style="font-size:10px;color:#c42b1c;">{{ t.error_message }}</div>
<div v-else-if="t.status !== 'completed' && t.status !== 'done' && t.status !== 'failed' && t.status !== 'timeout'" style="color:#aaa;">-</div>
<div v-if="t.status === 'completed' || t.status === 'done'" style="font-size:9px;color:#888;">{{ formatBytes((t.result && t.result.size) || 0) }} / {{ (t.result && t.result.duration) ? (t.result.duration).toFixed(1) + 's' : '-' }}</div>
<div v-if="(t.status === 'failed' || t.status === 'timeout' || t.status === 'error') && t.error_message" style="font-size:10px;color:#c42b1c;">{{ t.error_message }}</div>
<div v-else-if="t.status !== 'completed' && t.status !== 'done' && t.status !== 'failed' && t.status !== 'timeout' && t.status !== 'error'" style="color:#aaa;">-</div>
</td>
<td style="padding:4px 6px;white-space:nowrap;text-align:center;">{{ t.retry || 0 }}</td>
<td style="padding:4px 6px;white-space:nowrap;font-size:10px;color:#888;">{{ (t.created_at || '').substring(0,16) || '-' }}</td>
<td style="padding:4px 6px;white-space:nowrap;font-size:10px;color:#888;">{{ (t.rec_start || '').substring(0,16) || '-' }}</td>
<td style="padding:4px 6px;white-space:nowrap;font-size:10px;color:#888;">{{ (t.rec_end || '').substring(0,16) || '-' }}</td>
<td style="padding:4px 6px;white-space:nowrap;font-size:10px;color:#888;">{{ (t.end_time || '').substring(0,16) || '-' }}</td>
<td style="padding:4px 6px;text-align:center;white-space:nowrap;">
<button v-if="t.status === 'completed' || t.status === 'done'" style="font-size:10px;padding:1px 5px;margin:1px;" @click="previewHikTask(t)">预览</button>
<button v-if="t.status === 'completed' || t.status === 'done'" style="font-size:10px;padding:1px 5px;margin:1px;border-color:#f59f00;color:#f59f00;" @click="retryHikTask(t.task_id)">重录</button>
@ -981,6 +987,9 @@
hikStatusFilter: '',
hikSelectAll: false,
batchRetryMsg: '',
hikAutoRefresh: false,
hikAutoRefreshInterval: 5,
hikAutoRefreshTimer: null,
// 海康配置
hikConfig: { downloadDir: '', maxStorageNum: 50, maxStorageUnit: 'GB', circularRecording: true },
hikConfigSaving: false,
@ -1073,17 +1082,17 @@
self.hikSelectAll = false;
var url = '/api/hikvision/tasks?page=' + page + '&pageSize=' + self.hikPageSize;
if (self.hikStatusFilter) url += '&status=' + self.hikStatusFilter;
window.printServerAPI.callApi(url)
var p = window.printServerAPI.callApi(url)
.then(function(res) {
if (res.success) {
var list = res.data.list || [];
// 保留已有 _checked 状态
list.forEach(function(t) { t._checked = false; });
self.hikTasks = list;
self.hikTotal = res.data.total || 0;
}
return res;
})
.catch(function(e) { console.error('加载任务列表失败:', e); });
.catch(function(e) { console.error('加载任务列表失败:', e); throw e; });
// 同时刷新存储统计
window.printServerAPI.callApi('/api/hikvision/files?pageSize=1')
.then(function(res) {
@ -1093,6 +1102,7 @@
self.hikStoragePercent = res.data.storage.percent || 0;
}
}).catch(function(){});
return p;
},
previewHikTask(t) {
var result = t.result || {};
@ -1139,12 +1149,47 @@
console.error(e);
});
},
toggleAutoRefresh() {
this.hikAutoRefresh = !this.hikAutoRefresh;
if (this.hikAutoRefresh) {
this.loadHikTasks(1); // 强制回首页+全部状态
this.hikStatusFilter = '';
this._startAutoRefresh();
} else {
this._stopAutoRefresh();
}
try { localStorage.setItem('hikAutoRefresh', JSON.stringify({ enabled: this.hikAutoRefresh, interval: this.hikAutoRefreshInterval })); } catch(e) {}
},
_startAutoRefresh() {
this._stopAutoRefresh();
var self = this;
var ms = Math.max(1, self.hikAutoRefreshInterval || 5) * 1000;
var run = function() {
// 非首页或非全部状态时停止
if (self.hikPage !== 1 || self.hikStatusFilter !== '') {
self.hikAutoRefresh = false;
self._stopAutoRefresh();
try { localStorage.setItem('hikAutoRefresh', JSON.stringify({ enabled: false, interval: self.hikAutoRefreshInterval })); } catch(e) {}
return;
}
if (self.activeTab !== 'playback' || !self.hikAutoRefresh) return;
self.loadHikTasks(1).then(function() {
if (self.hikAutoRefresh) self.hikAutoRefreshTimer = setTimeout(run, ms);
}).catch(function() {
if (self.hikAutoRefresh) self.hikAutoRefreshTimer = setTimeout(run, ms);
});
};
self.hikAutoRefreshTimer = setTimeout(run, ms);
},
_stopAutoRefresh() {
if (this.hikAutoRefreshTimer) { clearTimeout(this.hikAutoRefreshTimer); this.hikAutoRefreshTimer = null; }
},
taskStatusText(status) {
var map = { pending: '⏳ 等待中', running: '⬇ 下载中', completed: '✅ 完成', done: '✅ 完成', failed: '❌ 失败', timeout: '⏰ 超时' };
return map[status] || status;
var map = { pending: '⏳ 等待中', running: '⬇ 下载中', completed: '✅ 完成', done: '✅ 完成', failed: '❌ 失败', timeout: '⏰ 超时', error: '⚠ 异常', starting: '🔄 启动中' };
return map[status] || ('❓ ' + (status || '未知'));
},
taskStatusColor(status) {
var map = { pending: '#f59f00', running: '#0b69c7', completed: '#107c10', done: '#107c10', failed: '#c42b1c', timeout: '#c42b1c' };
var map = { pending: '#f59f00', running: '#0b69c7', completed: '#107c10', done: '#107c10', failed: '#c42b1c', timeout: '#c42b1c', error: '#e67e22', starting: '#f59f00' };
return map[status] || '#888';
},
fmtDuration(seconds) {
@ -1631,17 +1676,18 @@
});
// 定期刷新
// 恢复自动刷新设置
try {
var saved = JSON.parse(localStorage.getItem('hikAutoRefresh') || '{}');
if (saved.interval) this.hikAutoRefreshInterval = saved.interval;
if (saved.enabled) { this.hikAutoRefresh = true; this._startAutoRefresh(); }
} catch(e) {}
// 定期刷新绑定状态
this._refreshInterval = setInterval(() => {
this.refreshBindStatus();
}, 10000);
// 录像回放 Tab 快速轮询(2秒)
this._hikPollTimer = setInterval(() => {
if (this.activeTab === 'playback') {
this.loadHikTasks();
}
}, 2000);
// 延迟检查更新
setTimeout(() => {
this.checkUpdate(false);
@ -1676,6 +1722,7 @@
}
if (this._qrTimer) { clearInterval(this._qrTimer); this._qrTimer = null; }
if (this._hikPollTimer) { clearInterval(this._hikPollTimer); this._hikPollTimer = null; }
if (this.hikAutoRefreshTimer) { clearInterval(this.hikAutoRefreshTimer); this.hikAutoRefreshTimer = null; }
}
});
})();