Compare commits

...

13 Commits

Author SHA1 Message Date
liufumingren
9ccd25459a chore: bump 1.0.37 2026-08-26 23:32:03 +08:00
liufumingren
7ed52dcefe feat(osd): ONVIF失败自动嗅探回退海康ISAPI协议,RTSP通道解析+坐标系转换 2026-08-26 23:32:00 +08:00
liufumingren
93198a8828 perf(live-stream): 低延迟参数+RTSP通道编码修正+4K缩放转码+快照兜底恢复 2026-08-26 23:31:57 +08:00
liufumingren
9ebe3d0dc4 fix(frpc): 非录制模式不自动启动穿透,仅录制模式按配置拉起 2026-08-25 15:00:03 +08:00
liufumingren
f17d8386a5 chore: 发布 1.0.33 2026-08-24 02:21:05 +08:00
liufumingren
38fa36c180 perf: 更新下载进度300ms节流、状态栏仅变化时写DOM、轮询失败静默 2026-08-24 02:21:01 +08:00
liufumingren
28a0b5db37 fix(live-stream): MJPEG限帧默认5fps、streamType=0子码流生效、三路转发背压丢帧防内存泄漏 2026-08-24 02:20:57 +08:00
liufumingren
093ca9da46 fix(shell): 修复后端子进程spawn参数传Promise导致秒退,加心跳自愈与后端日志落盘 2026-08-24 02:20:53 +08:00
liufumingren
ffd2d238c2 fix(bridge): WS桥接统一回显_msgId/_callId,响应严格按ID匹配避免广播误匹配 2026-08-24 02:20:48 +08:00
liufumingren
5bb8c30e12 fix(hikvision): PS转MP4不指定-f与bsf,由ffmpeg自动检测容器与编码 2026-08-24 02:20:43 +08:00
liufumingren
fff6a2f46b chore: 移除系统服务功能,桌面壳直接托管后端子进程 2026-08-24 02:20:39 +08:00
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
liufumingren
1c8f945773 feat(hikvision): WS下载稳定性与任务调度优化
- WS下载: 5s静默超时自动完成(socketClosed标志避免死锁)
- WS下载: 视频帧日志跳过(op=0x02)防止日志膨胀
- 10s无数据: 直接标记永久失败(录像机无此时间视频),不再重试
- receiveTask: 强制推送时终止进行中的旧下载,防止同一NVR双下载
- API层: 内存error状态统一映射为failed,与DB一致
- 调度器: per-IP槽位+全局并发上限
- UI: 新增完成时间列,输出显示文件大小/时长
2026-07-30 04:31:37 +08:00
22 changed files with 946 additions and 815 deletions

View File

@ -33,8 +33,6 @@ printServer 是一个面向 Windows 的本地打印服务应用。
- 业务服务,如打印机、设置、绑定
- views/
- 页面模板,目前主要是 index.html
- daemon/
- 守护或服务相关配置文件
- 临时/
- 临时分析文档、测试脚本、临时日志的统一目录,可在任务结束后整体清理
@ -65,8 +63,7 @@ npm run dev
- WebSocket 服务按 method 路由到 services/ 下对应实例方法
示例:
- setting.register -> services/setting.js
- setting.unregister -> services/setting.js
- setting.info -> services/setting.js
- printer.getWindowsPrinters -> services/printer.js
## 当前打包方向

View File

@ -209,10 +209,8 @@ function Invoke-SignFile([string]$TargetPath, [string]$Label) {
function Sign-AppArtifacts {
$appExePath = Join-Path $root 'dist\win-unpacked\printServer.exe'
$serviceWrapperPath = Join-Path $root 'dist\win-unpacked\resources\daemon\printserver.exe'
Invoke-SignFile -TargetPath $appExePath -Label 'app executable'
Invoke-SignFile -TargetPath $serviceWrapperPath -Label 'service wrapper'
}
function Sign-InstallerArtifacts {
@ -354,7 +352,7 @@ function Ensure-PackagedResources() {
Copy-Item -Path $iconSourcePath -Destination $iconTargetPath -Force
}
foreach ($dirName in @('daemon', 'frpc')) {
foreach ($dirName in @('frpc')) {
$sourcePath = Join-Path $root $dirName
$targetPath = Join-Path $resourcesDir $dirName

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

@ -10,6 +10,7 @@ import EventEmitter from 'events';
import { getResourcePath, getProjectRoot, extractPortCandidates, writeRuntimeState, isRecordingMode, getRunMode } from '../utils/runtime.js';
import db from '../utils/db.js';
import http from 'http';
import net from 'net';
function hasProcessArg(flag) {
return process.argv.includes(flag);
@ -416,7 +417,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 +468,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 +492,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 +539,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 +573,118 @@ 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
// ④ 每个录像机(IP)最多 maxPerNvr 个并发 worker
const maxPerNvr = 3; // 每个 NVR 最多 3 个并发
const maxTotal = 4; // 总并发上限
// 获取正在运行的 IP 及其并发数
const runningRows = this.db.all(`SELECT json_extract(task_params, '$.ip') as ip, COUNT(*) as cnt FROM hik_tasks WHERE status = 'running' GROUP BY ip`);
const runningCount = new Map();
for (const r of runningRows) { if (r.ip) runningCount.set(r.ip, r.cnt); }
// 获取待处理任务,按 IP 分组取最早的多条
const pendingRows = this.db.all(`SELECT * FROM hik_tasks WHERE status = 'pending' ORDER BY id ASC`);
const pendingByIp = new Map();
for (const pt of pendingRows) {
const tp = JSON.parse(pt.task_params || '{}');
const ip = tp.ip;
if (!ip || !tp.start || !tp.end) {
this.db.run(`UPDATE hik_tasks SET status='failed', error_message='参数不完整' WHERE id = ?`, pt.id);
continue;
}
if (!pendingByIp.has(ip)) pendingByIp.set(ip, []);
if (pendingByIp.get(ip).length < maxPerNvr) pendingByIp.get(ip).push(pt);
}
let started = 0;
while (started < MAX_WORKERS) {
const running = this.db.all(`SELECT DISTINCT worker_id FROM hik_tasks WHERE status = 'running' AND worker_id IS NOT NULL`);
const used = running.map(r => r.worker_id);
let wid = null;
for (let i = 1; i <= MAX_WORKERS; i++) { if (!used.includes(i)) { wid = i; break; } }
if (wid === null) break;
const pt = this.db.get(`SELECT * FROM hik_tasks WHERE status = 'pending' ORDER BY id ASC LIMIT 1`);
if (!pt) break;
const tp = JSON.parse(pt.task_params || '{}');
if (!tp.ip || !tp.start || !tp.end) {
this.db.run(`UPDATE hik_tasks SET status='failed', error_message='参数不完整' WHERE id = ?`, pt.id);
continue;
}
// 将相对路径解析为绝对路径以供下载使用
const downloadCfg = { ...tp, output: this._resolvePath(tp.output) };
for (const [ip, tasks] of pendingByIp) {
const current = runningCount.get(ip) || 0;
if (current >= maxPerNvr) continue; // 该 NVR 已达并发上限
if (started >= maxTotal) break;
// 最多启动 maxPerNvr - current 个新任务
const slots = Math.min(tasks.length, maxPerNvr - current, maxTotal - started);
for (let i = 0; i < slots; i++) {
const pt = tasks[i];
const downloadCfg = { ...JSON.parse(pt.task_params || '{}'), output: this._resolvePath(JSON.parse(pt.task_params || '{}').output) };
const wid = ip; // 用 IP 作为 worker_id
this.db.run(`UPDATE hik_tasks SET status='running', worker_id=?, start_time=datetime('now') WHERE id=?`, wid, pt.id);
const taskId = pt.task_id;
const tp = JSON.parse(pt.task_params || '{}');
const self = this;
const task = {
startTime: Date.now(),
progress: { chunks: 0, totalBytes: 0, totalMB: 0, speed: tp.speed || 4 },
params: tp, status: 'running',
_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();
startTime: Date.now(),
progress: { chunks: 0, totalBytes: 0, totalMB: 0, speed: tp.speed || 4 },
params: tp, status: 'running',
unique_code: pt.unique_code || '', // 服务器下发的任务编号
_aborted: false, // receiveTask 强制覆盖时设为 true
abort() {
task._aborted = true;
if (typeof task._abortDownload === 'function') {
try { task._abortDownload(); } catch {}
}
},
_onDone: (result) => {
if (task._aborted) return; // 已被强制终止,跳过所有后续处理
if (result.success === false || (result.size || 0) === 0) {
const errMsg = result.success === false ? '录制返回失败' : '录制文件大小为 0';
task._onError(new Error(errMsg));
return;
}
task.status = 'done'; task.result = result;
const relResult = { ...result, output: self._relativizePath(result.output || '') };
self.db.run(`UPDATE hik_tasks SET status='completed', end_time=datetime('now'), error_message=NULL, result=? WHERE task_id=?`, JSON.stringify(relResult), taskId);
try { self.db.table('hik_downloads').insert({ task_id: taskId, ip: tp.ip || '', channel: tp.channel || 0, output_path: relResult.output || tp.output || '', file_size: result.size || 0, duration: result.duration || 0, resolution: result.resolution || '', status: 'done' }); } catch (e) {}
self.checkHikStorageQuota().catch(() => {});
self._pushTaskResult(taskId, relResult);
setTimeout(() => self._hikTasks.delete(taskId), 5 * 60 * 1000);
self._scheduleHikTasks();
},
_onError: (err) => {
if (task._aborted) return; // 已被强制终止,跳过所有后续处理
task.status = 'error'; task.error = err.message;
// 录像机无此时间视频 → 永久失败,不再重试
const permanent = err.message === '录像机无此时间视频';
self.db.run(
permanent
? `UPDATE hik_tasks SET status='failed', retry=3, notice=1, end_time=datetime('now'), error_message=? WHERE task_id=?`
: `UPDATE hik_tasks SET status='failed', end_time=datetime('now'), error_message=? WHERE task_id=?`,
err.message, taskId
);
try { const fp = self._resolvePath(tp.output); if (fp && fs.existsSync(fp)) fs.unlinkSync(fp); } catch {}
self._pushTaskFailed(taskId, err.message);
setTimeout(() => self._hikTasks.delete(taskId), 5 * 60 * 1000);
self._scheduleHikTasks();
}
};
this._hikTasks.set(taskId, task);
hikvisionService.startDownload(downloadCfg, taskId, task);
runningCount.set(ip, (runningCount.get(ip) || 0) + 1);
started++;
}
}
// 空闲拉取:有空闲 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();
}
}
// 空闲拉取
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();
}
}
// ⑤ 推送重试:已完成/失败但服务端未确认的任务,按退避间隔重试
@ -657,6 +703,40 @@ class Main extends EventEmitter {
if (this._hikScheduleTimer) return;
this._hikScheduleTimer = setInterval(() => this._scheduleHikTasks(), 3000);
console.log('[Hikvision] 任务调度器已启动(每3秒),空闲拉取(间隔5分钟)');
// 每小时 1 次:录制开启时,重新拉起创建时间 24~48 小时的失败任务
if (!this._hikHourlyRetryTimer) {
this._hikHourlyRetryTimer = setInterval(() => this._sweepOldFailedTasks(), 3600 * 1000);
console.log('[Hikvision] 失败任务重扫器已启动(每小时1次,仅录制模式,扫描24~48小时前创建的失败任务)');
}
}
/**
* 每小时执行:仅录制模式(isRecording)下,
* 将创建时间在 24~48 小时前且状态为失败的任务 retry 重置为 0,
* 由现有调度器(每3秒)自动重新启动
*/
_sweepOldFailedTasks() {
try {
const hik = this.config && this.config.hikvision;
if (!hik || !hik.isRecording) {
return; // 非录制模式,跳过
}
const res = this.db.run(`
UPDATE hik_tasks
SET retry = 0
WHERE status IN ('failed','timeout','error')
AND created_at >= datetime('now', '-48 hours')
AND created_at < datetime('now', '-24 hours')
`);
if (res.changes > 0) {
console.log(`[Hikvision] 失败任务重扫: ${res.changes} 个(创建于24~48小时前) retry 已重置为 0,等待调度器自动重启`);
}
} catch (e) {
console.error('[Hikvision] 失败任务重扫异常:', e.message);
}
}
/**
@ -697,7 +777,9 @@ class Main extends EventEmitter {
return;
}
try {
const info = await hikvisionService.getLiveUrl(body.ip, body.httpPort || 80, body.user, body.pass, body.port || 7681, body.channel || 33, body.streamType || 1);
const stRaw = Number(body.streamType);
const st = Number.isNaN(stRaw) ? 1 : stRaw;
const info = await hikvisionService.getLiveUrl(body.ip, body.httpPort || 80, body.user, body.pass, body.port || 7681, body.channel || 33, st);
this._sendJson(res, 200, { success: true, ...info });
} catch (err) {
this._sendJson(res, 500, { success: false, message: err.message });
@ -715,8 +797,13 @@ class Main extends EventEmitter {
const user = params.get('user');
const pass = params.get('pass');
const channel = parseInt(params.get('channel')) || 33;
const streamType = parseInt(params.get('streamType')) || 1; // 1=主码流, 2=子码流(海康标准)
// 0=子码流/1=主码流(海康标准),NaN 才回退默认,避免 0 被 || 吞掉拉成高清流
const rawStreamType = parseInt(params.get('streamType'));
const streamType = Number.isNaN(rawStreamType) ? 1 : rawStreamType;
const mode = params.get('mode') || 'auto'; // auto=RTSP优先→失败降级HTTP
// 输出帧率:默认 25fps 与源帧率一致(不抽帧,保持流畅);背压丢帧保护负责防内存泄漏,无需靠限帧
const rawFps = parseInt(params.get('fps'));
const fps = Number.isNaN(rawFps) ? 25 : Math.min(30, Math.max(1, rawFps));
const channelCode = 100 * channel + streamType;
if (!ip || !user || !pass) {
@ -730,7 +817,7 @@ class Main extends EventEmitter {
// WebSocket 模式:通过 ISAPI WebSocket 取流(7681 端口)
if (mode === 'ws') {
if (!ffmpegPath) { this._sendJson(res, 500, { success: false, message: 'ffmpeg 未找到' }); return; }
return this._handleHikvisionLiveStreamWs(res, { ip, user, pass, channel, streamType, channelCode, ffmpegPath, hikvisionService, params });
return this._handleHikvisionLiveStreamWs(res, { ip, user, pass, channel, streamType, channelCode, ffmpegPath, hikvisionService, params, fps });
}
// HTTP 快照模式:纯 HTTP 轮询 ISAPI 快照(仅需 80 端口)
@ -749,10 +836,29 @@ class Main extends EventEmitter {
return this._handleHikvisionLiveStreamHttp(res, { ip, user, pass, channel, streamType, channelCode, hikvisionService, params });
}
// auto 模式:快速预检 RTSP 端口,不通直接降级(避免 ffmpeg 长等待造成“连不上”假象)
if (mode === 'auto' && ffmpegPath) {
const rtspPort = parseInt(params.get('rtspPort')) || 554;
const rtspReachable = await new Promise((resolve) => {
const s = net.createConnection({ host: ip, port: rtspPort });
s.setTimeout(1500);
s.once('connect', () => { s.destroy(); resolve(true); });
s.once('timeout', () => { s.destroy(); resolve(false); });
s.once('error', () => { resolve(false); });
});
if (!rtspReachable) {
console.log('[Hikvision] RTSP 端口 %d 预检不通,直接降级 HTTP 快照', rtspPort);
return this._handleHikvisionLiveStreamHttp(res, { ip, user, pass, channel, streamType, channelCode, hikvisionService, params });
}
}
// RTSP 模式(默认)
const rtspPort = parseInt(params.get('rtspPort')) || 554;
const rtspUrl = `rtsp://${encodeURIComponent(user)}:${encodeURIComponent(pass)}@${ip}:${rtspPort}/Streaming/Channels/${channelCode}`;
console.log('[Hikvision] live-stream RTSP channel=%d code=%d url=%s', channel, channelCode,
// RTSP 通道编码:海康 RTSP 1=主码流、2=子码流;streamType 0/1 均按主码流(601),2 按子码流(602)
const rtspStreamType = streamType === 2 ? 2 : 1;
const rtspChannelCode = 100 * channel + rtspStreamType;
const rtspUrl = `rtsp://${encodeURIComponent(user)}:${encodeURIComponent(pass)}@${ip}:${rtspPort}/Streaming/Channels/${rtspChannelCode}`;
console.log('[Hikvision] live-stream RTSP channel=%d code=%d url=%s', channel, rtspChannelCode,
rtspUrl.replace(/:[^:@]+@/, ':****@'));
let ffmpeg = null;
@ -768,7 +874,7 @@ class Main extends EventEmitter {
if (!res.writableEnded) try { res.end(); } catch {}
};
// RTSP 失败时降级到 HTTP 快照模式
// RTSP 失败时降级到 HTTP 快照模式(WS 模式加密协商未实现,仅 mode=ws 显式使用)
const fallbackToHttp = () => {
if (closed) return;
closed = true;
@ -797,12 +903,19 @@ class Main extends EventEmitter {
// 先不发送响应头——等首帧到或 ffmpeg 失败后再决定
// 如果连不上 RTSP,ffmpeg 会快速退出,此时可返回 JSON 错误
const rtspTransport = params.get('transport') === 'udp' ? 'udp' : 'tcp';
// 主码流可能是 4K:缩放到 1280 宽降低编码数据量与浏览器解码压力;fps < 源帧率时才限帧
const vf = fps >= 25 ? 'scale=1280:-2' : `scale=1280:-2,fps=${fps}`;
ffmpeg = spawn(ffmpegPath, [
'-rtsp_transport', 'tcp',
'-rtsp_transport', rtspTransport,
'-timeout', '3000000', // RTSP 连接超时 3s(微秒)
'-fflags', 'nobuffer', // 低延迟:不缓冲输入
'-flags', 'low_delay',
'-max_delay', '200000', // demuxer 缓冲上限 200ms
'-i', rtspUrl,
'-vf', vf,
'-f', 'mjpeg',
'-q:v', '5',
'-q:v', '6',
'-an',
'-nostdin',
'pipe:1'
@ -896,9 +1009,12 @@ class Main extends EventEmitter {
}
if (!res.destroyed) {
res.write(`--ffmpeg\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`);
res.write(frame);
res.write('\r\n');
// 背压保护:客户端消费慢时丢帧,避免 res 缓冲无限堆积导致内存持续增长
if (res.writableLength < 512 * 1024) {
res.write(`--ffmpeg\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`);
res.write(frame);
res.write('\r\n');
}
}
}
});
@ -916,7 +1032,7 @@ class Main extends EventEmitter {
* WebSocket 模式实时预览(公网可用,走 7681 端口)
* 通过 ISAPI WebSocket 取流 → ffmpeg 转 MJPEG
*/
async _handleHikvisionLiveStreamWs(res, { ip, user, pass, channel, streamType, channelCode, ffmpegPath, hikvisionService, params }) {
async _handleHikvisionLiveStreamWs(res, { ip, user, pass, channel, streamType, channelCode, ffmpegPath, hikvisionService, params, fps }) {
const wsPort = parseInt(params.get('wsPort')) || 7681;
const httpPort = parseInt(params.get('httpPort')) || parseInt(params.get('port')) || 80;
@ -953,11 +1069,16 @@ class Main extends EventEmitter {
const { spawn } = await import('child_process');
// Step 2: 启动 ffmpeg(从 stdin 读取 PS 流 → MJPEG 输出)
const vfArgsWs = fps >= 25 ? [] : ['-vf', 'fps=' + fps];
ffmpeg = spawn(ffmpegPath, [
'-f', 'mpegts',
'-f', 'mpeg', // 海康 ISAPI WS 推送的是 MPEG-PS 流(非 TS)
'-fflags', 'nobuffer', // 低延迟:不缓冲输入
'-flags', 'low_delay',
'-max_delay', '200000', // demuxer 缓冲上限 200ms
'-i', 'pipe:0',
...vfArgsWs,
'-f', 'mjpeg',
'-q:v', '5',
'-q:v', '6',
'-an',
'-nostdin',
'pipe:1'
@ -1058,9 +1179,12 @@ class Main extends EventEmitter {
}
if (!res.destroyed) {
res.write(`--ffmpeg\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`);
res.write(frame);
res.write('\r\n');
// 背压保护:客户端消费慢时丢帧,避免 res 缓冲无限堆积导致内存持续增长
if (res.writableLength < 512 * 1024) {
res.write(`--ffmpeg\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`);
res.write(frame);
res.write('\r\n');
}
}
}
});
@ -1080,17 +1204,20 @@ class Main extends EventEmitter {
*/
async _handleHikvisionLiveStreamHttp(res, { ip, user, pass, channel, streamType, channelCode, hikvisionService, params }) {
const httpPort = parseInt(params.get('httpPort')) || parseInt(params.get('port')) || 80;
const interval = Math.max(100, parseInt(params.get('interval')) || 250); // 轮询间隔 ms
// 最小拉取间隔:默认 200ms(5fps 均匀节奏,与旧版一致的兜底体验);可用 &interval= 覆盖(0=连续)
const interval = Number.isFinite(parseInt(params.get('interval'))) ? Math.max(0, parseInt(params.get('interval'))) : 200;
let closed = false;
let frameCount = 0;
const startTime = Date.now();
let cookieJar = {};
let sessionTag = '';
let agent = null;
const doCleanup = () => {
if (closed) return;
closed = true;
if (agent) { try { agent.destroy(); } catch {} }
if (!res.writableEnded) try { res.end(); } catch {}
};
@ -1104,6 +1231,9 @@ class Main extends EventEmitter {
sessionTag = loginResult.sessionTag;
console.log('[Hikvision] live-stream HTTP 登录成功 ch=%d, 开始轮询', channel);
// 连接复用:避免每帧 TCP 握手开销
agent = new http.Agent({ keepAlive: true, maxSockets: 2 });
// Step 2: 发送 MJPEG 响应头
res.writeHead(200, {
'Content-Type': 'multipart/x-mixed-replace; boundary=snapshot',
@ -1117,35 +1247,43 @@ class Main extends EventEmitter {
const snapshotUrl = `http://${ip}:${httpPort}/ISAPI/Streaming/channels/${channelCode}/picture`;
const headers = sessionTag ? { 'SessionTag': sessionTag } : {};
// Step 3: 轮询循环
while (!closed) {
const loopStart = Date.now();
// Step 3: 单路轮询(均匀节奏,避免并发乱序导致的画面跳帧)
const fetchFrame = async () => {
try {
const result = await hikvisionService._req('GET', snapshotUrl, null, headers, cookieJar, true);
const hdrs = sessionTag ? { 'SessionTag': sessionTag } : {};
const result = await hikvisionService._req('GET', snapshotUrl, null, hdrs, cookieJar, true, agent);
if (result.statusCode === 200 && result.body && result.body.length > 500) {
const jpeg = result.body; // Buffer (binary=true)
if (!res.destroyed) {
res.write(`--snapshot\r\nContent-Type: image/jpeg\r\nContent-Length: ${jpeg.length}\r\n\r\n`);
res.write(jpeg);
res.write('\r\n');
frameCount++;
}
} else if (result.statusCode === 401) {
// Session 过期,重新登录
console.log('[Hikvision] live-stream HTTP session 过期,重新登录');
return result.body;
}
if (result.statusCode === 401) {
// Session 过期,重新登录(login 内部有锁)
const relogin = await hikvisionService.login(ip, httpPort, user, pass);
cookieJar = relogin.cookieJar;
sessionTag = relogin.sessionTag;
headers['SessionTag'] = sessionTag || '';
}
} catch (e) {
// 单次快照失败不中断,继续轮询
}
} catch (e) { /* 单次失败忽略 */ }
return null;
};
// 控制轮询频率
const elapsed = Date.now() - loopStart;
const delay = Math.max(0, interval - elapsed);
if (delay > 0) await new Promise(r => setTimeout(r, delay));
const writeFrame = (jpeg) => {
if (!jpeg || closed || res.destroyed) return;
// 背压保护:客户端消费慢(如浏览器后台标签页)时丢帧,避免内存持续增长
if (res.writableLength < 512 * 1024) {
res.write(`--snapshot\r\nContent-Type: image/jpeg\r\nContent-Length: ${jpeg.length}\r\n\r\n`);
res.write(jpeg);
res.write('\r\n');
frameCount++;
}
};
while (!closed) {
const loopStart = Date.now();
const jpeg = await fetchFrame();
writeFrame(jpeg);
if (interval > 0) {
const delay = Math.max(0, interval - (Date.now() - loopStart));
if (delay > 0) await new Promise(r => setTimeout(r, delay));
}
}
} catch (err) {
console.error('[Main] live-stream HTTP 启动失败:', err.message);
@ -1180,7 +1318,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 });
}
@ -1756,7 +1894,7 @@ class Main extends EventEmitter {
const wsPort = Number(options.wsPort) || Number(this.config.wsPort) || 17301;
// 托管后端进程由桌面壳监管,当前进程不直接执行本地热重启。
if (hasProcessArg('--backend-runner') || hasProcessArg('--service-runner')) {
if (hasProcessArg('--backend-runner')) {
return { wsPort };
}

View File

@ -110,7 +110,7 @@ class WSClient {
const { token, refreshToken, tokenExpireTime } = this.app.config;
if (!this.app.info && token && refreshToken && tokenExpireTime) {
if (tokenExpireTime < Date.now()) {
//console.log('[WSClient] 心跳检测: token 已过期,尝试刷新');
console.log('[WSClient] 心跳检测: token 已过期,尝试刷新');
this.send({ method: 'auth.refreshToken', data: { token: refreshToken } });
} else {
//拉取信息
@ -122,7 +122,7 @@ class WSClient {
}
async _handleMessage(msg) {
if(msg === 'pong') {
//console.log('[WSClient] 收到心跳响应');
console.log('[WSClient] 收到心跳响应');
return;
}
//console.log("[WSClient]原始消息", msg)

View File

@ -250,9 +250,11 @@ class WSServer {
ws.send(JSON.stringify({ success: false, message: '消息解析失败' }));
return;
}
const { method, data, _callId } = parsed;
const { method, data, _callId, _msgId } = parsed;
// 统一回显请求 ID:优先 _msgId(Electron 桥接),兼容 _callId(页面直连)
const replyId = _msgId || _callId;
if (!method) {
ws.send(JSON.stringify({ success: false, message: 'method不能为空', _callId }));
ws.send(JSON.stringify({ success: false, message: 'method不能为空', _msgId: replyId, _callId: replyId }));
return;
}
// 支持多级目录结构,如 index.index.index
@ -265,17 +267,18 @@ class WSServer {
if (typeof serviceFn === 'function') {
try {
const result = await serviceFn(data);
ws.send(JSON.stringify({ success: true, method, result, _callId }));
ws.send(JSON.stringify({ success: true, method, result, _msgId: replyId, _callId: replyId }));
} catch (err) {
//console.log(err);
ws.send(JSON.stringify({ success: false, method, message: '服务方法执行失败: ' + err.message, _callId }));
ws.send(JSON.stringify({ success: false, method, message: '服务方法执行失败: ' + err.message, _msgId: replyId, _callId: replyId }));
}
} else {
ws.send(JSON.stringify({
success: false,
method,
message: '未找到对应服务方法',
_callId,
_msgId: replyId,
_callId: replyId,
debug: {
method,
methodPath,

Binary file not shown.

View File

@ -1,6 +0,0 @@
<configuration>
<startup>
<supportedRuntime version="v2.0.50727" />
<supportedRuntime version="v4.0" />
</startup>
</configuration>

View File

@ -1,12 +0,0 @@
<service>
<id>printserver.exe</id>
<name>PrintServer</name>
<description>printServer backend service</description>
<executable>D:\printServer\node_modules\electron\dist\electron.exe</executable>
<argument>D:\printServer</argument>
<argument>--service-runner</argument>
<logmode>rotate</logmode>
<startmode>Automatic</startmode>
<stoptimeout>30sec</stoptimeout>
<workingdirectory>D:\printServer</workingdirectory>
</service>

View File

@ -17,13 +17,11 @@ let reconcilePromise = null;
const MAIN_FILE = path.join(__dirname, '..', 'views', 'index.html');
const BACKEND_RUNNER_ARG = '--backend-runner';
const SERVICE_RUNNER_ARG = '--service-runner';
const RECONCILE_INTERVAL_MS = 5000;
const APP_TITLE = '打印电脑服务';
const ICON_ICO_PATH = path.join(__dirname, 'assets', 'printserver.ico');
const ICON_PNG_PATH = path.join(__dirname, 'assets', 'printserver-icon-256.png');
const TRAY_ICON_FALLBACK_DATA_URL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAAV0lEQVR4AWP4TwAw/P//PwMDA8P///8ZGRkYGBgY/v//z8DAwMDA8J8B4v///5kYGRkZGBj+////PwMDw38Ghv9kZGQYGBj+////PwPDfwYGhv8MDAwA0rQYV5vWJ2EAAAAASUVORK5CYII=';
const BACKGROUND_SERVICE_OPTIONS = { allowElevation: false };
function createTrayImage() {
const icon = nativeImage.createFromPath(ICON_PNG_PATH);
@ -51,7 +49,7 @@ function hasArg(flag) {
}
function isHeadlessRunner() {
return hasArg(BACKEND_RUNNER_ARG) || hasArg(SERVICE_RUNNER_ARG);
return hasArg(BACKEND_RUNNER_ARG);
}
async function loadWorkspaceModule(relativePath) {
@ -59,12 +57,6 @@ async function loadWorkspaceModule(relativePath) {
return import(pathToFileURL(filePath).href);
}
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function isPortReachable(port) {
return new Promise((resolve) => {
const socket = net.createConnection({ host: '127.0.0.1', port });
@ -106,6 +98,43 @@ async function isBackendReady() {
// ─── 打包模式:WS 桥接(连接子进程的本地 WS 服务) ───
let _bridgeConnectPromise = null;
let _bridgeHeartbeat = null; // { pingTimer, pongTimer }
function stopBridgeHeartbeat() {
if (!_bridgeHeartbeat) return;
if (_bridgeHeartbeat.pingTimer) clearInterval(_bridgeHeartbeat.pingTimer);
if (_bridgeHeartbeat.pongTimer) clearTimeout(_bridgeHeartbeat.pongTimer);
_bridgeHeartbeat = null;
}
// 心跳:探测半开连接(休眠/唤醒后 TCP 已断但 readyState 仍为 1),超时则主动断开让周期循环重连
function startBridgeHeartbeat(ws) {
stopBridgeHeartbeat();
const state = { pingTimer: null, pongTimer: null };
state.pingTimer = setInterval(function () {
if (ws.readyState !== 1) return;
try { ws.ping(); } catch (e) { return; }
state.pongTimer = setTimeout(function () {
console.error('[Bridge] 心跳无响应,主动断开重建连接');
try { ws.terminate(); } catch (e) { /* ignore */ }
}, 10000);
}, 15000);
ws.on('pong', function () {
if (state.pongTimer) { clearTimeout(state.pongTimer); state.pongTimer = null; }
});
_bridgeHeartbeat = state;
}
// 响应超时后销毁当前桥接(可能半开),强制后续调用重建连接
function invalidateBackendBridge() {
stopBridgeHeartbeat();
if (backendWS) {
try { backendWS.terminate(); } catch (e) { /* ignore */ }
}
backendWS = null;
_bridgeConnectPromise = null;
}
async function ensureBackendBridge() {
if (!app.isPackaged || backendApp) return;
if (backendWS && backendWS.readyState === 1) return;
@ -143,12 +172,13 @@ async function ensureBackendBridge() {
}
} catch (e) { /* ignore */ }
});
ws.on('close', function () { backendWS = null; _bridgeConnectPromise = null; });
ws.on('error', function () { backendWS = null; _bridgeConnectPromise = null; });
ws.on('close', function () { stopBridgeHeartbeat(); backendWS = null; _bridgeConnectPromise = null; });
ws.on('error', function () { stopBridgeHeartbeat(); backendWS = null; _bridgeConnectPromise = null; });
startBridgeHeartbeat(ws);
resolve();
});
ws.on('error', function (err) { if (!connected) { _bridgeConnectPromise = null; reject(err); } });
setTimeout(function () { if (!connected) { _bridgeConnectPromise = null; reject(new Error('Bridge timeout')); } }, 5000);
setTimeout(function () { if (!connected) { _bridgeConnectPromise = null; reject(new Error('Bridge timeout')); } }, 15000);
});
})();
@ -184,7 +214,7 @@ async function handleServiceCall(method, data, allowRetry) {
if (settled) return;
try {
var resp = JSON.parse(raw.toString());
if (resp.method === method || resp._msgId === mid) {
if (resp._msgId === mid || resp._callId === mid) {
settled = true;
if (_ws && _ws.removeListener) _ws.removeListener('message', handler);
resolve(resp);
@ -197,8 +227,10 @@ async function handleServiceCall(method, data, allowRetry) {
if (settled) return;
settled = true;
if (_ws && _ws.removeListener) _ws.removeListener('message', handler);
console.error('[Bridge] 响应超时:', method);
invalidateBackendBridge();
resolve({ success: false, method: method, message: 'Bridge timeout' });
}, 10000);
}, 30000);
});
}
return { success: false, method, message: 'WSClient not ready' };
@ -233,7 +265,7 @@ async function handleServiceCall(method, data, allowRetry) {
if (settled) return;
try {
var resp = JSON.parse(raw.toString());
if (resp.method === method || resp._msgId === mid) {
if (resp._msgId === mid || resp._callId === mid) {
settled = true;
if (_ws2 && _ws2.removeListener) _ws2.removeListener('message', handler);
resolve(resp);
@ -246,8 +278,10 @@ async function handleServiceCall(method, data, allowRetry) {
if (settled) return;
settled = true;
if (_ws2 && _ws2.removeListener) _ws2.removeListener('message', handler);
console.error('[Bridge] 响应超时:', method);
invalidateBackendBridge();
resolve({ success: false, method: method, message: 'Bridge timeout' });
}, 10000);
}, 30000);
});
}
@ -652,10 +686,8 @@ function cleanupEventForwarding() {
console.log('[Main] 事件转发已清理');
}
async function getWindowsServiceHelper() {
return loadWorkspaceModule('utils/windowsService.js');
}
// 注意:本函数必须保持同步(内部无 await),否则 spawn 收到的 args 会变成 Promise 对象,
// 子进程 argv 变成 "[object Promise]",isHeadlessRunner 判定失败,因单实例锁被壳持有而秒退。
function getManagedBackendArgs() {
if (app.isPackaged) {
return [BACKEND_RUNNER_ARG];
@ -670,24 +702,28 @@ function startManagedBackend() {
}
backendProcess = spawn(process.execPath, getManagedBackendArgs(), {
stdio: 'ignore',
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true
});
backendProcess.once('exit', () => {
backendProcess = null;
});
}
async function stopManagedBackend() {
if (!backendProcess) {
return;
// 诊断:后端子进程输出落盘,便于排查拉起失败(stdio ignore 会丢弃崩溃信息)
try {
const fs = require('fs');
const logPath = path.join('C:\\ProgramData\\printServer', 'backend-runner.log');
const out = fs.createWriteStream(logPath, { flags: 'a' });
out.write('\n===== backend spawn ' + new Date().toISOString() + ' args=' + JSON.stringify(getManagedBackendArgs()) + ' =====\n');
backendProcess.stdout.pipe(out);
backendProcess.stderr.pipe(out);
backendProcess.once('exit', (code, sig) => {
try {
out.write('[exit] code=' + code + ' signal=' + sig + ' at=' + new Date().toISOString() + '\n');
out.end();
} catch (e) { /* ignore */ }
backendProcess = null;
});
} catch (e) {
console.error('[Backend] 诊断日志初始化失败:', e && e.message);
}
const child = backendProcess;
backendProcess = null;
child.kill();
await delay(800);
}
async function ensureDesiredBackendState() {
@ -696,49 +732,8 @@ async function ensureDesiredBackendState() {
return;
}
const config = await readRuntimeConfig();
let backendReady = await isBackendReady();
const serviceHelper = await getWindowsServiceHelper();
if (config.isService) {
try {
const status = await serviceHelper.ensureServiceInstalled(BACKGROUND_SERVICE_OPTIONS);
// 仅在系统服务已接管时才停止本地后端,避免服务未运行时出现周期性停启抖动。
if (status.running) {
if (backendProcess) {
await stopManagedBackend();
backendReady = await isBackendReady();
}
return;
}
if (!backendReady) {
await serviceHelper.startService(BACKGROUND_SERVICE_OPTIONS);
const startedStatus = await serviceHelper.getServiceStatus(BACKGROUND_SERVICE_OPTIONS);
if (startedStatus.running && backendProcess) {
await stopManagedBackend();
backendReady = await isBackendReady();
}
}
// 服务未运行但本地后端可用时,保持本地后端运行,避免 UI 持续断开重连。
return;
} catch (error) {
console.error('[Runtime] 系统服务启动失败,回退到本地后端:', error);
}
} else {
try {
const status = await serviceHelper.getServiceStatus(BACKGROUND_SERVICE_OPTIONS);
if (status.installed) {
await serviceHelper.uninstallService(BACKGROUND_SERVICE_OPTIONS);
backendReady = await isBackendReady();
}
} catch (error) {
console.error('[Runtime] 清理系统服务失败:', error);
}
}
// 打包态:桌面壳直接托管本地后端子进程(系统服务功能已移除)
const backendReady = await isBackendReady();
if (!backendReady && !backendProcess) {
startManagedBackend();
}

View File

@ -1,6 +1,6 @@
{
"name": "printserver",
"version": "1.0.23",
"version": "1.0.37",
"main": "electron/main.cjs",
"scripts": {
"start": "node index.js",
@ -25,6 +25,7 @@
"@xmldom/xmldom": "^0.9.10",
"better-sqlite3": "^12.11.1",
"iconv-lite": "^0.7.2",
"onvif": "^0.8.1",
"ws": "^8.19.0"
},
"optionalDependencies": {
@ -72,10 +73,6 @@
"to": "printserver.ico"
},
"printer.ps1",
{
"from": "daemon",
"to": "daemon"
},
{
"from": "frpc",
"to": "frpc"

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

@ -47,21 +47,25 @@ class FrpcService extends service {
}
/**
* 应用启动时自动拉起(如果 config.frpc.enabled 为 true,或录制模式下自动启用)
* 应用启动时自动拉起(仅录制模式:enabled 或配置了 serverAddr 才启用;
* 非录制服务器不自动穿透,即使历史配置残留 enabled=true)
*/
_autoStart() {
const cfg = this.config.frpc || {};
// 录制模式 + 有 serverAddr 配置 → 自动启用(无论 enabled 字段)
const shouldAutoStart = cfg.enabled || (isRecordingMode(this.config) && cfg.serverAddr);
const recording = isRecordingMode(this.config);
const shouldAutoStart = recording && (!!cfg.enabled || !!cfg.serverAddr);
if (shouldAutoStart) {
_logFile('[Frpc] 自动启动 frpc (enabled=%s, recording=%s)',
!!cfg.enabled, isRecordingMode(this.config));
!!cfg.enabled, recording);
if (!cfg.enabled) {
// 补写 enabled 标记,避免后续 updateConfig 判定混乱
cfg.enabled = true;
this.config.frpc = cfg;
}
this._startFrpc();
} else {
_logFile('[Frpc] 跳过自动启动 (enabled=%s, recording=%s)',
!!cfg.enabled, recording);
}
}

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);
// 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 {
// 清理可能产生的 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;
@ -744,7 +821,13 @@ class HikvisionService extends BaseService {
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 {}
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); }
@ -752,7 +835,7 @@ class HikvisionService extends BaseService {
})();
});
}
async _req(method, url, body, headers, cookieJar, binary = false) {
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('; ');
@ -768,7 +851,9 @@ class HikvisionService extends BaseService {
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 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', () => {

View File

@ -1,13 +1,9 @@
import service from '../core/BaseService.js';
import configUtil from '../utils/config.js';
import { startService, uninstallService } from '../utils/windowsService.js';
function isServiceRunnerProcess() {
return process.argv.includes('--service-runner');
}
import { isElectronRuntime } from '../utils/runtime.js';
function isManagedBackendRunnerProcess() {
return process.argv.includes('--backend-runner') || process.argv.includes('--service-runner');
return process.argv.includes('--backend-runner');
}
function scheduleCurrentProcessExit() {
@ -26,8 +22,6 @@ class SettingService extends service {
super();
this.info = this.info.bind(this);
this.unbind = this.unbind.bind(this);
this.register = this.register.bind(this);
this.unregister = this.unregister.bind(this);
this.updatePorts = this.updatePorts.bind(this);
this.restartBackend = this.restartBackend.bind(this);
this.setToken = this.setToken.bind(this);
@ -43,7 +37,6 @@ class SettingService extends service {
return {
isBind: !!config.token,
name: config.name || '',
isService: !!config.isService,
wsPort: Number(config.wsPort) || 17301,
recording: {
isRecording: !!hik.isRecording,
@ -81,6 +74,7 @@ class SettingService extends service {
const { app } = this;
const targetWsPort = Number(data.wsPort) || Number(app.config?.wsPort) || 17301;
// 托管后端子进程(打包态):退出后由桌面壳 reconcile 循环重新拉起
if (isManagedBackendRunnerProcess()) {
scheduleCurrentProcessExit();
return {
@ -91,6 +85,42 @@ class SettingService extends service {
};
}
// Electron 主进程内嵌后端(开发模式):无法自我重启,重启整个桌面应用
if (isElectronRuntime()) {
if (targetWsPort !== Number(app.config?.wsPort)) {
app.config.wsPort = targetWsPort;
configUtil.write(app.config);
}
try {
const electron = await import('electron');
const electronApp = electron.app || electron.default?.app;
if (!electronApp || typeof electronApp.relaunch !== 'function') {
throw new Error('electron app 对象不可用');
}
// 给 WS 响应留出时间,再重启整个应用
setTimeout(() => {
try {
electronApp.relaunch();
electronApp.exit(0);
} catch (error) {
console.error('[SettingService] 应用重启失败:', error);
}
}, 500);
return {
ok: true,
restarting: true,
wsPort: targetWsPort,
message: '应用正在重启,请稍候'
};
} catch (error) {
return {
ok: false,
restarting: false,
message: `应用重启失败:${error.message}`
};
}
}
if (!app || typeof app.restartBackendRuntime !== 'function') {
return {
ok: false,
@ -134,74 +164,8 @@ class SettingService extends service {
return { ok: true, message: '解绑成功' };
}
// WebSocket 注册服务,切换为“系统服务管理后端”的状态(已弃用,系统服务功能已移除)
// WebSocket 注册服务,切换为“系统服务管理后端”的状态
async register() {
const { config } = this;
const previousIsService = !!config.isService;
try {
await startService();
} catch (error) {
config.isService = previousIsService;
configUtil.write(config);
this.app.isService = previousIsService;
return {
ok: false,
message: `系统服务注册失败:${error.message}`,
isService: previousIsService
};
}
config.isService = true;
configUtil.write(config);
this.app.isService = true;
if (!isServiceRunnerProcess()) {
scheduleCurrentProcessExit();
}
return {
ok: true,
message: isServiceRunnerProcess()
? '服务模式已启用'
: '服务模式已启用,当前前台后端将退出,由系统服务接管',
isService: true
};
}
// WebSocket 注销服务,切回“桌面壳直接拉起后端”的状态
async unregister() {
const { config } = this;
const previousIsService = !!config.isService;
if (!isServiceRunnerProcess()) {
try {
await uninstallService();
} catch (error) {
config.isService = previousIsService;
configUtil.write(config);
this.app.isService = previousIsService;
return {
ok: false,
message: `系统服务注销失败:${error.message}`,
isService: previousIsService
};
}
}
config.isService = false;
configUtil.write(config);
this.app.isService = false;
return {
ok: true,
message: isServiceRunnerProcess()
? '服务模式已关闭,桌面壳会切回本地后端启动并清理系统服务'
: '服务已注销,后端将恢复为桌面壳直接启动',
isService: false
};
}
async setToken(data) {
const { config } = this;
config.token = data.token;
@ -316,10 +280,16 @@ class SettingService extends service {
* data: { rtspUrl, text, x?, y? }
*/
async setCameraOSD(data) {
if (!data || !data.rtspUrl || !data.text) return;
console.log('[CameraOSD] set 收到请求:', JSON.stringify(data));
if (!data || !data.rtspUrl || !data.text) {
console.log('[CameraOSD] set 参数不完整,跳过:', { hasRtsp: !!data?.rtspUrl, hasText: !!data?.text });
return;
}
try {
console.log('[CameraOSD] set 开始执行 rtspUrl=%s text=%s x=%d y=%d', data.rtspUrl, data.text, data.x, data.y);
const { setCameraOSD } = await import('../utils/cameraOsd.js');
await setCameraOSD(data.rtspUrl, data.text, data.x, data.y);
console.log('[CameraOSD] set 执行成功');
} catch (e) {
console.error('[CameraOSD] set 执行失败:', e.message);
}

View File

@ -197,6 +197,19 @@ class UpdateService extends service {
updatedAt: new Date().toISOString()
};
// 下载中状态每个网络 chunk 触发一次(60MB 包约 4000 次),
// 节流到 300ms 一次,避免消息洪泛消耗主进程/渲染进程内存;
// 其他状态(starting/downloaded/installing/failed)立即发送,保证终态不丢。
if (patch.status === 'downloading') {
const now = Date.now();
if (this._lastProgressEmitAt && now - this._lastProgressEmitAt < 300) {
return;
}
this._lastProgressEmitAt = now;
} else {
this._lastProgressEmitAt = 0;
}
this.app.emit('updateDownloadProgress', this._downloadState);
}
@ -338,14 +351,6 @@ class UpdateService extends service {
throw new Error('当前系统不支持自动启动安装程序');
}
if (process.argv.includes('--service-runner')) {
throw new Error('服务模式无法弹出安装向导,请在前台模式下重试');
}
if (this.app?.config?.isService) {
throw new Error('当前处于服务模式,无法直接弹出安装向导,请先注销服务后再更新');
}
const escapedPath = installerPath.replace(/'/g, "''");
const psArgs = [
'-NoProfile',

View File

@ -11,6 +11,8 @@ import { promisify } from 'util';
import fs from 'fs';
import path from 'path';
import os from 'os';
import http from 'http';
import crypto from 'crypto';
const require = createRequire(import.meta.url);
const { Cam } = require('onvif');
@ -34,15 +36,25 @@ const _log = (...a) => _writeLog('INFO', ...a);
const _err = (...a) => _writeLog('ERR', ...a);
/**
* 解析 RTSP URL 提取 [用户名, 密码, 主机]
* 解析 RTSP URL 提取 [用户名, 密码, 主机, 通道号]
* 格式: rtsp://username:password@host:port/path
* 通道解析: /stream2 → 2;/Streaming/Channels/201 → 2;默认 1
*/
function extractRTSPInfo(rtspUrl) {
const match = rtspUrl.match(/^rtsp:\/\/([^:]+):(.+)@([^:/]+)/);
const match = rtspUrl.match(/^rtsp:\/\/([^:]+):(.+)@([^:/]+)(?::(\d+))?(\/\S*)?/);
if (!match) {
throw new Error('RTSP URL 格式无效,期望: rtsp://用户名:密码@主机:端口/路径');
}
return { username: match[1], password: match[2], host: match[3] };
let channel = 1;
const pathPart = match[5] || '';
// 海康风格 /Streaming/Channels/201(第1位数字=通道号)
const hc = pathPart.match(/\/Streaming\/Channels\/(\d)\d{2}/i);
if (hc) channel = parseInt(hc[1], 10);
else {
const sm = pathPart.match(/stream(\d+)/i);
if (sm) channel = parseInt(sm[1], 10);
}
return { username: match[1], password: match[2], host: match[3], channel };
}
/**
@ -62,6 +74,207 @@ export async function clearCameraOSD(rtspUrl) {
return _osdAction(rtspUrl, '', 0, 0, 'clear');
}
/**
* 海康 ISAPI 协议 OSD 设置(当 ONVIF 不可用时回退)
* 接口: GET/PUT /ISAPI/System/Video/inputs/channels/1/overlays/text
* 认证: Basic / Digest 自适应
* @returns {Promise<{ok: boolean, message: string}>}
*/
async function _osdActionIsapi(host, username, password, osdText, posX, posY, mode, channel = 1) {
_log('[ISAPI] 开始设置 OSD host=%s mode=%s channel=%d', host, mode, channel);
try {
const ch = Number.isInteger(channel) && channel >= 1 ? channel : 1;
const baseUri = `/ISAPI/System/Video/inputs/channels/${ch}/overlays/text`;
const mainUri = `/ISAPI/System/Video/inputs/channels/${ch}/overlays`;
let auth = await _isapiAuth(host, username, password, baseUri);
if (!auth) {
return { ok: false, message: 'ISAPI 认证失败(Basic/Digest 均不可用)' };
}
// 401 时自动重新握手并重试一次(nonce 过期/stale 场景)
const authedReq = async (method, uri, body) => {
let resp = await _isapiRequest(host, method, uri, body, auth.headers(method, uri));
if (resp.status === 401) {
const newAuth = await _isapiAuth(host, username, password, baseUri);
if (newAuth) {
auth = newAuth;
resp = await _isapiRequest(host, method, uri, body, auth.headers(method, uri));
}
}
return resp;
};
// 1. 读取现有 OSD
const getResp = await authedReq('GET', baseUri, null);
_log('[ISAPI] GET overlays status=%s body=%s', getResp.status, (getResp.body || '').slice(0, 500));
if (mode === 'clear') {
// 清空:提交空列表
const emptyXml = '<?xml version="1.0" encoding="UTF-8"?>\n' +
'<TextOverlayList xmlns="http://www.hikvision.com/ver20/XMLSchema" version="2.0"></TextOverlayList>';
const putResp = await authedReq('PUT', baseUri, emptyXml);
_log('[ISAPI] clear PUT status=%s body=%s', putResp.status, (putResp.body || '').slice(0, 300));
if (putResp.status >= 200 && putResp.status < 300) {
return { ok: true, message: 'OSD 已清空 (ISAPI)', count: 0 };
}
return { ok: false, message: 'ISAPI 清空 OSD 失败: HTTP ' + putResp.status };
}
// 2. 设置文字:设备字段兼容 positionX/positionY/displayText(回读确认过)
// 坐标系:从 overlays 总接口读 normalizedScreenSize(实测 GV413 为 704x576,
// 与主码流 1920x1080 无关)。Y 轴方向:实测该设备 positionY 小=靠底部(bottom-up),
// 因此 ONVIF 归一化 posY(-1=下, +1=上)映射为 py = (1-posY)/2*H
let width = 704, height = 576;
try {
const mainResp = await authedReq('GET', mainUri, null);
const wm = /<normalizedScreenWidth>(\d+)</.exec(mainResp.body || '');
const hm = /<normalizedScreenHeight>(\d+)</.exec(mainResp.body || '');
if (wm && hm) { width = +wm[1]; height = +hm[1]; }
} catch (_) { /* 用默认 704x576 */ }
_log('[ISAPI] OSD 坐标系 %dx%d (bottom-up Y)', width, height);
// 重试链:normalized 坐标系 → 安全坐标(0,0)
const attempts = [
{ w: width, h: height },
{ w: 0, h: 0 }
];
let putResp = { status: 0, body: '' };
let xml = '';
for (const a of attempts) {
let px, py;
if (a.w === 0) { px = 0; py = 0; }
else {
px = Math.max(0, Math.min(a.w - 8, Math.round((posX + 1) / 2 * a.w)));
py = Math.max(0, Math.min(a.h - 8, Math.round((1 - posY) / 2 * a.h)));
}
xml = '<?xml version="1.0" encoding="UTF-8"?>\n' +
'<TextOverlayList xmlns="http://www.hikvision.com/ver20/XMLSchema" version="2.0">\n' +
'<TextOverlay>\n<id>1</id>\n<enabled>true</enabled>\n' +
`<positionX>${px}</positionX>\n<positionY>${py}</positionY>\n` +
`<displayText>${_xmlEscape(osdText)}</displayText>\n` +
'<isPersistentText>true</isPersistentText>\n' +
'</TextOverlay>\n</TextOverlayList>';
putResp = await authedReq('PUT', baseUri, xml);
_log('[ISAPI] set PUT(%d,%d) status=%s body=%s', px, py, putResp.status, (putResp.body || '').slice(0, 200));
if (putResp.status >= 200 && putResp.status < 300) break;
}
if (!(putResp.status >= 200 && putResp.status < 300)) {
return { ok: false, message: 'ISAPI 设置 OSD 失败: HTTP ' + putResp.status + ' ' + (putResp.body || '').slice(0, 100) };
}
// 3. 回读验证
const verifyResp = await authedReq('GET', baseUri, null);
const body = verifyResp.body || '';
_log('[ISAPI] verify GET status=%s body=%s', verifyResp.status, body.slice(0, 500));
if (mode === 'clear') {
return { ok: true, message: 'OSD 已清空 (ISAPI)', count: 0 };
}
const found = body.includes(_xmlEscape(osdText)) || body.includes(osdText);
if (found) {
_log('[ISAPI] OK OSD 写入成功:', osdText);
return { ok: true, message: 'OSD 设置成功 (ISAPI): ' + osdText, count: 1 };
}
_err('[ISAPI] FAIL 回读验证失败: 期望="' + osdText + '" body=' + body.slice(0, 300));
return { ok: false, message: 'ISAPI OSD 写入验证失败' };
} catch (e) {
_err('[ISAPI] 异常:', e.message);
return { ok: false, message: 'ISAPI OSD 操作异常: ' + e.message };
}
}
function _xmlEscape(s) {
return String(s ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
/**
* ISAPI 认证握手:先无认证请求,401 后按 WWW-Authenticate 选择 Digest 或 Basic
* @returns {Promise<{headers:(method,uri)=>Object}|null>}
*/
async function _isapiAuth(host, username, password, probeUri) {
try {
const probe = await _isapiRequest(host, 'GET', probeUri, null, {});
const wwwAuth = (probe.headers['www-authenticate'] || '') + ' ' + ((probe.body && probe.status === 401) ? '' : '');
_log('[ISAPI] 探测 status=%s WWW-Authenticate=%s', probe.status, (probe.headers['www-authenticate'] || '无').slice(0, 120));
// 有些设备直接返回 200(无认证)
if (probe.status !== 401 && probe.status !== 0) {
return { headers: () => ({}) };
}
const wa = probe.headers['www-authenticate'] || '';
if (/digest/i.test(wa)) {
const realm = /realm="([^"]*)"/i.exec(wa)?.[1] || '';
const nonce = /nonce="([^"]*)"/i.exec(wa)?.[1] || '';
const qop = /qop="([^"]*)"/i.exec(wa)?.[1] || 'auth';
const opaque = /opaque="([^"]*)"/i.exec(wa)?.[1] || '';
if (!realm || !nonce) return null;
return {
headers: (method, uri) => {
const cnonce = crypto.randomBytes(8).toString('hex');
const nc = '00000001';
const ha1 = _md5(`${username}:${realm}:${password}`);
const ha2 = _md5(`${method}:${uri}`);
const response = _md5(`${ha1}:${nonce}:${nc}:${cnonce}:${qop}:${ha2}`);
let h = `Digest username="${username}", realm="${realm}", nonce="${nonce}", uri="${uri}", response="${response}", qop=${qop}, nc=${nc}, cnonce="${cnonce}"`;
if (opaque) h += `, opaque="${opaque}"`;
return { Authorization: h };
}
};
}
// Basic
const basic = 'Basic ' + Buffer.from(`${username}:${password}`).toString('base64');
return { headers: () => ({ Authorization: basic }) };
} catch (e) {
_err('[ISAPI] 认证探测异常:', e.message);
return null;
}
}
function _md5(s) {
return crypto.createHash('md5').update(s, 'utf8').digest('hex');
}
/** 嗅探设备是否支持海康 ISAPI 协议(快速 GET /ISAPI/System/deviceInfo) */
async function _isapiProbe(host) {
try {
const resp = await _isapiRequest(host, 'GET', '/ISAPI/System/deviceInfo', null, {}, 2500);
// 200 = 无需认证;401 = 接口存在需认证;404/其他 = 不支持
if (resp.status === 200 || resp.status === 401) {
_log('[ISAPI] 嗅探成功 host=%s status=%d', host, resp.status);
return true;
}
_log('[ISAPI] 嗅探不支持 host=%s status=%d', host, resp.status);
return false;
} catch (e) {
_log('[ISAPI] 嗅探失败 host=%s: %s', host, e.message);
return false;
}
}
/** 原生 HTTP 请求(带 Content-Length,避免 chunked 被设备拒绝) */
function _isapiRequest(host, method, uri, body, headers, timeoutMs = 8000) {
return new Promise((resolve, reject) => {
const h = { ...headers };
if (body != null) {
h['Content-Type'] = 'application/xml';
h['Content-Length'] = Buffer.byteLength(body);
}
const req = http.request({ host, port: 80, path: uri, method, headers: h, timeout: timeoutMs }, (res) => {
let data = '';
res.on('data', (c) => (data += c));
res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: data }));
});
req.on('timeout', () => { req.destroy(); reject(new Error('ISAPI 请求超时')); });
req.on('error', reject);
if (body != null) req.write(body);
req.end();
});
}
/**
* OSD 核心操作
* @param {string} mode - 'replace'=删旧建新, 'append'=叠加追加, 'clear'=只删不建
@ -69,24 +282,38 @@ export async function clearCameraOSD(rtspUrl) {
async function _osdAction(rtspUrl, osdText, posX, posY, mode) {
_log('收到 OSD 请求, rtspUrl:', rtspUrl.replace(/:[^:@]+@/, ':****@'), 'text:', osdText, 'pos:', posX, posY, 'mode:', mode);
const info = extractRTSPInfo(rtspUrl);
_log('连接摄像头:', info.host, '用户:', info.username);
_log('连接摄像头:', info.host, '用户:', info.username, '通道:', info.channel);
// 0. 先嗅探 ISAPI(海康系设备):可用则直接走 ISAPI,无需试 ONVIF
if (await _isapiProbe(info.host)) {
_log('探测到 ISAPI 协议(海康系设备),直接使用 ISAPI');
return _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel);
}
// 1. ONVIF 尝试:端口依次 80(标准)→ 2020(MIPC 等非标),全失败回退 ISAPI
return new Promise((resolve) => {
new Cam({
hostname: info.host,
username: info.username,
password: info.password,
port: 2020,
timeout: 10000,
preserveAddress: true
}, async function (err) {
if (err) {
_err('连接失败:', err.message);
return resolve({ ok: false, message: `连接摄像头失败: ${err.message}` });
}
const cam = this;
try {
const onvifPorts = [80, 2020];
const tryPort = (idx) => {
_log('尝试 ONVIF 端口:', onvifPorts[idx]);
new Cam({
hostname: info.host,
username: info.username,
password: info.password,
port: onvifPorts[idx],
timeout: 6000,
preserveAddress: true
}, async function (err) {
if (err) {
_err('ONVIF 端口 %d 失败:', onvifPorts[idx], err.message);
if (idx + 1 < onvifPorts.length) { tryPort(idx + 1); return; }
_log('ONVIF 全部失败 → 回退海康 ISAPI 协议');
resolve(await _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel));
return;
}
// ONVIF 连接成功,执行原逻辑
const cam = this;
(async () => {
try {
// 转为 Promise 风格
const getOSDs = promisify(cam.getOSDs).bind(cam);
const createOSD = promisify(cam.createOSD).bind(cam);
@ -163,13 +390,16 @@ async function _osdAction(rtspUrl, osdText, posX, posY, mode) {
_log('OK OSD 写入成功:', osdText);
resolve({ ok: true, message: 'OSD 设置成功: ' + osdText, count: textOSDs.length });
} else {
_err('FAIL OSD 写入失败: 期望="' + osdText + '" 实际=[' + verifyTexts + ']');
resolve({ ok: false, message: 'OSD 写入验证失败' });
_err('ONVIF FAIL OSD 写入失败: 期望="' + osdText + '" 实际=[' + verifyTexts + '] → 回退海康 ISAPI 协议');
resolve(await _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel));
}
} catch (e) {
_err('操作失败:', e.message);
resolve({ ok: false, message: `OSD 操作失败: ${e.message}` });
}
});
} catch (e) {
_err('ONVIF 操作失败:', e.message, '→ 回退海康 ISAPI 协议');
resolve(await _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel));
}
})();
});
};
tryPort(0);
});
}

View File

@ -1,289 +0,0 @@
import fs from 'fs';
import path from 'path';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { getProjectRoot, getResourcePath, isElectronRuntime, isPackagedElectron } from './runtime.js';
const execFileAsync = promisify(execFile);
const SERVICE_NAME = 'PrintServer';
const SERVICE_ID = 'printserver.exe';
function assertWindows() {
if (process.platform !== 'win32') {
throw new Error('Windows 服务能力仅支持 Windows 环境');
}
}
function escapeXml(value) {
return String(value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
function getServiceWrapperPath() {
return getResourcePath('daemon', SERVICE_ID);
}
function getServiceXmlPath() {
return getResourcePath('daemon', 'printserver.xml');
}
function getServiceWorkingDirectory() {
if (isPackagedElectron()) {
return path.dirname(process.execPath);
}
return getProjectRoot();
}
function getServiceCommandDefinition() {
if (isElectronRuntime()) {
return {
executable: process.execPath,
arguments: isPackagedElectron() ? ['--service-runner'] : [getProjectRoot(), '--service-runner'],
workingDirectory: getServiceWorkingDirectory()
};
}
return {
executable: process.execPath,
arguments: [path.join(getProjectRoot(), 'index.js')],
workingDirectory: getProjectRoot()
};
}
function buildServiceXml() {
const command = getServiceCommandDefinition();
const argumentLines = command.arguments
.map((argument) => ` <argument>${escapeXml(argument)}</argument>`)
.join('\n');
return [
'<service>',
` <id>${SERVICE_ID}</id>`,
` <name>${SERVICE_NAME}</name>`,
' <description>printServer backend service</description>',
` <executable>${escapeXml(command.executable)}</executable>`,
argumentLines,
' <logmode>rotate</logmode>',
' <startmode>Automatic</startmode>',
' <stoptimeout>30sec</stoptimeout>',
` <workingdirectory>${escapeXml(command.workingDirectory)}</workingdirectory>`,
'</service>',
''
].join('\n');
}
export function ensureServiceDefinition() {
assertWindows();
const wrapperPath = getServiceWrapperPath();
const xmlPath = getServiceXmlPath();
if (!fs.existsSync(wrapperPath)) {
throw new Error(`服务包装器不存在: ${wrapperPath}`);
}
const expectedXml = buildServiceXml();
const currentXml = fs.existsSync(xmlPath) ? fs.readFileSync(xmlPath, 'utf8') : '';
if (currentXml !== expectedXml) {
fs.writeFileSync(xmlPath, expectedXml, 'utf8');
}
return {
name: SERVICE_NAME,
id: SERVICE_ID,
wrapperPath,
xmlPath,
workingDirectory: getServiceWorkingDirectory()
};
}
function isAccessDeniedErrorMessage(message) {
if (!message) {
return false;
}
return /AccessDenied|拒绝访问|\b0x5\b|\berror\s*5\b/i.test(String(message));
}
function isServiceAlreadyExistsErrorMessage(message) {
if (!message) {
return false;
}
return /already exists|已存在|Service with id\s*'?.+?'?\s*already exists/i.test(String(message));
}
function isServiceAlreadyRunningErrorMessage(message) {
if (!message) {
return false;
}
return /already started|already running|已启动|正在运行/i.test(String(message));
}
async function runWrapperCommandElevated(command, metadata) {
const escapedWrapperPath = metadata.wrapperPath.replace(/'/g, "''");
const escapedCommand = String(command).replace(/'/g, "''");
const escapedWorkingDirectory = path.dirname(metadata.wrapperPath).replace(/'/g, "''");
const psCommand = [
"$proc = Start-Process",
`-FilePath '${escapedWrapperPath}'`,
`-ArgumentList '${escapedCommand}'`,
`-WorkingDirectory '${escapedWorkingDirectory}'`,
'-Verb RunAs',
'-WindowStyle Hidden',
'-PassThru',
'-Wait;',
'exit $proc.ExitCode'
].join(' ');
try {
await execFileAsync('powershell.exe', ['-NoProfile', '-Command', psCommand], {
windowsHide: true
});
} catch (error) {
const stdout = (error.stdout || '').trim();
const stderr = (error.stderr || '').trim();
const details = [stdout, stderr, error.message].filter(Boolean).join(' | ');
throw new Error(`提权执行服务命令 ${command} 失败: ${details}`);
}
return {
stdout: '',
stderr: ''
};
}
async function runWrapperCommand(command, options = {}) {
const {
allowElevation = true
} = options;
const metadata = ensureServiceDefinition();
try {
const result = await execFileAsync(metadata.wrapperPath, [command], {
cwd: path.dirname(metadata.wrapperPath),
windowsHide: true
});
return {
stdout: (result.stdout || '').trim(),
stderr: (result.stderr || '').trim()
};
} catch (error) {
const stdout = (error.stdout || '').trim();
const stderr = (error.stderr || '').trim();
const details = [stdout, stderr, error.message].filter(Boolean).join(' | ');
if (allowElevation && command !== 'status' && isAccessDeniedErrorMessage(details)) {
try {
return await runWrapperCommandElevated(command, metadata);
} catch (elevatedError) {
throw new Error(`执行服务命令 ${command} 失败: ${details} | ${elevatedError.message}`);
}
}
throw new Error(`执行服务命令 ${command} 失败: ${details}`);
}
}
function parseServiceStatus(rawStatus) {
const normalized = (rawStatus || '').trim();
if (!normalized || normalized === 'NonExistent') {
return {
installed: false,
running: false,
rawStatus: normalized || 'NonExistent'
};
}
return {
installed: true,
running: /started|running|active/i.test(normalized),
rawStatus: normalized
};
}
export async function getServiceStatus(options = {}) {
const { stdout } = await runWrapperCommand('status', options);
return parseServiceStatus(stdout);
}
export async function ensureServiceInstalled(options = {}) {
let status = null;
try {
status = await getServiceStatus(options);
} catch (error) {
status = null;
}
if (status && status.installed) {
return status;
}
try {
await runWrapperCommand('install', options);
} catch (error) {
if (!isServiceAlreadyExistsErrorMessage(error.message)) {
throw error;
}
}
try {
return await getServiceStatus(options);
} catch (error) {
// 某些机器上 status 读取异常,但 install 已提示“已存在”。此时按已安装处理。
return {
installed: true,
running: false,
rawStatus: 'Existing'
};
}
}
export async function startService(options = {}) {
const status = await ensureServiceInstalled(options);
if (status.running) {
return status;
}
try {
await runWrapperCommand('start', options);
} catch (error) {
if (!isServiceAlreadyRunningErrorMessage(error.message)) {
throw error;
}
}
return getServiceStatus(options);
}
export async function stopService(options = {}) {
const status = await getServiceStatus(options);
if (!status.installed || !status.running) {
return status;
}
await runWrapperCommand('stop', options);
return getServiceStatus(options);
}
export async function uninstallService(options = {}) {
const status = await getServiceStatus(options);
if (!status.installed) {
return status;
}
if (status.running) {
await runWrapperCommand('stop', options);
}
await runWrapperCommand('uninstall', options);
return getServiceStatus(options);
}

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) {
@ -1276,7 +1321,8 @@
};
}
} else {
alert(data.message || '获取绑定状态失败!');
// 每 10 秒轮询调用:失败静默处理,避免模态弹窗阻塞页面,状态会自动恢复
console.warn('[UI] 获取绑定状态失败:', data.message || '');
}
});
},
@ -1631,17 +1677,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 +1723,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; }
}
});
})();
@ -1691,30 +1739,46 @@
var ws = mainApp.wsStatus;
var items = statusEl.querySelectorAll('.status-item');
var html0 = '', html1 = '', html2 = '';
if (items[0]) {
var c = ws[mainApp.wsClientStatus] || ws.connected;
items[0].innerHTML = '<span class="status-dot" style="background:' + c.color + '"></span>' +
html0 = '<span class="status-dot" style="background:' + c.color + '"></span>' +
'<span>本地服务:<strong style="color:' + c.color + '">' + c.title + '</strong></span>';
}
if (items[1]) {
var s = ws[mainApp.wsServerStatus] || ws.disconnected;
items[1].innerHTML = '<span class="status-dot" style="background:' + s.color + '"></span>' +
html1 = '<span class="status-dot" style="background:' + s.color + '"></span>' +
'<span>服务器连接:<strong style="color:' + s.color + '">' + s.title + '</strong></span>';
}
if (items[2]) {
var bindC = mainApp.isBind ? '#107c10' : '#c42b1c';
var bindT = mainApp.isBind ? '已绑定' : '未绑定';
var clickable = mainApp.isBind ? 'cursor:pointer;text-decoration:underline' : '';
items[2].innerHTML = '<span class="status-dot" style="background:' + bindC + '"></span>' +
html2 = '<span class="status-dot" style="background:' + bindC + '"></span>' +
'<span>打印服务绑定:<strong style="color:' + bindC + ';' + clickable + '" id="bindStatusText">' + bindT + '</strong></span>';
}
// 仅在内容变化时写 DOM,避免每 500ms 全量重建节点
if (!lastSbHtml) lastSbHtml = {};
if (lastSbHtml[0] !== html0) { lastSbHtml[0] = html0; if (items[0]) items[0].innerHTML = html0; }
if (lastSbHtml[1] !== html1) { lastSbHtml[1] = html1; if (items[1]) items[1].innerHTML = html1; }
if (lastSbHtml[2] !== html2) { lastSbHtml[2] = html2; if (items[2]) items[2].innerHTML = html2; }
var btns = statusEl.querySelectorAll('button');
if (btns[0]) btns[0].textContent = mainApp.updateChecking ? '检查中...' : '检查更新';
if (btns[1]) { btns[1].textContent = mainApp.restartingBackend ? '重启中...' : '重启服务'; btns[1].disabled = mainApp.restartingBackend; }
if (btns[0]) {
var btn0Text = mainApp.updateChecking ? '检查中...' : '检查更新';
if (btns[0].textContent !== btn0Text) btns[0].textContent = btn0Text;
}
if (btns[1]) {
var btn1Text = mainApp.restartingBackend ? '重启中...' : '重启服务';
if (btns[1].textContent !== btn1Text) btns[1].textContent = btn1Text;
btns[1].disabled = mainApp.restartingBackend;
}
}
var lastSbHtml = null;
// 绑定按钮事件
var btnCheck = document.getElementById('btnCheckUpdate');
if (btnCheck) {

View File

@ -227,10 +227,6 @@
<span class="status-label">本地服务:</span>
<span class="status-value" :style="{color: wsStatus[wsClientStatus].color}">{{ wsStatus[wsClientStatus].title }}</span>
</div>
<div class="status-item">
<span class="status-label">服务注册:</span>
<span class="status-value" :style="{color: isServices ? 'green' : 'red'}" @click="isServices ? unregister() : register()" style="cursor:pointer;">{{ isServices ? '已注册' : '未注册' }}</span>
</div>
<div class="status-item">
<span class="status-label">服务器连接:</span>
<span class="status-value" :style="{color: wsStatus[wsServerStatus].color}">{{ wsStatus[wsServerStatus].title }}</span>
@ -350,8 +346,7 @@ new Vue({
'disconnected': { title: '未连接', color: 'red' },
'connected': { title: '已连接', color: 'green' },
'error': { title: '连接错误', color: 'red' },
},
isServices: false
}
},
methods: {
loadComponents() {
@ -387,20 +382,6 @@ new Vue({
}
});
},
register() {
wsSendWithCallback('setting.register', {}, (data) => {
if (data.success) {
this.isServices = data.result || '';
}
});
},
unregister() {
wsSendWithCallback('setting.unregister', {}, (data) => {
if (data.success) {
this.isServices = data.result || '';
}
});
},
isBind() {
wsSendWithCallback('setting.info', {}, (data) => {
if (data.success) {