feat: Linux录制模式支持 - 平台适配/frpc/打印守卫
This commit is contained in:
parent
da67b15465
commit
4e9135c9f4
@ -354,7 +354,7 @@ function Ensure-PackagedResources() {
|
|||||||
Copy-Item -Path $iconSourcePath -Destination $iconTargetPath -Force
|
Copy-Item -Path $iconSourcePath -Destination $iconTargetPath -Force
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($dirName in @('daemon')) {
|
foreach ($dirName in @('daemon', 'frpc')) {
|
||||||
$sourcePath = Join-Path $root $dirName
|
$sourcePath = Join-Path $root $dirName
|
||||||
$targetPath = Join-Path $resourcesDir $dirName
|
$targetPath = Join-Path $resourcesDir $dirName
|
||||||
|
|
||||||
|
|||||||
26
config.json
26
config.json
@ -1,6 +1,16 @@
|
|||||||
{
|
{
|
||||||
"port": 3000,
|
"wsPort": 17301,
|
||||||
"wsPort": 3001,
|
"wsPorts": [
|
||||||
|
17301,
|
||||||
|
17302,
|
||||||
|
17303
|
||||||
|
],
|
||||||
|
"httpPort": 17311,
|
||||||
|
"httpPorts": [
|
||||||
|
17311,
|
||||||
|
17312,
|
||||||
|
17313
|
||||||
|
],
|
||||||
"logLevel": "info",
|
"logLevel": "info",
|
||||||
"printerDefault": "",
|
"printerDefault": "",
|
||||||
"maxPrintJobs": 10,
|
"maxPrintJobs": 10,
|
||||||
@ -9,8 +19,14 @@
|
|||||||
"url": "ws://printer.wms.gztbyc.com/ws",
|
"url": "ws://printer.wms.gztbyc.com/ws",
|
||||||
"reconnectInterval": 3000
|
"reconnectInterval": 3000
|
||||||
},
|
},
|
||||||
|
"hikvision": {
|
||||||
|
"downloadDir": "G:/gameauto/recordings",
|
||||||
|
"maxStorage": "50GB",
|
||||||
|
"circularRecording": true
|
||||||
|
},
|
||||||
"refreshTokenExpireTime": 0,
|
"refreshTokenExpireTime": 0,
|
||||||
"tokenExpireTime": 1780684406126,
|
"tokenExpireTime": 1784925603819,
|
||||||
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3YXJlaG91c2UiOiIxMDAwMDAiLCJjb21wdXRlcklkIjoiMjgiLCJpYXQiOjE3ODA2ODA4MDYsImV4cCI6MTc4MDY4NDQwNn0.O3Kzn4dVqkzSY8YT6nN_RpulznGPq4_LY6SY6o30cGk",
|
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3YXJlaG91c2UiOiIxMDAwMDAiLCJjb21wdXRlcklkIjoiMjgiLCJpYXQiOjE3ODQ5MjIwMDMsImV4cCI6MTc4NDkyNTYwM30.lpXdfZaIgoJhW0neOT6tzg7JhqFqfmVytWgkwgQlmc8",
|
||||||
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3YXJlaG91c2UiOiIxMDAwMDAiLCJjb21wdXRlcklkIjoiMjgiLCJpYXQiOjE3Nzg2MTAwNDMsImV4cCI6NDkzNDM3MDA0M30.JkOtPdc6VA5IDxy6E6Pqk5nffmE5VagoXtXYr7cNLZc"
|
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3YXJlaG91c2UiOiIxMDAwMDAiLCJjb21wdXRlcklkIjoiMjgiLCJpYXQiOjE3Nzg2MTAwNDMsImV4cCI6NDkzNDM3MDA0M30.JkOtPdc6VA5IDxy6E6Pqk5nffmE5VagoXtXYr7cNLZc",
|
||||||
|
"name": ""
|
||||||
}
|
}
|
||||||
@ -1,6 +1,8 @@
|
|||||||
{
|
{
|
||||||
"port": 3000,
|
"wsPort": 17301,
|
||||||
"wsPort": 3001,
|
"wsPorts": [17301, 17302, 17303],
|
||||||
|
"httpPort": 17311,
|
||||||
|
"httpPorts": [17311, 17312, 17313],
|
||||||
"logLevel": "info",
|
"logLevel": "info",
|
||||||
"printerDefault": "",
|
"printerDefault": "",
|
||||||
"maxPrintJobs": 10,
|
"maxPrintJobs": 10,
|
||||||
@ -9,6 +11,11 @@
|
|||||||
"url": "ws://printer.wms.gztbyc.com/ws",
|
"url": "ws://printer.wms.gztbyc.com/ws",
|
||||||
"reconnectInterval": 3000
|
"reconnectInterval": 3000
|
||||||
},
|
},
|
||||||
|
"hikvision": {
|
||||||
|
"downloadDir": "G:/gameauto/recordings",
|
||||||
|
"maxStorage": "50GB",
|
||||||
|
"circularRecording": true
|
||||||
|
},
|
||||||
"update": {
|
"update": {
|
||||||
"feedUrl": "https://dl.wms.gztbyc.com/printServer/latest.json",
|
"feedUrl": "https://dl.wms.gztbyc.com/printServer/latest.json",
|
||||||
"downloadBaseUrl": "https://dl.wms.gztbyc.com/printServer"
|
"downloadBaseUrl": "https://dl.wms.gztbyc.com/printServer"
|
||||||
|
|||||||
1685
core/main.js
1685
core/main.js
File diff suppressed because it is too large
Load Diff
@ -108,7 +108,6 @@ class WSClient {
|
|||||||
if (this.status === 'connected') {
|
if (this.status === 'connected') {
|
||||||
this.send('ping');
|
this.send('ping');
|
||||||
const { token, refreshToken, tokenExpireTime } = this.app.config;
|
const { token, refreshToken, tokenExpireTime } = this.app.config;
|
||||||
console.log(this.app.info,"this.app.info的值")
|
|
||||||
if (!this.app.info && token && refreshToken && tokenExpireTime) {
|
if (!this.app.info && token && refreshToken && tokenExpireTime) {
|
||||||
if (tokenExpireTime < Date.now()) {
|
if (tokenExpireTime < Date.now()) {
|
||||||
//console.log('[WSClient] 心跳检测: token 已过期,尝试刷新');
|
//console.log('[WSClient] 心跳检测: token 已过期,尝试刷新');
|
||||||
@ -136,7 +135,6 @@ class WSClient {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const { method, data } = parsed;
|
const { method, data } = parsed;
|
||||||
//console.log('[WSClient] 可用服务列表:', method, this.services, '方法:', method);
|
|
||||||
if (!method) {
|
if (!method) {
|
||||||
//this.send({ success: false, message: '消息缺少 method 字段' });
|
//this.send({ success: false, message: '消息缺少 method 字段' });
|
||||||
return;
|
return;
|
||||||
@ -145,9 +143,12 @@ class WSClient {
|
|||||||
let serviceFn = this.services;
|
let serviceFn = this.services;
|
||||||
for (let i = 0; i < methodPath.length; i++) {
|
for (let i = 0; i < methodPath.length; i++) {
|
||||||
serviceFn = serviceFn[methodPath[i]];
|
serviceFn = serviceFn[methodPath[i]];
|
||||||
//console.log("serviceFn", serviceFn,methodPath[i]);
|
|
||||||
if (!serviceFn) break;
|
if (!serviceFn) break;
|
||||||
}
|
}
|
||||||
|
// 调试:打印非高频方法的路由情况
|
||||||
|
if (method && method !== 'base.printerList' && method !== 'printerComponent.statusChange' && method !== 'setting.setToken' && method !== 'setting.setInfo') {
|
||||||
|
console.log('[WSClient] 方法路由:', method, typeof serviceFn === 'function' ? 'OK' : 'MISSING');
|
||||||
|
}
|
||||||
if (typeof serviceFn === 'function') {
|
if (typeof serviceFn === 'function') {
|
||||||
try {
|
try {
|
||||||
const result = await serviceFn(data);
|
const result = await serviceFn(data);
|
||||||
|
|||||||
122
core/wsServer.js
122
core/wsServer.js
@ -2,14 +2,23 @@ import { WebSocketServer } from 'ws';
|
|||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { pathToFileURL } from 'url';
|
import { pathToFileURL } from 'url';
|
||||||
|
import { isRecordingMode } from '../utils/runtime.js';
|
||||||
|
|
||||||
class WSServer {
|
class WSServer {
|
||||||
constructor(port, app, options = {}) {
|
/**
|
||||||
this.port = port || 8081;
|
* @param {number|number[]} portCandidates 单个端口或端口候选数组
|
||||||
|
* @param {object} app Main 实例
|
||||||
|
* @param {object} options WebSocketServer 额外选项
|
||||||
|
*/
|
||||||
|
constructor(portCandidates, app, options = {}) {
|
||||||
|
this.portCandidates = Array.isArray(portCandidates)
|
||||||
|
? portCandidates.filter(p => Number.isFinite(p) && p > 0)
|
||||||
|
: (Number.isFinite(portCandidates) && portCandidates > 0 ? [portCandidates] : [8081]);
|
||||||
|
this.port = null; // 实际监听的端口(_start 成功后赋值)
|
||||||
this.options = options;
|
this.options = options;
|
||||||
this.server = null;
|
this.server = null;
|
||||||
this.clients = new Set();
|
this.clients = new Set();
|
||||||
this.services = app.services; // 从 app 获取服务实例
|
this.services = app.services;
|
||||||
this.app = app;
|
this.app = app;
|
||||||
this._eventHandlers = {};
|
this._eventHandlers = {};
|
||||||
this._start();
|
this._start();
|
||||||
@ -46,12 +55,24 @@ class WSServer {
|
|||||||
this._eventHandlers.updateDownloadProgress = (data) => {
|
this._eventHandlers.updateDownloadProgress = (data) => {
|
||||||
this.broadcast({ success: true, method: 'update.downloadProgress', result: data });
|
this.broadcast({ success: true, method: 'update.downloadProgress', result: data });
|
||||||
};
|
};
|
||||||
|
this._eventHandlers.infoChanged = (data) => {
|
||||||
|
this.broadcast({ success: true, method: 'setting.infoChanged', result: data });
|
||||||
|
};
|
||||||
|
this._eventHandlers.frpcStatusChange = (data) => {
|
||||||
|
this.broadcast({ success: true, method: 'frpc.statusChange', result: data });
|
||||||
|
};
|
||||||
|
this._eventHandlers.migrationNeeded = (data) => {
|
||||||
|
this.broadcast({ success: true, method: 'setting.migrationNeeded', result: data });
|
||||||
|
};
|
||||||
|
|
||||||
this.app.on('printerComponentStatusChange', this._eventHandlers.printerComponentStatusChange);
|
this.app.on('printerComponentStatusChange', this._eventHandlers.printerComponentStatusChange);
|
||||||
this.app.on('wsClientStatusChange', this._eventHandlers.wsClientStatusChange);
|
this.app.on('wsClientStatusChange', this._eventHandlers.wsClientStatusChange);
|
||||||
this.app.on('generateCode', this._eventHandlers.generateCode);
|
this.app.on('generateCode', this._eventHandlers.generateCode);
|
||||||
this.app.on('printerList', this._eventHandlers.printerList);
|
this.app.on('printerList', this._eventHandlers.printerList);
|
||||||
this.app.on('updateDownloadProgress', this._eventHandlers.updateDownloadProgress);
|
this.app.on('updateDownloadProgress', this._eventHandlers.updateDownloadProgress);
|
||||||
|
this.app.on('infoChanged', this._eventHandlers.infoChanged);
|
||||||
|
this.app.on('frpcStatusChange', this._eventHandlers.frpcStatusChange);
|
||||||
|
this.app.on('migrationNeeded', this._eventHandlers.migrationNeeded);
|
||||||
}
|
}
|
||||||
|
|
||||||
_unbindAppEvents() {
|
_unbindAppEvents() {
|
||||||
@ -74,35 +95,69 @@ class WSServer {
|
|||||||
if (this._eventHandlers.updateDownloadProgress) {
|
if (this._eventHandlers.updateDownloadProgress) {
|
||||||
this.app.off('updateDownloadProgress', this._eventHandlers.updateDownloadProgress);
|
this.app.off('updateDownloadProgress', this._eventHandlers.updateDownloadProgress);
|
||||||
}
|
}
|
||||||
|
if (this._eventHandlers.infoChanged) {
|
||||||
|
this.app.off('infoChanged', this._eventHandlers.infoChanged);
|
||||||
|
}
|
||||||
|
if (this._eventHandlers.frpcStatusChange) {
|
||||||
|
this.app.off('frpcStatusChange', this._eventHandlers.frpcStatusChange);
|
||||||
|
}
|
||||||
|
if (this._eventHandlers.migrationNeeded) {
|
||||||
|
this.app.off('migrationNeeded', this._eventHandlers.migrationNeeded);
|
||||||
|
}
|
||||||
|
|
||||||
this._eventHandlers = {};
|
this._eventHandlers = {};
|
||||||
}
|
}
|
||||||
_start() {
|
_start() {
|
||||||
this.server = new WebSocketServer({ port: this.port, ...this.options });
|
const tryPort = (index) => {
|
||||||
this.server.on('connection', (ws, req) => {
|
if (index >= this.portCandidates.length) {
|
||||||
this.clients.add(ws);
|
console.error('[WSServer] 所有端口均被占用:', this.portCandidates);
|
||||||
//console.log('[WSServer] 新客户端连接,当前连接数:', this.clients.size);
|
return;
|
||||||
if (typeof this.onConnection === 'function') {
|
|
||||||
this.onConnection(ws, req);
|
|
||||||
}
|
}
|
||||||
ws.on('message', (msg) => {
|
const candidate = this.portCandidates[index];
|
||||||
//console.log('[WSServer] 收到消息:', msg);
|
const server = new WebSocketServer({ port: candidate, ...this.options });
|
||||||
this._handleMessage(ws, msg);
|
|
||||||
|
server.on('listening', () => {
|
||||||
|
this.port = candidate;
|
||||||
|
this.server = server;
|
||||||
|
console.log('[WSServer] WS 服务已启动,端口:', candidate);
|
||||||
|
this.app.emit('wsServerReady', { port: candidate });
|
||||||
});
|
});
|
||||||
ws.on('close', () => {
|
|
||||||
this.clients.delete(ws);
|
server.on('error', (err) => {
|
||||||
if (this.clients.size === 0 && this.app.CodeTimer) {
|
if (err.code === 'EADDRINUSE') {
|
||||||
clearTimeout(this.app.CodeTimer);
|
console.warn('[WSServer] 端口 %d 被占用,尝试下一个', candidate);
|
||||||
console.log('所有客户端已断开,清除绑定码定时器', this.app.CodeTimer);
|
tryPort(index + 1);
|
||||||
this.app.CodeTimer = null;
|
return;
|
||||||
}
|
}
|
||||||
console.log('[WSServer] 客户端断开,当前连接数:', this.clients.size);
|
console.error('[WSServer] 端口 %d 启动失败:', candidate, err.message);
|
||||||
|
tryPort(index + 1);
|
||||||
});
|
});
|
||||||
ws.on('error', (err) => {
|
|
||||||
this.clients.delete(ws);
|
server.on('connection', (ws, req) => {
|
||||||
console.log('[WSServer] 客户端错误:', err.message);
|
this.clients.add(ws);
|
||||||
|
if (typeof this.onConnection === 'function') {
|
||||||
|
this.onConnection(ws, req);
|
||||||
|
}
|
||||||
|
ws.on('message', (msg) => {
|
||||||
|
this._handleMessage(ws, msg);
|
||||||
|
});
|
||||||
|
ws.on('close', () => {
|
||||||
|
this.clients.delete(ws);
|
||||||
|
if (this.clients.size === 0 && this.app.CodeTimer) {
|
||||||
|
clearTimeout(this.app.CodeTimer);
|
||||||
|
console.log('所有客户端已断开,清除绑定码定时器', this.app.CodeTimer);
|
||||||
|
this.app.CodeTimer = null;
|
||||||
|
}
|
||||||
|
console.log('[WSServer] 客户端断开,当前连接数:', this.clients.size);
|
||||||
|
});
|
||||||
|
ws.on('error', (err) => {
|
||||||
|
this.clients.delete(ws);
|
||||||
|
console.log('[WSServer] 客户端错误:', err.message);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
};
|
||||||
|
|
||||||
|
tryPort(0);
|
||||||
}
|
}
|
||||||
async onConnection(ws, req) {
|
async onConnection(ws, req) {
|
||||||
const tasks = [];
|
const tasks = [];
|
||||||
@ -127,8 +182,10 @@ class WSServer {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 发送打印组件列表
|
// 发送打印组件列表(录制模式跳过)
|
||||||
if (this.services.printerComponent && typeof this.services.printerComponent.getAll === 'function') {
|
if (isRecordingMode(this.app.config)) {
|
||||||
|
// 录制模式:静默跳过,不发送错误
|
||||||
|
} else if (this.services.printerComponent && typeof this.services.printerComponent.getAll === 'function') {
|
||||||
try {
|
try {
|
||||||
const components = this.services.printerComponent.getAll(); // 同步调用
|
const components = this.services.printerComponent.getAll(); // 同步调用
|
||||||
ws.send(JSON.stringify({ success: true, method: 'printerComponent.getAll', result: components }));
|
ws.send(JSON.stringify({ success: true, method: 'printerComponent.getAll', result: components }));
|
||||||
@ -139,8 +196,10 @@ class WSServer {
|
|||||||
ws.send(JSON.stringify({ success: false, message: 'printerComponent.getAll 服务不可用' }));
|
ws.send(JSON.stringify({ success: false, message: 'printerComponent.getAll 服务不可用' }));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 发送打印机列表
|
// 发送打印机列表(录制模式跳过)
|
||||||
if (this.services.printer && typeof this.services.printer.getWindowsPrinters === 'function') {
|
if (isRecordingMode(this.app.config)) {
|
||||||
|
// 录制模式:静默跳过
|
||||||
|
} else if (this.services.printer && typeof this.services.printer.getWindowsPrinters === 'function') {
|
||||||
tasks.push(
|
tasks.push(
|
||||||
this.services.printer.getWindowsPrinters()
|
this.services.printer.getWindowsPrinters()
|
||||||
);
|
);
|
||||||
@ -152,6 +211,15 @@ class WSServer {
|
|||||||
if (this.app.wsClient) {
|
if (this.app.wsClient) {
|
||||||
ws.send(JSON.stringify({ success: true, method: 'wsClient.statusChange', result: { status: this.app.wsClient.status } }));
|
ws.send(JSON.stringify({ success: true, method: 'wsClient.statusChange', result: { status: this.app.wsClient.status } }));
|
||||||
}
|
}
|
||||||
|
// 发送 frpc 初始状态(弥补时序:frpc 可能在 wsServer 启动前就已就绪)
|
||||||
|
if (this.services.frpc && typeof this.services.frpc.getStatus === 'function') {
|
||||||
|
try {
|
||||||
|
const frpcStatus = this.services.frpc.getStatus();
|
||||||
|
ws.send(JSON.stringify({ success: true, method: 'frpc.statusChange', result: frpcStatus }));
|
||||||
|
} catch (err) {
|
||||||
|
ws.send(JSON.stringify({ success: false, message: '获取 frpc 状态失败: ' + err.message }));
|
||||||
|
}
|
||||||
|
}
|
||||||
if (!this.app.config.token) {
|
if (!this.app.config.token) {
|
||||||
//检测是否随机码过期
|
//检测是否随机码过期
|
||||||
if (this.app.randomCode) {
|
if (this.app.randomCode) {
|
||||||
|
|||||||
44
db/init.sql
Normal file
44
db/init.sql
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
-- printServer SQLite 建表脚本
|
||||||
|
-- 数据库文件: printserver.db
|
||||||
|
|
||||||
|
-- 海康 NVR 下载记录表(存储配额管理)
|
||||||
|
CREATE TABLE IF NOT EXISTS hik_downloads (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
task_id TEXT NOT NULL UNIQUE,
|
||||||
|
ip TEXT DEFAULT '',
|
||||||
|
channel INTEGER DEFAULT 0,
|
||||||
|
output_path TEXT NOT NULL,
|
||||||
|
file_size INTEGER DEFAULT 0,
|
||||||
|
duration REAL DEFAULT 0,
|
||||||
|
resolution TEXT DEFAULT '',
|
||||||
|
status TEXT DEFAULT 'done',
|
||||||
|
deleted INTEGER DEFAULT 0,
|
||||||
|
created_at TEXT DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_hik_downloads_deleted ON hik_downloads(deleted);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_hik_downloads_status ON hik_downloads(status);
|
||||||
|
|
||||||
|
-- 海康 NVR 任务池表(调度、重试、超时管理)
|
||||||
|
CREATE TABLE IF NOT EXISTS hik_tasks (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
task_id TEXT NOT NULL UNIQUE,
|
||||||
|
unique_code TEXT DEFAULT '',
|
||||||
|
task_params TEXT,
|
||||||
|
status TEXT DEFAULT 'pending',
|
||||||
|
worker_id INTEGER,
|
||||||
|
retry INTEGER DEFAULT 0,
|
||||||
|
notice INTEGER DEFAULT 0,
|
||||||
|
timeout INTEGER DEFAULT 0,
|
||||||
|
error_message TEXT,
|
||||||
|
result TEXT,
|
||||||
|
tmp_file_path TEXT DEFAULT '',
|
||||||
|
pushed INTEGER DEFAULT 0,
|
||||||
|
push_retry INTEGER DEFAULT 0,
|
||||||
|
push_next_retry_at TEXT DEFAULT '',
|
||||||
|
start_time TEXT,
|
||||||
|
end_time TEXT,
|
||||||
|
created_at TEXT DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_hik_tasks_unique_code ON hik_tasks(unique_code);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_hik_tasks_status ON hik_tasks(status);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_hik_tasks_worker ON hik_tasks(worker_id);
|
||||||
63
e2e_test.mjs
Normal file
63
e2e_test.mjs
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
// e2e 测试:下载+转码+验证链接
|
||||||
|
const base = 'http://127.0.0.1:3002';
|
||||||
|
|
||||||
|
async function post(path, body) {
|
||||||
|
const res = await fetch(base + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function get(path) {
|
||||||
|
const res = await fetch(base + path);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
const cfg = { ip: '192.168.8.241', port: 7681, httpPort: 80, user: 'admin', pass: 'ky666888', channel: 33, start: '2026-07-01T00:03:00Z', end: '2026-07-01T00:05:00Z', speed: 4, output: 'G:/gameauto/recordings/verify_link.ps' };
|
||||||
|
|
||||||
|
console.log('[1] POST /api/hikvision/download');
|
||||||
|
const { taskId, status } = await post('/api/hikvision/download', cfg);
|
||||||
|
console.log(' taskId:', taskId, 'status:', status);
|
||||||
|
|
||||||
|
console.log('[2] 轮询...');
|
||||||
|
let s;
|
||||||
|
for (let i = 0; i < 30; i++) {
|
||||||
|
await new Promise(r => setTimeout(r, 1000));
|
||||||
|
s = await get('/api/hikvision/status?taskId=' + taskId);
|
||||||
|
const mb = s.progress?.totalMB || 0;
|
||||||
|
console.log(' [' + (i + 1) + ']', s.status, mb + 'MB');
|
||||||
|
if (s.status !== 'downloading' && s.status !== 'starting') break;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n========================================');
|
||||||
|
console.log(' 最终结果');
|
||||||
|
console.log('========================================');
|
||||||
|
const { result } = s;
|
||||||
|
console.log(' output :', result.output);
|
||||||
|
console.log(' size :', (result.size / 1024).toFixed(0) + 'KB');
|
||||||
|
console.log(' duration:', result.duration + 's');
|
||||||
|
console.log(' rawPs :', result.rawPs || false);
|
||||||
|
console.log(' chunks :', result.chunks || 'n/a');
|
||||||
|
|
||||||
|
const fs = await import('fs');
|
||||||
|
const filePath = result.output;
|
||||||
|
if (fs.existsSync(filePath)) {
|
||||||
|
const stat = fs.statSync(filePath);
|
||||||
|
console.log('\n ✅ 文件存在: ' + stat.size + ' bytes');
|
||||||
|
console.log(' 📁 本地路径: ' + filePath);
|
||||||
|
console.log(' 🔗 file 链接: file:///' + filePath.replace(/\\/g, '/'));
|
||||||
|
|
||||||
|
// ffprobe 验证
|
||||||
|
const { execSync } = await import('child_process');
|
||||||
|
try {
|
||||||
|
const probe = execSync('ffprobe "' + filePath + '" 2>&1', { encoding: 'utf-8', stdio: 'pipe' });
|
||||||
|
const durMatch = probe.match(/Duration: ([^,]+)/);
|
||||||
|
const vidMatch = probe.match(/Video: ([^\n]+)/);
|
||||||
|
const audMatch = probe.match(/Audio: ([^\n]+)/);
|
||||||
|
if (durMatch) console.log(' ⏱ Duration:', durMatch[1].trim());
|
||||||
|
if (vidMatch) console.log(' 🎬 Video :', vidMatch[1].trim());
|
||||||
|
if (audMatch) console.log(' 🔊 Audio :', audMatch[1].trim());
|
||||||
|
} catch (e) {
|
||||||
|
console.log(' ffprobe 失败:', e.message);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log('\n ❌ 文件不存在: ' + filePath);
|
||||||
|
}
|
||||||
@ -8,5 +8,5 @@ await build({
|
|||||||
projectDir,
|
projectDir,
|
||||||
prepackaged,
|
prepackaged,
|
||||||
win: ['nsis'],
|
win: ['nsis'],
|
||||||
publish: 'never'
|
publish: 'never',
|
||||||
});
|
});
|
||||||
@ -1,4 +1,4 @@
|
|||||||
const { app, BrowserWindow, Menu, Tray, nativeImage, ipcMain } = require('electron');
|
const { app, BrowserWindow, Menu, Tray, nativeImage, ipcMain, dialog } = require('electron');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const net = require('net');
|
const net = require('net');
|
||||||
const { spawn } = require('child_process');
|
const { spawn } = require('child_process');
|
||||||
@ -88,7 +88,20 @@ function isPortReachable(port) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function isBackendReady() {
|
async function isBackendReady() {
|
||||||
return isPortReachable(3001);
|
try {
|
||||||
|
// 优先读运行时状态(后端实际选中的端口)
|
||||||
|
var runtimeMod = await loadWorkspaceModule('utils/runtime.js');
|
||||||
|
var rt = runtimeMod.readRuntimeState();
|
||||||
|
if (rt.wsPort) {
|
||||||
|
return isPortReachable(rt.wsPort);
|
||||||
|
}
|
||||||
|
// 降级:读配置
|
||||||
|
var config = await readRuntimeConfig();
|
||||||
|
var port = config.wsPort || 17301;
|
||||||
|
return isPortReachable(port);
|
||||||
|
} catch (_) {
|
||||||
|
return isPortReachable(17301);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── 打包模式:WS 桥接(连接子进程的本地 WS 服务) ───
|
// ─── 打包模式:WS 桥接(连接子进程的本地 WS 服务) ───
|
||||||
@ -99,8 +112,19 @@ async function ensureBackendBridge() {
|
|||||||
if (_bridgeConnectPromise) return _bridgeConnectPromise;
|
if (_bridgeConnectPromise) return _bridgeConnectPromise;
|
||||||
|
|
||||||
_bridgeConnectPromise = (async function () {
|
_bridgeConnectPromise = (async function () {
|
||||||
var config = await readRuntimeConfig();
|
// 优先读运行时状态(后端实际选中的端口)
|
||||||
var wsPort = config.wsPort || 3001;
|
var wsPort;
|
||||||
|
try {
|
||||||
|
var runtimeMod = await loadWorkspaceModule('utils/runtime.js');
|
||||||
|
var rt = runtimeMod.readRuntimeState();
|
||||||
|
if (rt.wsPort) {
|
||||||
|
wsPort = rt.wsPort;
|
||||||
|
}
|
||||||
|
} catch (_) { /* ignore */ }
|
||||||
|
if (!wsPort) {
|
||||||
|
var config = await readRuntimeConfig();
|
||||||
|
wsPort = config.wsPort || 17301;
|
||||||
|
}
|
||||||
var mod = await import('ws');
|
var mod = await import('ws');
|
||||||
var WebSocketImpl = mod.default || mod.WebSocket || require('ws');
|
var WebSocketImpl = mod.default || mod.WebSocket || require('ws');
|
||||||
|
|
||||||
@ -249,6 +273,218 @@ ipcMain.handle('service:getBackendStatus', () => {
|
|||||||
return 'connecting';
|
return 'connecting';
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** 获取后端 HTTP 端口 */
|
||||||
|
ipcMain.handle('service:getHttpPort', async () => {
|
||||||
|
try {
|
||||||
|
var runtimeMod = await loadWorkspaceModule('utils/runtime.js');
|
||||||
|
var rt = runtimeMod.readRuntimeState();
|
||||||
|
if (rt.httpPort) return rt.httpPort;
|
||||||
|
} catch (_) { /* ignore */ }
|
||||||
|
try {
|
||||||
|
var config = await readRuntimeConfig();
|
||||||
|
return config.httpPort || 17311;
|
||||||
|
} catch (_) {
|
||||||
|
return 17311;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** 通过 IPC 代理调用后端 API(全模式内部直调,共享文件系统) */
|
||||||
|
ipcMain.handle('service:callApi', async (_event, apiPath, options) => {
|
||||||
|
try {
|
||||||
|
var method = (options && options.method) || 'GET';
|
||||||
|
var body = options && options.body;
|
||||||
|
var urlParams = new URLSearchParams(apiPath.includes('?') ? apiPath.split('?')[1] : '');
|
||||||
|
var pathOnly = apiPath.split('?')[0];
|
||||||
|
|
||||||
|
// /api/hikvision/files → 直接查 DB
|
||||||
|
if (pathOnly === '/api/hikvision/files' && method === 'GET') {
|
||||||
|
try {
|
||||||
|
var dbMod = await loadWorkspaceModule('utils/db.js');
|
||||||
|
var db = dbMod.default;
|
||||||
|
var page = parseInt(urlParams.get('page')) || 1;
|
||||||
|
var pageSize = Math.min(parseInt(urlParams.get('pageSize')) || 20, 100);
|
||||||
|
var search = (urlParams.get('search') || '').trim();
|
||||||
|
var offset = (page - 1) * pageSize;
|
||||||
|
|
||||||
|
var whereClause = '';
|
||||||
|
var queryParams = [];
|
||||||
|
if (search) {
|
||||||
|
whereClause = 'WHERE (ip LIKE ? OR output_path LIKE ?)';
|
||||||
|
queryParams.push('%' + search + '%', '%' + search + '%');
|
||||||
|
}
|
||||||
|
var totalRow = db.get('SELECT COUNT(*) as total FROM hik_downloads ' + whereClause, ...queryParams);
|
||||||
|
var total = totalRow ? totalRow.total : 0;
|
||||||
|
var rows = db.all('SELECT * FROM hik_downloads ' + whereClause + ' ORDER BY id DESC LIMIT ? OFFSET ?', ...queryParams, pageSize, offset);
|
||||||
|
var storageRow = db.get('SELECT COALESCE(SUM(file_size), 0) as used, COUNT(*) as fileCount FROM hik_downloads WHERE deleted = 0');
|
||||||
|
var usedBytes = storageRow ? storageRow.used : 0;
|
||||||
|
var fileCount = storageRow ? storageRow.fileCount : 0;
|
||||||
|
var hikCfg = (backendApp ? backendApp.config : await readRuntimeConfig()).hikvision || {};
|
||||||
|
var maxStorage = parseSizeToBytes(hikCfg.maxStorage || '50GB');
|
||||||
|
|
||||||
|
// 获取 HTTP 端口用于生成播放 URL
|
||||||
|
var dlPort;
|
||||||
|
try {
|
||||||
|
var rtMod = await loadWorkspaceModule('utils/runtime.js');
|
||||||
|
dlPort = rtMod.readRuntimeState().httpPort;
|
||||||
|
} catch (_) { /* ignore */ }
|
||||||
|
if (!dlPort) dlPort = (backendApp ? backendApp.config : await readRuntimeConfig()).httpPort || 17311;
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
list: rows.map(function (r) {
|
||||||
|
return {
|
||||||
|
...r,
|
||||||
|
downloadUrl: r.output_path ? 'http://127.0.0.1:' + dlPort + '/api/hikvision/file?path=' + encodeURIComponent(r.output_path) : null
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
page: page, pageSize: pageSize, total: total,
|
||||||
|
storage: { used: usedBytes, max: maxStorage, fileCount: fileCount, percent: maxStorage > 0 ? Math.round(usedBytes / maxStorage * 100) : 0 }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch (e) { return { success: false, message: e.message }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// /api/hikvision/config → 直接读写 config.json
|
||||||
|
if (pathOnly === '/api/hikvision/config') {
|
||||||
|
if (method === 'GET') {
|
||||||
|
try {
|
||||||
|
var cfg = (backendApp ? backendApp.config : await readRuntimeConfig()).hikvision || {};
|
||||||
|
return { success: true, hikvision: cfg };
|
||||||
|
} catch (e) { return { success: false, message: e.message }; }
|
||||||
|
}
|
||||||
|
if (method === 'POST') {
|
||||||
|
try {
|
||||||
|
var cfgMod = await loadWorkspaceModule('utils/config.js');
|
||||||
|
var configUtil = cfgMod.default;
|
||||||
|
var currentConfig = configUtil.read();
|
||||||
|
currentConfig.hikvision = { ...(currentConfig.hikvision || {}), ...body };
|
||||||
|
configUtil.write(currentConfig);
|
||||||
|
if (backendApp) backendApp.config = currentConfig;
|
||||||
|
return { success: true, message: '配置已保存', hikvision: currentConfig.hikvision };
|
||||||
|
} catch (e) { return { success: false, message: e.message }; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// /api/health
|
||||||
|
if (pathOnly === '/api/health' && method === 'GET') {
|
||||||
|
return { success: true, message: 'OK' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// /api/hikvision/tasks → 查询 hik_tasks 表
|
||||||
|
if (pathOnly === '/api/hikvision/tasks' && method === 'GET') {
|
||||||
|
try {
|
||||||
|
var dbMod2 = await loadWorkspaceModule('utils/db.js');
|
||||||
|
var db2 = dbMod2.default;
|
||||||
|
var tPage = parseInt(urlParams.get('page')) || 1;
|
||||||
|
var tPageSize = Math.min(parseInt(urlParams.get('pageSize')) || 50, 100);
|
||||||
|
var tStatus = urlParams.get('status') || '';
|
||||||
|
var tOffset = (tPage - 1) * tPageSize;
|
||||||
|
|
||||||
|
var tWhere = '';
|
||||||
|
var tParams = [];
|
||||||
|
if (tStatus) { tWhere = 'WHERE status = ?'; tParams.push(tStatus); }
|
||||||
|
|
||||||
|
var tTotalRow = db2.get('SELECT COUNT(*) as total FROM hik_tasks ' + tWhere, ...tParams);
|
||||||
|
var tRows = db2.all('SELECT * FROM hik_tasks ' + tWhere + ' ORDER BY id DESC LIMIT ? OFFSET ?', ...tParams, tPageSize, tOffset);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
list: tRows.map(function(r) {
|
||||||
|
var p = r.task_params ? JSON.parse(r.task_params) : {};
|
||||||
|
var rt = r.result ? JSON.parse(r.result) : null;
|
||||||
|
return {
|
||||||
|
id: r.id, task_id: r.task_id, unique_code: r.unique_code || '',
|
||||||
|
status: r.status,
|
||||||
|
ip: p.ip || '', channel: p.channel || 0,
|
||||||
|
speed: p.speed || 4, videoTime: p.videoTime || 0,
|
||||||
|
rec_start: p.start || '', rec_end: p.end || '',
|
||||||
|
output: p.output || '', retry: r.retry,
|
||||||
|
error_message: r.error_message, start_time: r.start_time, end_time: r.end_time,
|
||||||
|
created_at: r.created_at, progress: null, result: rt
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
page: tPage, pageSize: tPageSize,
|
||||||
|
total: tTotalRow ? tTotalRow.total : 0
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch (e) { return { success: false, message: e.message }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// /api/hikvision/retry → 重试/重录任务
|
||||||
|
if (pathOnly === '/api/hikvision/retry' && method === 'POST') {
|
||||||
|
try {
|
||||||
|
var dbMod3 = await loadWorkspaceModule('utils/db.js');
|
||||||
|
var db3 = dbMod3.default;
|
||||||
|
var taskId = (body && body.taskId) || '';
|
||||||
|
if (!taskId) return { success: false, message: '缺少 taskId' };
|
||||||
|
|
||||||
|
var task = db3.get('SELECT status FROM hik_tasks WHERE task_id = ?', taskId);
|
||||||
|
if (!task) return { success: false, message: '任务不存在' };
|
||||||
|
|
||||||
|
if (task.status === 'completed' || task.status === 'done') {
|
||||||
|
// 重录已完成任务:先删除旧文件,再重置状态
|
||||||
|
console.log('[Retry] 重录已完成任务:', taskId, '原状态:', task.status);
|
||||||
|
// 读取旧文件路径并删除
|
||||||
|
var oldRow = db3.get('SELECT tmp_file_path FROM hik_tasks WHERE task_id = ?', taskId);
|
||||||
|
if (oldRow && oldRow.tmp_file_path) {
|
||||||
|
try {
|
||||||
|
var cfgMod4 = await loadWorkspaceModule('utils/config.js');
|
||||||
|
var hikCfg = cfgMod4.default.read().hikvision || {};
|
||||||
|
var baseDir = (hikCfg.downloadDir || 'D').replace(/[\\\/]+$/, '');
|
||||||
|
if (/^[A-Za-z]$/.test(baseDir)) baseDir = baseDir + ':/hikvision_recordings';
|
||||||
|
var absPath = require('path').join(baseDir, oldRow.tmp_file_path);
|
||||||
|
if (require('fs').existsSync(absPath)) {
|
||||||
|
require('fs').unlinkSync(absPath);
|
||||||
|
console.log('[Retry] 已删除旧文件:', absPath);
|
||||||
|
}
|
||||||
|
} catch (e) { console.error('[Retry] 删除旧文件失败:', e.message); }
|
||||||
|
}
|
||||||
|
db3.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=?",
|
||||||
|
taskId
|
||||||
|
);
|
||||||
|
return { success: true, message: '已重新加入录制队列' };
|
||||||
|
} else if (task.status === 'failed' || task.status === 'timeout') {
|
||||||
|
console.log('[Retry] 重试失败任务:', taskId);
|
||||||
|
db3.run(
|
||||||
|
"UPDATE hik_tasks SET status='pending', retry=retry+1, error_message=NULL WHERE task_id=?",
|
||||||
|
taskId
|
||||||
|
);
|
||||||
|
return { success: true, message: '已重新加入队列' };
|
||||||
|
} else {
|
||||||
|
return { success: false, message: '当前状态不支持重试: ' + task.status };
|
||||||
|
}
|
||||||
|
} catch (e) { return { success: false, message: e.message }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: false, message: 'Unknown API: ' + pathOnly };
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[callApi] error:', e.message);
|
||||||
|
return { success: false, message: e.message };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function parseSizeToBytes(sizeStr) {
|
||||||
|
var match = String(sizeStr).match(/^([\d.]+)\s*(TB|GB|MB|KB)$/i);
|
||||||
|
if (!match) return 50 * 1024 * 1024 * 1024;
|
||||||
|
var num = parseFloat(match[1]);
|
||||||
|
var multipliers = { TB: Math.pow(1024, 4), GB: Math.pow(1024, 3), MB: Math.pow(1024, 2), KB: 1024 };
|
||||||
|
return Math.round(num * (multipliers[match[2].toUpperCase()] || 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 打开文件夹选择对话框 */
|
||||||
|
ipcMain.handle('dialog:openFolder', async () => {
|
||||||
|
if (!mainWindow || mainWindow.isDestroyed()) return { canceled: true };
|
||||||
|
var result = await dialog.showOpenDialog(mainWindow, {
|
||||||
|
title: '选择下载目录',
|
||||||
|
properties: ['openDirectory']
|
||||||
|
});
|
||||||
|
if (result.canceled) return { canceled: true };
|
||||||
|
return { canceled: false, path: result.filePaths[0] };
|
||||||
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 注册后端事件 → 渲染进程转发(替代 WSServer.onConnection / _bindAppEvents)
|
* 注册后端事件 → 渲染进程转发(替代 WSServer.onConnection / _bindAppEvents)
|
||||||
*/
|
*/
|
||||||
@ -271,15 +507,33 @@ function setupEventForwarding() {
|
|||||||
|
|
||||||
// wsClient 状态变化改用防抖转发,避免短暂断开/重连导致 UI 闪烁
|
// wsClient 状态变化改用防抖转发,避免短暂断开/重连导致 UI 闪烁
|
||||||
let wsStatusDebounceTimer = null;
|
let wsStatusDebounceTimer = null;
|
||||||
|
let wsLastForwardedStatus = null;
|
||||||
const forwardWsStatus = (data) => {
|
const forwardWsStatus = (data) => {
|
||||||
|
// error 立即转发,不防抖
|
||||||
|
if (data.status === 'error') {
|
||||||
|
if (wsStatusDebounceTimer) {
|
||||||
|
clearTimeout(wsStatusDebounceTimer);
|
||||||
|
wsStatusDebounceTimer = null;
|
||||||
|
}
|
||||||
|
wsLastForwardedStatus = data.status;
|
||||||
|
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||||
|
mainWindow.webContents.send('service:event', {
|
||||||
|
success: true,
|
||||||
|
method: 'wsClient.statusChange',
|
||||||
|
result: data
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (wsStatusDebounceTimer) {
|
if (wsStatusDebounceTimer) {
|
||||||
clearTimeout(wsStatusDebounceTimer);
|
clearTimeout(wsStatusDebounceTimer);
|
||||||
wsStatusDebounceTimer = null;
|
wsStatusDebounceTimer = null;
|
||||||
}
|
}
|
||||||
// connected 立即转发;disconnected/error 延迟 2 秒确认
|
// connected 立即转发;disconnected 延迟 2 秒确认
|
||||||
const delayMs = data.status === 'connected' ? 0 : 2000;
|
const delayMs = data.status === 'connected' ? 0 : 2000;
|
||||||
wsStatusDebounceTimer = setTimeout(() => {
|
wsStatusDebounceTimer = setTimeout(() => {
|
||||||
wsStatusDebounceTimer = null;
|
wsStatusDebounceTimer = null;
|
||||||
|
wsLastForwardedStatus = data.status;
|
||||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||||
mainWindow.webContents.send('service:event', {
|
mainWindow.webContents.send('service:event', {
|
||||||
success: true,
|
success: true,
|
||||||
@ -333,6 +587,12 @@ function setupEventForwarding() {
|
|||||||
|
|
||||||
backendApp.on('updateDownloadProgress', forward('update.downloadProgress'));
|
backendApp.on('updateDownloadProgress', forward('update.downloadProgress'));
|
||||||
|
|
||||||
|
backendApp.on('infoChanged', forward('setting.infoChanged'));
|
||||||
|
|
||||||
|
backendApp.on('frpcStatusChange', forward('frpc.statusChange'));
|
||||||
|
|
||||||
|
backendApp.on('migrationNeeded', forward('setting.migrationNeeded'));
|
||||||
|
|
||||||
// ─── 主动请求绑定码(替代 WSServer.onConnection),仅首次未绑定时请求一次 ───
|
// ─── 主动请求绑定码(替代 WSServer.onConnection),仅首次未绑定时请求一次 ───
|
||||||
let bindCodeRequested = false;
|
let bindCodeRequested = false;
|
||||||
const requestBindCode = () => {
|
const requestBindCode = () => {
|
||||||
@ -371,6 +631,9 @@ function setupEventForwarding() {
|
|||||||
() => backendApp.off('printerList'),
|
() => backendApp.off('printerList'),
|
||||||
() => backendApp.off('generateCode', generateCodeHandler),
|
() => backendApp.off('generateCode', generateCodeHandler),
|
||||||
() => backendApp.off('updateDownloadProgress'),
|
() => backendApp.off('updateDownloadProgress'),
|
||||||
|
() => backendApp.off('infoChanged'),
|
||||||
|
() => backendApp.off('frpcStatusChange'),
|
||||||
|
() => backendApp.off('migrationNeeded'),
|
||||||
() => backendApp.off('wsClientStatusChange', wsStatusHandler)
|
() => backendApp.off('wsClientStatusChange', wsStatusHandler)
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@ -44,5 +44,28 @@ contextBridge.exposeInMainWorld('printServerAPI', {
|
|||||||
const handler = (_event, status) => callback(status);
|
const handler = (_event, status) => callback(status);
|
||||||
ipcRenderer.on('backend:status', handler);
|
ipcRenderer.on('backend:status', handler);
|
||||||
return () => ipcRenderer.removeListener('backend:status', handler);
|
return () => ipcRenderer.removeListener('backend:status', handler);
|
||||||
}
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取后端 HTTP 端口(用于直接调用 HTTP API)
|
||||||
|
* @returns {Promise<number>}
|
||||||
|
*/
|
||||||
|
getHttpPort: () =>
|
||||||
|
ipcRenderer.invoke('service:getHttpPort'),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过 IPC 代理调用后端 HTTP API
|
||||||
|
* @param {string} path API 路径,如 '/api/hikvision/files?page=1'
|
||||||
|
* @param {object} options { method, body }
|
||||||
|
* @returns {Promise<object>}
|
||||||
|
*/
|
||||||
|
callApi: (path, options) =>
|
||||||
|
ipcRenderer.invoke('service:callApi', path, options || {}),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开文件夹选择对话框
|
||||||
|
* @returns {Promise<{canceled: boolean, path?: string}>}
|
||||||
|
*/
|
||||||
|
selectFolder: () =>
|
||||||
|
ipcRenderer.invoke('dialog:openFolder')
|
||||||
});
|
});
|
||||||
|
|||||||
BIN
frpc/frpc.exe
Normal file
BIN
frpc/frpc.exe
Normal file
Binary file not shown.
183
hik_download_debug.py
Normal file
183
hik_download_debug.py
Normal file
@ -0,0 +1,183 @@
|
|||||||
|
"""Hikvision NVR WebSocket download tool (debug version with verbose logging)"""
|
||||||
|
import json,sys,time,os,hashlib,struct,socket,subprocess,shutil
|
||||||
|
from base64 import b64encode
|
||||||
|
from xml.etree import ElementTree as ET
|
||||||
|
import requests
|
||||||
|
|
||||||
|
def main():
|
||||||
|
# 支持命令行参数或写死的测试参数
|
||||||
|
if len(sys.argv) > 1:
|
||||||
|
cfg = json.loads(sys.argv[1])
|
||||||
|
else:
|
||||||
|
cfg = {
|
||||||
|
"ip": "192.168.8.241",
|
||||||
|
"port": 7681,
|
||||||
|
"httpPort": 80,
|
||||||
|
"user": "admin",
|
||||||
|
"pass": "ky666888",
|
||||||
|
"channel": 33,
|
||||||
|
"start": "2026-07-01T08:00:00",
|
||||||
|
"end": "2026-07-01T08:05:00",
|
||||||
|
"speed": 4,
|
||||||
|
"output": "G:/gameauto/recordings/output.ps"
|
||||||
|
}
|
||||||
|
IP=cfg.get("ip","192.168.8.241");PORT=cfg.get("port",7681);HTTP=cfg.get("httpPort",80)
|
||||||
|
USER=cfg["user"];PASS=cfg["pass"];CH=cfg.get("channel",33)
|
||||||
|
START=cfg["start"];END=cfg["end"];SPEED=cfg.get("speed",4);OUT=cfg["output"]
|
||||||
|
NS={'h':'http://www.hikvision.com/ver20/XMLSchema'}
|
||||||
|
|
||||||
|
print("="*60+"\n Hikvision NVR WS Download (Debug)\n"+"="*60)
|
||||||
|
print(f" Device:{IP}:{HTTP} Ch:{CH} Time:{START}->{END} Speed:{SPEED}x\n Output:{OUT}")
|
||||||
|
|
||||||
|
s=requests.Session()
|
||||||
|
# [1] caps
|
||||||
|
print("\n[1] Caps...")
|
||||||
|
rand=str(int(time.time()*1000))[-8:]
|
||||||
|
caps_url = f"http://{IP}:{HTTP}/ISAPI/Security/sessionLogin/capabilities?username={USER}&random:{rand}"
|
||||||
|
print(f" >>> GET {caps_url}")
|
||||||
|
r=s.get(caps_url, timeout=5)
|
||||||
|
print(f" <<< {r.status_code}")
|
||||||
|
print(f" <<< Headers: {dict(r.headers)}")
|
||||||
|
print(f" <<< Body: {r.text}")
|
||||||
|
rt=ET.fromstring(r.text)
|
||||||
|
sid=rt.findtext('.//h:sessionID','',NS);ch=rt.findtext('.//h:challenge','',NS)
|
||||||
|
itr=int(rt.findtext('.//h:iterations','1',NS));slt=rt.findtext('.//h:salt','',NS)
|
||||||
|
ver=rt.findtext('.//h:sessionIDVersion','1',NS);vl=rt.findtext('.//h:isSessionIDValidLongTerm','false',NS)
|
||||||
|
st=rt.findtext('.//h:isSupportSessionTag','false',NS);irr=rt.findtext('.//h:isIrreversible','false',NS)=='true'
|
||||||
|
print(f" v={ver} itr={itr} irrev={irr}")
|
||||||
|
|
||||||
|
# [2] pwd
|
||||||
|
print("[2] Calc password...")
|
||||||
|
if irr:
|
||||||
|
d=hashlib.sha256((USER+slt+PASS).encode()).hexdigest();d=hashlib.sha256((d+ch).encode()).hexdigest()
|
||||||
|
for _ in range(2,itr):d=hashlib.sha256(d.encode()).hexdigest()
|
||||||
|
else:
|
||||||
|
d=hashlib.sha256((PASS+ch).encode()).hexdigest()
|
||||||
|
for _ in range(1,itr):d=hashlib.sha256(d.encode()).hexdigest()
|
||||||
|
print(f" digest={d[:16]}...")
|
||||||
|
|
||||||
|
# [3] login
|
||||||
|
print("[3] Login...")
|
||||||
|
ts=str(int(time.time()*1000))
|
||||||
|
if ver=='2':
|
||||||
|
xml=f'<SessionLogin><userName>{USER}</userName><password>{d}</password><sessionID>{sid}</sessionID><isSessionIDValidLongTerm>{vl}</isSessionIDValidLongTerm><sessionIDVersion>2</sessionIDVersion><isNeedSessionTag>{st}</isNeedSessionTag></SessionLogin>'
|
||||||
|
else:
|
||||||
|
xml=f'<SessionLogin><userName>{USER}</userName><password>{d}</password><sessionID>{sid}</sessionID></SessionLogin>'
|
||||||
|
login_url = f"http://{IP}:{HTTP}/ISAPI/Security/sessionLogin?timeStamp={ts}"
|
||||||
|
print(f" >>> POST {login_url}")
|
||||||
|
print(f" >>> Headers: {{'Content-Type': 'text/plain;charset=UTF-8'}}")
|
||||||
|
print(f" >>> Body: {xml}")
|
||||||
|
r=s.post(login_url, data=xml.encode(), headers={"Content-Type":"text/plain;charset=UTF-8"}, timeout=5)
|
||||||
|
print(f" <<< {r.status_code}")
|
||||||
|
print(f" <<< Headers: {dict(r.headers)}")
|
||||||
|
print(f" <<< Body: {r.text}")
|
||||||
|
if r.status_code!=200:print(f" FAIL {r.status_code} {r.text[:200]}");sys.exit(1)
|
||||||
|
tag=ET.fromstring(r.text).findtext('.//h:sessionTag','',NS);s.headers["SessionTag"]=tag
|
||||||
|
print(f" OK tag={tag[:16]}...")
|
||||||
|
|
||||||
|
# [4] token
|
||||||
|
print("[4] Token...")
|
||||||
|
token_url = f"http://{IP}:{HTTP}/ISAPI/Security/token?format=json"
|
||||||
|
print(f" >>> GET {token_url}")
|
||||||
|
print(f" >>> Cookies: {dict(s.cookies)}")
|
||||||
|
print(f" >>> SessionTag header: {s.headers.get('SessionTag', 'N/A')[:16]}...")
|
||||||
|
r=s.get(token_url, timeout=5)
|
||||||
|
print(f" <<< {r.status_code}")
|
||||||
|
print(f" <<< Body: {r.text[:200]}")
|
||||||
|
if r.status_code!=200:
|
||||||
|
print(" SessionTag 方式失败, 尝试 Digest 认证...")
|
||||||
|
s2=requests.Session();s2.auth=requests.auth.HTTPDigestAuth(USER,PASS)
|
||||||
|
durl = f"http://{IP}:{HTTP}/ISAPI/System/deviceInfo"
|
||||||
|
print(f" >>> GET {durl} (Digest Auth)")
|
||||||
|
r2=s2.get(durl, timeout=5)
|
||||||
|
print(f" <<< {r2.status_code}")
|
||||||
|
print(f" >>> GET {token_url} (Digest Auth)")
|
||||||
|
r=s2.get(token_url, timeout=5)
|
||||||
|
print(f" <<< {r.status_code}")
|
||||||
|
print(f" <<< Body: {r.text[:200]}")
|
||||||
|
tok=r.json()["Token"]["value"]
|
||||||
|
print(f" token={tok[:40]}...")
|
||||||
|
|
||||||
|
# [5] WS
|
||||||
|
print("[5] WebSocket...")
|
||||||
|
key=b64encode(os.urandom(16)).decode()
|
||||||
|
ws_path = f"/?version=1.0&cipherSuites=1&token={tok}"
|
||||||
|
hs=(f"GET {ws_path} HTTP/1.1\r\n"
|
||||||
|
f"Host: {IP}:{PORT}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
|
||||||
|
f"Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: {key}\r\n"
|
||||||
|
f"Origin: http://127.0.0.1\r\nUser-Agent: Mozilla/5.0 Chrome/149.0\r\n\r\n")
|
||||||
|
print(f" >>> WS connect to {IP}:{PORT}")
|
||||||
|
print(f" >>> WS Handshake:")
|
||||||
|
for l in hs.split('\r\n'):
|
||||||
|
if l: print(f" {l}")
|
||||||
|
sk=socket.socket();sk.settimeout(10);sk.connect((IP,PORT));sk.send(hs.encode())
|
||||||
|
resp=b""
|
||||||
|
while b"\r\n\r\n" not in resp:resp+=sk.recv(4096)
|
||||||
|
print(f" <<< WS 握手响应:")
|
||||||
|
hdr = resp[:resp.find(b"\r\n\r\n")].decode()
|
||||||
|
for l in hdr.split('\r\n'):
|
||||||
|
if l: print(f" {l}")
|
||||||
|
rem=resp[resp.find(b"\r\n\r\n")+4:]
|
||||||
|
print(f" OK shake: {rem[2:].decode()}" if len(rem)>2 else " OK")
|
||||||
|
|
||||||
|
def ws_send(data):
|
||||||
|
p=data.encode() if isinstance(data,str) else data
|
||||||
|
f=bytearray([0x81 if isinstance(data,str) else 0x82]);l=len(p)
|
||||||
|
if l<126:f.append(l)
|
||||||
|
elif l<65536:f.extend([126,*struct.pack(">H",l)])
|
||||||
|
else:f.extend([127,*struct.pack(">Q",l)])
|
||||||
|
f.extend(p);sk.send(bytes(f))
|
||||||
|
def ws_recv():
|
||||||
|
h=sk.recv(2)
|
||||||
|
if len(h)<2:return None
|
||||||
|
op,l=h[0]&0xF,h[1]&0x7F
|
||||||
|
if l==126:l=struct.unpack(">H",sk.recv(2))[0]
|
||||||
|
elif l==127:l=struct.unpack(">Q",sk.recv(8))[0]
|
||||||
|
d=b""
|
||||||
|
while len(d)<l:d+=sk.recv(l-len(d))
|
||||||
|
if op==0x01:return d.decode()
|
||||||
|
if op==0x02:return d
|
||||||
|
return d
|
||||||
|
|
||||||
|
cmd={"sequence":0,"cmd":"playback","url":f"live://{IP}:{PORT}/{CH}/0","startTime":START,"endTime":END}
|
||||||
|
print(f" >>> WS Playback cmd: {json.dumps(cmd)}")
|
||||||
|
ws_send(json.dumps(cmd))
|
||||||
|
|
||||||
|
os.makedirs(os.path.dirname(OUT)or".",exist_ok=True)
|
||||||
|
f=open(OUT,"wb");total=0;chunks=0;ss=False;t0=time.time();lr=t0;sk.settimeout(120)
|
||||||
|
while True:
|
||||||
|
try:msg=ws_recv()
|
||||||
|
except socket.timeout:print(f"\n timeout");break
|
||||||
|
if msg is None:print(f"\n closed");break
|
||||||
|
if isinstance(msg,str):
|
||||||
|
d=json.loads(msg);sc=d.get("statusCode",0)
|
||||||
|
print(f"\n <- {sc} {d.get('statusString','')}")
|
||||||
|
if sc==1:continue
|
||||||
|
break
|
||||||
|
elif isinstance(msg,bytes):
|
||||||
|
chunks+=1;total+=len(msg);f.write(msg)
|
||||||
|
if not ss and chunks>=10:
|
||||||
|
spd_cmd = json.dumps({"sequence":0,"cmd":"speed","rate":SPEED})
|
||||||
|
print(f"\n -> speed x{SPEED} cmd: {spd_cmd}")
|
||||||
|
ws_send(spd_cmd);ss=True
|
||||||
|
if time.time()-lr>0.5:
|
||||||
|
el=time.time()-t0;print(f"\r [{chunks:5d}] {total/1048576:.2f}MB {total/el/1024:.0f}KB/s {el:.0f}s",end="");lr=time.time()
|
||||||
|
|
||||||
|
sk.close();f.close()
|
||||||
|
el=time.time()-t0;mb=total/1048576 if total else 0
|
||||||
|
print(f"\n[6] Done: {chunks}chunks {mb:.1f}MB {el:.1f}s {mb/el*8 if el>0 else 0:.1f}Mbps")
|
||||||
|
|
||||||
|
if mb==0:return print(json.dumps({"success":False,"output":OUT,"size":0}))
|
||||||
|
|
||||||
|
mp4=OUT.replace(".ps",".mp4")
|
||||||
|
print(f"[7] Transcode -> {mp4}")
|
||||||
|
ff=shutil.which("ffmpeg") or os.path.join(os.environ.get("APPDATA",""),"npm","node_modules","@ffmpeg-installer","ffmpeg","node_modules","@ffmpeg-installer","win32-x64","ffmpeg.exe")
|
||||||
|
if ff and os.path.exists(ff):
|
||||||
|
subprocess.run([ff,"-i",OUT,"-c","copy",mp4,"-y"],capture_output=True,timeout=60)
|
||||||
|
ms=os.path.getsize(mp4);os.remove(OUT)
|
||||||
|
print(f" OK: {ms/1048576:.1f}MB")
|
||||||
|
print("\n"+"="*60+"\n"+json.dumps({"success":True,"output":mp4,"size":ms,"duration":el,"speed":SPEED})+"\n"+"="*60)
|
||||||
|
else:
|
||||||
|
print(f" No ffmpeg, raw PS: {OUT}")
|
||||||
|
|
||||||
|
if __name__=="__main__":main()
|
||||||
438
package-lock.json
generated
438
package-lock.json
generated
@ -1,16 +1,21 @@
|
|||||||
{
|
{
|
||||||
"name": "printserver",
|
"name": "printserver",
|
||||||
"version": "1.0.0",
|
"version": "1.0.29",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "printserver",
|
"name": "printserver",
|
||||||
"version": "1.0.0",
|
"version": "1.0.29",
|
||||||
|
"hasInstallScript": true,
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@ffmpeg-installer/ffmpeg": "^1.1.0",
|
||||||
|
"@xmldom/xmldom": "^0.9.10",
|
||||||
|
"better-sqlite3": "^12.11.1",
|
||||||
"iconv-lite": "^0.7.2",
|
"iconv-lite": "^0.7.2",
|
||||||
"node-windows": "^1.0.0-beta.8",
|
"node-windows": "^1.0.0-beta.8",
|
||||||
|
"onvif": "^0.8.1",
|
||||||
"ws": "^8.19.0"
|
"ws": "^8.19.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@ -484,6 +489,132 @@
|
|||||||
"node": ">= 10.0.0"
|
"node": ">= 10.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@ffmpeg-installer/darwin-arm64": {
|
||||||
|
"version": "4.1.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@ffmpeg-installer/darwin-arm64/-/darwin-arm64-4.1.5.tgz",
|
||||||
|
"integrity": "sha512-hYqTiP63mXz7wSQfuqfFwfLOfwwFChUedeCVKkBtl/cliaTM7/ePI9bVzfZ2c+dWu3TqCwLDRWNSJ5pqZl8otA==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "https://git.ffmpeg.org/gitweb/ffmpeg.git/blob_plain/HEAD:/LICENSE.md",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@ffmpeg-installer/darwin-x64": {
|
||||||
|
"version": "4.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@ffmpeg-installer/darwin-x64/-/darwin-x64-4.1.0.tgz",
|
||||||
|
"integrity": "sha512-Z4EyG3cIFjdhlY8wI9aLUXuH8nVt7E9SlMVZtWvSPnm2sm37/yC2CwjUzyCQbJbySnef1tQwGG2Sx+uWhd9IAw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "LGPL-2.1",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@ffmpeg-installer/ffmpeg": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@ffmpeg-installer/ffmpeg/-/ffmpeg-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-Uq4rmwkdGxIa9A6Bd/VqqYbT7zqh1GrT5/rFwCwKM70b42W5gIjWeVETq6SdcL0zXqDtY081Ws/iJWhr1+xvQg==",
|
||||||
|
"license": "LGPL-2.1",
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@ffmpeg-installer/darwin-arm64": "4.1.5",
|
||||||
|
"@ffmpeg-installer/darwin-x64": "4.1.0",
|
||||||
|
"@ffmpeg-installer/linux-arm": "4.1.3",
|
||||||
|
"@ffmpeg-installer/linux-arm64": "4.1.4",
|
||||||
|
"@ffmpeg-installer/linux-ia32": "4.1.0",
|
||||||
|
"@ffmpeg-installer/linux-x64": "4.1.0",
|
||||||
|
"@ffmpeg-installer/win32-ia32": "4.1.0",
|
||||||
|
"@ffmpeg-installer/win32-x64": "4.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@ffmpeg-installer/linux-arm": {
|
||||||
|
"version": "4.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-arm/-/linux-arm-4.1.3.tgz",
|
||||||
|
"integrity": "sha512-NDf5V6l8AfzZ8WzUGZ5mV8O/xMzRag2ETR6+TlGIsMHp81agx51cqpPItXPib/nAZYmo55Bl2L6/WOMI3A5YRg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "GPLv3",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@ffmpeg-installer/linux-arm64": {
|
||||||
|
"version": "4.1.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-arm64/-/linux-arm64-4.1.4.tgz",
|
||||||
|
"integrity": "sha512-dljEqAOD0oIM6O6DxBW9US/FkvqvQwgJ2lGHOwHDDwu/pX8+V0YsDL1xqHbj1DMX/+nP9rxw7G7gcUvGspSoKg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "GPLv3",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@ffmpeg-installer/linux-ia32": {
|
||||||
|
"version": "4.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-ia32/-/linux-ia32-4.1.0.tgz",
|
||||||
|
"integrity": "sha512-0LWyFQnPf+Ij9GQGD034hS6A90URNu9HCtQ5cTqo5MxOEc7Rd8gLXrJvn++UmxhU0J5RyRE9KRYstdCVUjkNOQ==",
|
||||||
|
"cpu": [
|
||||||
|
"ia32"
|
||||||
|
],
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "GPLv3",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@ffmpeg-installer/linux-x64": {
|
||||||
|
"version": "4.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-x64/-/linux-x64-4.1.0.tgz",
|
||||||
|
"integrity": "sha512-Y5BWhGLU/WpQjOArNIgXD3z5mxxdV8c41C+U15nsE5yF8tVcdCGet5zPs5Zy3Ta6bU7haGpIzryutqCGQA/W8A==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "GPLv3",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@ffmpeg-installer/win32-ia32": {
|
||||||
|
"version": "4.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@ffmpeg-installer/win32-ia32/-/win32-ia32-4.1.0.tgz",
|
||||||
|
"integrity": "sha512-FV2D7RlaZv/lrtdhaQ4oETwoFUsUjlUiasiZLDxhEUPdNDWcH1OU9K1xTvqz+OXLdsmYelUDuBS/zkMOTtlUAw==",
|
||||||
|
"cpu": [
|
||||||
|
"ia32"
|
||||||
|
],
|
||||||
|
"license": "GPLv3",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@ffmpeg-installer/win32-x64": {
|
||||||
|
"version": "4.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@ffmpeg-installer/win32-x64/-/win32-x64-4.1.0.tgz",
|
||||||
|
"integrity": "sha512-Drt5u2vzDnIONf4ZEkKtFlbvwj6rI3kxw1Ck9fpudmtgaZIHD4ucsWB2lCZBXRxJgXR+2IMSti+4rtM4C4rXgg==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"license": "GPLv3",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
]
|
||||||
|
},
|
||||||
"node_modules/@isaacs/cliui": {
|
"node_modules/@isaacs/cliui": {
|
||||||
"version": "8.0.2",
|
"version": "8.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
|
||||||
@ -861,13 +992,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@xmldom/xmldom": {
|
"node_modules/@xmldom/xmldom": {
|
||||||
"version": "0.8.11",
|
"version": "0.9.10",
|
||||||
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.11.tgz",
|
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.10.tgz",
|
||||||
"integrity": "sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw==",
|
"integrity": "sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=10.0.0"
|
"node": ">=14.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/7zip-bin": {
|
"node_modules/7zip-bin": {
|
||||||
@ -1199,7 +1329,6 @@
|
|||||||
"version": "1.5.1",
|
"version": "1.5.1",
|
||||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||||
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
|
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
|
||||||
"dev": true,
|
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "github",
|
"type": "github",
|
||||||
@ -1216,6 +1345,20 @@
|
|||||||
],
|
],
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/better-sqlite3": {
|
||||||
|
"version": "12.11.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz",
|
||||||
|
"integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==",
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"bindings": "^1.5.0",
|
||||||
|
"prebuild-install": "^7.1.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/binary-extensions": {
|
"node_modules/binary-extensions": {
|
||||||
"version": "2.3.0",
|
"version": "2.3.0",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/binary-extensions/-/binary-extensions-2.3.0.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/binary-extensions/-/binary-extensions-2.3.0.tgz",
|
||||||
@ -1229,11 +1372,19 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/bindings": {
|
||||||
|
"version": "1.5.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
|
||||||
|
"integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"file-uri-to-path": "1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/bl": {
|
"node_modules/bl": {
|
||||||
"version": "4.1.0",
|
"version": "4.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
|
||||||
"integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
|
"integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"buffer": "^5.5.0",
|
"buffer": "^5.5.0",
|
||||||
@ -1280,7 +1431,6 @@
|
|||||||
"version": "5.7.1",
|
"version": "5.7.1",
|
||||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
|
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
|
||||||
"integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
|
"integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
|
||||||
"dev": true,
|
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "github",
|
"type": "github",
|
||||||
@ -1849,7 +1999,6 @@
|
|||||||
"version": "6.0.0",
|
"version": "6.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
|
||||||
"integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
|
"integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"mimic-response": "^3.1.0"
|
"mimic-response": "^3.1.0"
|
||||||
@ -1865,7 +2014,6 @@
|
|||||||
"version": "3.1.0",
|
"version": "3.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
|
||||||
"integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
|
"integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=10"
|
"node": ">=10"
|
||||||
@ -1874,6 +2022,15 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/deep-extend": {
|
||||||
|
"version": "0.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
|
||||||
|
"integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/defaults": {
|
"node_modules/defaults": {
|
||||||
"version": "1.0.4",
|
"version": "1.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz",
|
||||||
@ -1949,7 +2106,6 @@
|
|||||||
"version": "2.1.2",
|
"version": "2.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
|
||||||
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
|
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
|
||||||
"dev": true,
|
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
@ -2391,7 +2547,6 @@
|
|||||||
"version": "1.4.5",
|
"version": "1.4.5",
|
||||||
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
|
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
|
||||||
"integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
|
"integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"once": "^1.4.0"
|
"once": "^1.4.0"
|
||||||
@ -2494,6 +2649,15 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/expand-template": {
|
||||||
|
"version": "2.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
|
||||||
|
"integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
|
||||||
|
"license": "(MIT OR WTFPL)",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/exponential-backoff": {
|
"node_modules/exponential-backoff": {
|
||||||
"version": "3.1.3",
|
"version": "3.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz",
|
||||||
@ -2557,6 +2721,12 @@
|
|||||||
"pend": "~1.2.0"
|
"pend": "~1.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/file-uri-to-path": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/filelist": {
|
"node_modules/filelist": {
|
||||||
"version": "1.0.6",
|
"version": "1.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz",
|
||||||
@ -2657,6 +2827,12 @@
|
|||||||
"node": ">= 6"
|
"node": ">= 6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/fs-constants": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/fs-extra": {
|
"node_modules/fs-extra": {
|
||||||
"version": "8.1.0",
|
"version": "8.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
|
||||||
@ -2781,6 +2957,12 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/github-from-package": {
|
||||||
|
"version": "0.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
|
||||||
|
"integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/glob": {
|
"node_modules/glob": {
|
||||||
"version": "7.2.3",
|
"version": "7.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
|
||||||
@ -3096,7 +3278,6 @@
|
|||||||
"version": "1.2.1",
|
"version": "1.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||||
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
|
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
|
||||||
"dev": true,
|
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "github",
|
"type": "github",
|
||||||
@ -3146,7 +3327,12 @@
|
|||||||
"version": "2.0.4",
|
"version": "2.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
|
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
|
||||||
"dev": true,
|
"license": "ISC"
|
||||||
|
},
|
||||||
|
"node_modules/ini": {
|
||||||
|
"version": "1.3.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
|
||||||
|
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/ip-address": {
|
"node_modules/ip-address": {
|
||||||
@ -3549,7 +3735,6 @@
|
|||||||
"version": "1.2.8",
|
"version": "1.2.8",
|
||||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
|
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
|
||||||
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
|
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
@ -3701,6 +3886,12 @@
|
|||||||
"mkdirp": "bin/cmd.js"
|
"mkdirp": "bin/cmd.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/mkdirp-classic": {
|
||||||
|
"version": "0.5.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
|
||||||
|
"integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/ms": {
|
"node_modules/ms": {
|
||||||
"version": "2.1.3",
|
"version": "2.1.3",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/ms/-/ms-2.1.3.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/ms/-/ms-2.1.3.tgz",
|
||||||
@ -3708,6 +3899,12 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/napi-build-utils": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/negotiator": {
|
"node_modules/negotiator": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
|
||||||
@ -3867,7 +4064,6 @@
|
|||||||
"version": "1.4.0",
|
"version": "1.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
|
||||||
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
|
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
|
||||||
"dev": true,
|
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"wrappy": "1"
|
"wrappy": "1"
|
||||||
@ -3889,6 +4085,18 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/onvif": {
|
||||||
|
"version": "0.8.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/onvif/-/onvif-0.8.1.tgz",
|
||||||
|
"integrity": "sha512-D0VSuTQutZWQsaWWvh7acbengYNJew25kXpXc/stJc6/xYx2MwU1tkIZA23bu12hr5MxstSQ55decY7we2/LWw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"xml2js": "^0.6.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/ora": {
|
"node_modules/ora": {
|
||||||
"version": "5.4.1",
|
"version": "5.4.1",
|
||||||
"resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz",
|
||||||
@ -4060,6 +4268,16 @@
|
|||||||
"node": ">=10.4.0"
|
"node": ">=10.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/plist/node_modules/@xmldom/xmldom": {
|
||||||
|
"version": "0.8.13",
|
||||||
|
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz",
|
||||||
|
"integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/postject": {
|
"node_modules/postject": {
|
||||||
"version": "1.0.0-alpha.6",
|
"version": "1.0.0-alpha.6",
|
||||||
"resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz",
|
"resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz",
|
||||||
@ -4090,6 +4308,45 @@
|
|||||||
"node": "^12.20.0 || >=14"
|
"node": "^12.20.0 || >=14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/prebuild-install": {
|
||||||
|
"version": "7.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
|
||||||
|
"integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",
|
||||||
|
"deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"detect-libc": "^2.0.0",
|
||||||
|
"expand-template": "^2.0.3",
|
||||||
|
"github-from-package": "0.0.0",
|
||||||
|
"minimist": "^1.2.3",
|
||||||
|
"mkdirp-classic": "^0.5.3",
|
||||||
|
"napi-build-utils": "^2.0.0",
|
||||||
|
"node-abi": "^3.3.0",
|
||||||
|
"pump": "^3.0.0",
|
||||||
|
"rc": "^1.2.7",
|
||||||
|
"simple-get": "^4.0.0",
|
||||||
|
"tar-fs": "^2.0.0",
|
||||||
|
"tunnel-agent": "^0.6.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"prebuild-install": "bin.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/prebuild-install/node_modules/node-abi": {
|
||||||
|
"version": "3.94.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.94.0.tgz",
|
||||||
|
"integrity": "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"semver": "^7.3.5"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/proc-log": {
|
"node_modules/proc-log": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/proc-log/-/proc-log-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/proc-log/-/proc-log-5.0.0.tgz",
|
||||||
@ -4147,7 +4404,6 @@
|
|||||||
"version": "3.0.4",
|
"version": "3.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
|
||||||
"integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
|
"integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"end-of-stream": "^1.1.0",
|
"end-of-stream": "^1.1.0",
|
||||||
@ -4177,6 +4433,21 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/rc": {
|
||||||
|
"version": "1.2.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
|
||||||
|
"integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
|
||||||
|
"license": "(BSD-2-Clause OR MIT OR Apache-2.0)",
|
||||||
|
"dependencies": {
|
||||||
|
"deep-extend": "^0.6.0",
|
||||||
|
"ini": "~1.3.0",
|
||||||
|
"minimist": "^1.2.0",
|
||||||
|
"strip-json-comments": "~2.0.1"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"rc": "cli.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/read-binary-file-arch": {
|
"node_modules/read-binary-file-arch": {
|
||||||
"version": "1.0.6",
|
"version": "1.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz",
|
||||||
@ -4194,7 +4465,6 @@
|
|||||||
"version": "3.6.2",
|
"version": "3.6.2",
|
||||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
|
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
|
||||||
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"inherits": "^2.0.3",
|
"inherits": "^2.0.3",
|
||||||
@ -4377,7 +4647,6 @@
|
|||||||
"version": "5.2.1",
|
"version": "5.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||||
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
||||||
"dev": true,
|
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "github",
|
"type": "github",
|
||||||
@ -4414,7 +4683,6 @@
|
|||||||
"version": "1.6.0",
|
"version": "1.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz",
|
||||||
"integrity": "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==",
|
"integrity": "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==",
|
||||||
"dev": true,
|
|
||||||
"license": "BlueOak-1.0.0",
|
"license": "BlueOak-1.0.0",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=11.0.0"
|
"node": ">=11.0.0"
|
||||||
@ -4424,7 +4692,6 @@
|
|||||||
"version": "7.7.4",
|
"version": "7.7.4",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/semver/-/semver-7.7.4.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/semver/-/semver-7.7.4.tgz",
|
||||||
"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
|
"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
|
||||||
"dev": true,
|
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"bin": {
|
"bin": {
|
||||||
"semver": "bin/semver.js"
|
"semver": "bin/semver.js"
|
||||||
@ -4488,6 +4755,51 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
|
"node_modules/simple-concat": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "patreon",
|
||||||
|
"url": "https://www.patreon.com/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "consulting",
|
||||||
|
"url": "https://feross.org/support"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/simple-get": {
|
||||||
|
"version": "4.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",
|
||||||
|
"integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "patreon",
|
||||||
|
"url": "https://www.patreon.com/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "consulting",
|
||||||
|
"url": "https://feross.org/support"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"decompress-response": "^6.0.0",
|
||||||
|
"once": "^1.3.1",
|
||||||
|
"simple-concat": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/simple-update-notifier": {
|
"node_modules/simple-update-notifier": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz",
|
||||||
@ -4614,7 +4926,6 @@
|
|||||||
"version": "1.3.0",
|
"version": "1.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
|
||||||
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
|
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"safe-buffer": "~5.2.0"
|
"safe-buffer": "~5.2.0"
|
||||||
@ -4676,6 +4987,15 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/strip-json-comments": {
|
||||||
|
"version": "2.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
|
||||||
|
"integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/sumchecker": {
|
"node_modules/sumchecker": {
|
||||||
"version": "3.0.1",
|
"version": "3.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
|
||||||
@ -4719,6 +5039,40 @@
|
|||||||
"node": ">=18"
|
"node": ">=18"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/tar-fs": {
|
||||||
|
"version": "2.1.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz",
|
||||||
|
"integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"chownr": "^1.1.1",
|
||||||
|
"mkdirp-classic": "^0.5.2",
|
||||||
|
"pump": "^3.0.0",
|
||||||
|
"tar-stream": "^2.1.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/tar-fs/node_modules/chownr": {
|
||||||
|
"version": "1.1.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
|
||||||
|
"integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
|
||||||
|
"license": "ISC"
|
||||||
|
},
|
||||||
|
"node_modules/tar-stream": {
|
||||||
|
"version": "2.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
|
||||||
|
"integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"bl": "^4.0.3",
|
||||||
|
"end-of-stream": "^1.4.1",
|
||||||
|
"fs-constants": "^1.0.0",
|
||||||
|
"inherits": "^2.0.3",
|
||||||
|
"readable-stream": "^3.1.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/tar/node_modules/yallist": {
|
"node_modules/tar/node_modules/yallist": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
|
||||||
@ -4929,6 +5283,18 @@
|
|||||||
"utf8-byte-length": "^1.0.1"
|
"utf8-byte-length": "^1.0.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/tunnel-agent": {
|
||||||
|
"version": "0.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
|
||||||
|
"integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"safe-buffer": "^5.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/type-fest": {
|
"node_modules/type-fest": {
|
||||||
"version": "0.13.1",
|
"version": "0.13.1",
|
||||||
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz",
|
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz",
|
||||||
@ -5014,7 +5380,6 @@
|
|||||||
"version": "1.0.2",
|
"version": "1.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
||||||
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
|
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/verror": {
|
"node_modules/verror": {
|
||||||
@ -5099,7 +5464,6 @@
|
|||||||
"version": "1.0.2",
|
"version": "1.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
||||||
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
||||||
"dev": true,
|
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/ws": {
|
"node_modules/ws": {
|
||||||
@ -5129,6 +5493,28 @@
|
|||||||
"integrity": "sha512-huCv9IH9Tcf95zuYCsQraZtWnJvBtLVE0QHMOs8bWyZAFZNDcYjsPq1nEx8jKA9y+Beo9v+7OBPRisQTjinQMw==",
|
"integrity": "sha512-huCv9IH9Tcf95zuYCsQraZtWnJvBtLVE0QHMOs8bWyZAFZNDcYjsPq1nEx8jKA9y+Beo9v+7OBPRisQTjinQMw==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/xml2js": {
|
||||||
|
"version": "0.6.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz",
|
||||||
|
"integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"sax": ">=0.6.0",
|
||||||
|
"xmlbuilder": "~11.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/xml2js/node_modules/xmlbuilder": {
|
||||||
|
"version": "11.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz",
|
||||||
|
"integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/xmlbuilder": {
|
"node_modules/xmlbuilder": {
|
||||||
"version": "15.1.1",
|
"version": "15.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
|
||||||
|
|||||||
24
package.json
24
package.json
@ -1,12 +1,14 @@
|
|||||||
{
|
{
|
||||||
"name": "printserver",
|
"name": "printserver",
|
||||||
"version": "1.0.14",
|
"version": "1.0.23",
|
||||||
"main": "electron/main.cjs",
|
"main": "electron/main.cjs",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node index.js",
|
"start": "node index.js",
|
||||||
"test": "echo \"Error: no test specified\" && exit 1",
|
"test": "echo \"Error: no test specified\" && exit 1",
|
||||||
"dev": "nodemon index.js",
|
"dev": "chcp 65001 > nul && nodemon index.js",
|
||||||
"desktop:dev": "electron .",
|
"desktop:dev": "chcp 65001 > nul && electron .",
|
||||||
|
"start:linux": "node index.js",
|
||||||
|
"postinstall": "node -e \"process.env.npm_config_omit!=='dev'&&process.exit(0);require('child_process').execSync('npx @electron/rebuild -f -w better-sqlite3',{stdio:'inherit'})\"",
|
||||||
"package:clean": "powershell -NoProfile -File build.ps1 clean",
|
"package:clean": "powershell -NoProfile -File build.ps1 clean",
|
||||||
"package:prepare": "powershell -NoProfile -File build.ps1 prepare",
|
"package:prepare": "powershell -NoProfile -File build.ps1 prepare",
|
||||||
"package:app": "powershell -NoProfile -File build.ps1 app",
|
"package:app": "powershell -NoProfile -File build.ps1 app",
|
||||||
@ -19,10 +21,15 @@
|
|||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"description": "Windows local print service with HTTP, WebSocket, tray shell and printer component integration",
|
"description": "Windows local print service with HTTP, WebSocket, tray shell and printer component integration",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@ffmpeg-installer/ffmpeg": "^1.1.0",
|
||||||
|
"@xmldom/xmldom": "^0.9.10",
|
||||||
|
"better-sqlite3": "^12.11.1",
|
||||||
"iconv-lite": "^0.7.2",
|
"iconv-lite": "^0.7.2",
|
||||||
"node-windows": "^1.0.0-beta.8",
|
|
||||||
"ws": "^8.19.0"
|
"ws": "^8.19.0"
|
||||||
},
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"node-windows": "^1.0.0-beta.8"
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"electron": "^37.2.0",
|
"electron": "^37.2.0",
|
||||||
"electron-builder": "^26.0.12",
|
"electron-builder": "^26.0.12",
|
||||||
@ -36,12 +43,16 @@
|
|||||||
"directories": {
|
"directories": {
|
||||||
"output": "dist"
|
"output": "dist"
|
||||||
},
|
},
|
||||||
|
"asarUnpack": [
|
||||||
|
"node_modules/@ffmpeg-installer/**/*"
|
||||||
|
],
|
||||||
"files": [
|
"files": [
|
||||||
"electron/**/*",
|
"electron/**/*",
|
||||||
"core/**/*",
|
"core/**/*",
|
||||||
"services/**/*",
|
"services/**/*",
|
||||||
"utils/**/*",
|
"utils/**/*",
|
||||||
"views/**/*",
|
"views/**/*",
|
||||||
|
"db/**/*",
|
||||||
"index.js",
|
"index.js",
|
||||||
"package.json",
|
"package.json",
|
||||||
"!electron/assets/icon-gray.svg",
|
"!electron/assets/icon-gray.svg",
|
||||||
@ -64,6 +75,10 @@
|
|||||||
{
|
{
|
||||||
"from": "daemon",
|
"from": "daemon",
|
||||||
"to": "daemon"
|
"to": "daemon"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "frpc",
|
||||||
|
"to": "frpc"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"win": {
|
"win": {
|
||||||
@ -92,4 +107,3 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -4,5 +4,22 @@
|
|||||||
"path": "."
|
"path": "."
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"settings": {}
|
"settings": {
|
||||||
|
"files.watcherExclude": {
|
||||||
|
"dist/**": true,
|
||||||
|
"node_modules/**": true,
|
||||||
|
"临时/**": true,
|
||||||
|
"versioning/**": true
|
||||||
|
},
|
||||||
|
"search.exclude": {
|
||||||
|
"dist/**": true,
|
||||||
|
"临时/**": true
|
||||||
|
},
|
||||||
|
"codegraph.exclude": {
|
||||||
|
"dist/**": true,
|
||||||
|
"node_modules/**": true,
|
||||||
|
"临时/**": true,
|
||||||
|
"versioning/**": true
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
BIN
printserver.db
Normal file
BIN
printserver.db
Normal file
Binary file not shown.
BIN
printserver.db-shm
Normal file
BIN
printserver.db-shm
Normal file
Binary file not shown.
BIN
printserver.db-wal
Normal file
BIN
printserver.db-wal
Normal file
Binary file not shown.
5
runtime.json
Normal file
5
runtime.json
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"wsPort": 17301,
|
||||||
|
"httpPort": 17311,
|
||||||
|
"startedAt": "2026-07-24T19:39:53.176Z"
|
||||||
|
}
|
||||||
297
services/frpc.js
Normal file
297
services/frpc.js
Normal file
@ -0,0 +1,297 @@
|
|||||||
|
import { spawn } from 'child_process';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import service from '../core/BaseService.js';
|
||||||
|
import configUtil from '../utils/config.js';
|
||||||
|
import { getProjectRoot, getResourcePath, getAppDataDir, isRecordingMode } from '../utils/runtime.js';
|
||||||
|
|
||||||
|
const FRPC_EXE = process.platform === 'win32' ? 'frpc.exe' : 'frpc';
|
||||||
|
|
||||||
|
// 文件日志:写 console + 写入文件(方便打包后排查问题)
|
||||||
|
function _logFile(...args) {
|
||||||
|
const msg = args.join(' ');
|
||||||
|
console.log(msg);
|
||||||
|
try {
|
||||||
|
const logDir = getAppDataDir();
|
||||||
|
const logPath = path.join(logDir, 'frpc.log');
|
||||||
|
const ts = new Date().toISOString().replace('T', ' ').substring(0, 19);
|
||||||
|
fs.appendFileSync(logPath, `[${ts}] ${msg}\n`, 'utf-8');
|
||||||
|
} catch (_) { /* 写日志失败不阻塞主流程 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
function _errFile(...args) {
|
||||||
|
const msg = args.join(' ');
|
||||||
|
console.error(msg);
|
||||||
|
try {
|
||||||
|
const logDir = getAppDataDir();
|
||||||
|
const logPath = path.join(logDir, 'frpc.log');
|
||||||
|
const ts = new Date().toISOString().replace('T', ' ').substring(0, 19);
|
||||||
|
fs.appendFileSync(logPath, `[${ts}] [ERR] ${msg}\n`, 'utf-8');
|
||||||
|
} catch (_) { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
class FrpcService extends service {
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
this.process = null;
|
||||||
|
this.status = 'stopped'; // stopped | starting | running | error
|
||||||
|
this._watchTimer = null;
|
||||||
|
|
||||||
|
this.updateConfig = this.updateConfig.bind(this);
|
||||||
|
this.getStatus = this.getStatus.bind(this);
|
||||||
|
this.stop = this.stop.bind(this);
|
||||||
|
|
||||||
|
// 启动时检查是否需要自动拉起 frpc
|
||||||
|
_logFile('[Frpc] 服务初始化, 当前 frpc 配置:', JSON.stringify(this.config.frpc || null));
|
||||||
|
this._autoStart();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 应用启动时自动拉起(如果 config.frpc.enabled 为 true,或录制模式下自动启用)
|
||||||
|
*/
|
||||||
|
_autoStart() {
|
||||||
|
const cfg = this.config.frpc || {};
|
||||||
|
// 录制模式 + 有 serverAddr 配置 → 自动启用(无论 enabled 字段)
|
||||||
|
const shouldAutoStart = cfg.enabled || (isRecordingMode(this.config) && cfg.serverAddr);
|
||||||
|
if (shouldAutoStart) {
|
||||||
|
_logFile('[Frpc] 自动启动 frpc (enabled=%s, recording=%s)',
|
||||||
|
!!cfg.enabled, isRecordingMode(this.config));
|
||||||
|
if (!cfg.enabled) {
|
||||||
|
// 补写 enabled 标记,避免后续 updateConfig 判定混乱
|
||||||
|
cfg.enabled = true;
|
||||||
|
this.config.frpc = cfg;
|
||||||
|
}
|
||||||
|
this._startFrpc();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 服务端下发 frpc 配置(通过 WS 调用)
|
||||||
|
*/
|
||||||
|
async updateConfig(data) {
|
||||||
|
if (!data || typeof data !== 'object') {
|
||||||
|
return { ok: false, message: '配置数据无效' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const { config, app } = this;
|
||||||
|
config.frpc = {
|
||||||
|
enabled: !!data.enabled,
|
||||||
|
serverAddr: data.serverAddr || '',
|
||||||
|
serverPort: Number(data.serverPort) || 6005,
|
||||||
|
authToken: data.authToken || '',
|
||||||
|
token: data.token || '',
|
||||||
|
proxies: Array.isArray(data.proxies) ? data.proxies : []
|
||||||
|
};
|
||||||
|
|
||||||
|
configUtil.write(config);
|
||||||
|
app.config = config;
|
||||||
|
_logFile('[Frpc] 配置已更新:', JSON.stringify(config.frpc));
|
||||||
|
|
||||||
|
// 根据 enabled 决定启动或停止
|
||||||
|
if (config.frpc.enabled && config.frpc.serverAddr) {
|
||||||
|
this._startFrpc();
|
||||||
|
return { ok: true, message: 'frpc 配置已更新,正在启动' };
|
||||||
|
} else {
|
||||||
|
this._stopFrpc();
|
||||||
|
return { ok: true, message: 'frpc 已停用' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 停止 frpc
|
||||||
|
*/
|
||||||
|
stop() {
|
||||||
|
this._stopFrpc();
|
||||||
|
return { ok: true, message: 'frpc 已停止' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前状态
|
||||||
|
*/
|
||||||
|
getStatus() {
|
||||||
|
return {
|
||||||
|
status: this.status,
|
||||||
|
enabled: !!(this.config.frpc && this.config.frpc.enabled)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── frpc 进程管理 ───
|
||||||
|
|
||||||
|
_findFrpcExe() {
|
||||||
|
const root = getProjectRoot();
|
||||||
|
const exeName = FRPC_EXE;
|
||||||
|
|
||||||
|
if (process.platform === 'win32') {
|
||||||
|
this._frpcSearchPaths = [
|
||||||
|
getResourcePath('frpc', exeName),
|
||||||
|
getResourcePath(exeName),
|
||||||
|
path.join(root, exeName),
|
||||||
|
path.join(root, 'frpc', exeName),
|
||||||
|
path.join(root, 'bin', exeName),
|
||||||
|
path.join(process.cwd(), exeName),
|
||||||
|
exeName
|
||||||
|
];
|
||||||
|
} else {
|
||||||
|
// Linux: 优先查找系统 PATH,再查项目目录
|
||||||
|
this._frpcSearchPaths = [
|
||||||
|
'/usr/bin/frpc',
|
||||||
|
'/usr/local/bin/frpc',
|
||||||
|
'/opt/frp/frpc',
|
||||||
|
path.join(root, 'frpc', exeName),
|
||||||
|
path.join(root, exeName),
|
||||||
|
path.join(process.cwd(), exeName),
|
||||||
|
exeName
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const p of this._frpcSearchPaths) {
|
||||||
|
if (fs.existsSync(p)) return p;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
_generateFrpcIni() {
|
||||||
|
const cfg = this.config.frpc || {};
|
||||||
|
const lines = ['[common]'];
|
||||||
|
lines.push('server_addr = ' + (cfg.serverAddr || '127.0.0.1'));
|
||||||
|
lines.push('server_port = ' + (cfg.serverPort || 6005));
|
||||||
|
|
||||||
|
if (cfg.authToken) {
|
||||||
|
lines.push('token = ' + cfg.authToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 代理配置
|
||||||
|
if (Array.isArray(cfg.proxies)) {
|
||||||
|
for (const p of cfg.proxies) {
|
||||||
|
if (!p.name) continue;
|
||||||
|
lines.push('');
|
||||||
|
lines.push('[' + p.name + ']');
|
||||||
|
lines.push('type = ' + (p.type || 'http'));
|
||||||
|
lines.push('local_ip = ' + (p.localIp || '127.0.0.1'));
|
||||||
|
lines.push('local_port = ' + (p.localPort || 0));
|
||||||
|
|
||||||
|
// http/https 类型用 subdomain,不设 remote_port
|
||||||
|
if (p.type === 'http' || p.type === 'https') {
|
||||||
|
if (p.subdomain) {
|
||||||
|
lines.push('subdomain = ' + p.subdomain);
|
||||||
|
}
|
||||||
|
if (p.customDomains) {
|
||||||
|
lines.push('custom_domains = ' + p.customDomains);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
lines.push('remote_port = ' + (p.remotePort || 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const root = getAppDataDir();
|
||||||
|
const iniPath = path.join(root, 'frpc.ini');
|
||||||
|
fs.writeFileSync(iniPath, lines.join('\n'), 'utf-8');
|
||||||
|
return iniPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
_startFrpc() {
|
||||||
|
const hadProcess = !!this.process;
|
||||||
|
this._stopFrpc();
|
||||||
|
|
||||||
|
const doSpawn = () => {
|
||||||
|
|
||||||
|
const exePath = this._findFrpcExe();
|
||||||
|
if (!exePath) {
|
||||||
|
_errFile('[Frpc] frpc.exe 未找到,搜索路径:', JSON.stringify(this._frpcSearchPaths));
|
||||||
|
for (const p of this._frpcSearchPaths) {
|
||||||
|
_errFile('[Frpc] 检查:', p, fs.existsSync(p) ? '(存在)' : '(不存在)');
|
||||||
|
}
|
||||||
|
this._setStatus('error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const iniPath = this._generateFrpcIni();
|
||||||
|
_logFile('[Frpc] 启动 frpc:', exePath, '-c', iniPath);
|
||||||
|
_logFile('[Frpc] ini 内容:', fs.readFileSync(iniPath, 'utf-8'));
|
||||||
|
|
||||||
|
try {
|
||||||
|
const spawnOpts = {
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe']
|
||||||
|
};
|
||||||
|
if (process.platform === 'win32') {
|
||||||
|
spawnOpts.windowsHide = true;
|
||||||
|
}
|
||||||
|
this.process = spawn(exePath, ['-c', iniPath], spawnOpts);
|
||||||
|
|
||||||
|
this._setStatus('starting');
|
||||||
|
|
||||||
|
this.process.stdout.on('data', (data) => {
|
||||||
|
const text = data.toString();
|
||||||
|
_logFile('[Frpc][stdout]', text.trim());
|
||||||
|
// frpc 输出中包含 "start proxy success" 表示连接成功
|
||||||
|
if (text.includes('start proxy success') || text.includes('run success')) {
|
||||||
|
this._setStatus('running');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.process.stderr.on('data', (data) => {
|
||||||
|
_errFile('[Frpc][stderr]', data.toString().trim());
|
||||||
|
});
|
||||||
|
|
||||||
|
this.process.on('error', (err) => {
|
||||||
|
_errFile('[Frpc] 进程错误:', err.message);
|
||||||
|
this._setStatus('error');
|
||||||
|
});
|
||||||
|
|
||||||
|
this.process.on('exit', (code) => {
|
||||||
|
_logFile('[Frpc] 进程退出, code:', code);
|
||||||
|
if (this.status !== 'stopped') {
|
||||||
|
this._setStatus('error');
|
||||||
|
}
|
||||||
|
this.process = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 超时检测:10 秒内没收到 running 则标记 error
|
||||||
|
clearTimeout(this._watchTimer);
|
||||||
|
this._watchTimer = setTimeout(() => {
|
||||||
|
if (this.status === 'starting') {
|
||||||
|
_errFile('[Frpc] 启动超时 (10s)');
|
||||||
|
this._setStatus('error');
|
||||||
|
}
|
||||||
|
}, 10000);
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
_errFile('[Frpc] 启动失败:', err.message);
|
||||||
|
this._setStatus('error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (hadProcess) {
|
||||||
|
// 延迟 3 秒让 frp 服务端释放旧代理名
|
||||||
|
setTimeout(doSpawn, 3000);
|
||||||
|
} else {
|
||||||
|
doSpawn();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_stopFrpc() {
|
||||||
|
clearTimeout(this._watchTimer);
|
||||||
|
if (this.process) {
|
||||||
|
// 移除旧进程的所有事件监听,避免退出事件在新进程启动后误设 error
|
||||||
|
this.process.removeAllListeners();
|
||||||
|
try {
|
||||||
|
this.process.kill();
|
||||||
|
} catch (e) { /* ignore */ }
|
||||||
|
this.process = null;
|
||||||
|
}
|
||||||
|
this._setStatus('stopped');
|
||||||
|
}
|
||||||
|
|
||||||
|
_setStatus(newStatus) {
|
||||||
|
const prev = this.status;
|
||||||
|
this.status = newStatus;
|
||||||
|
if (prev !== newStatus) {
|
||||||
|
_logFile('[Frpc] 状态变更: %s -> %s', prev, newStatus);
|
||||||
|
// 通知本地前端
|
||||||
|
this.app.emit('frpcStatusChange', { status: newStatus });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default FrpcService;
|
||||||
808
services/hikvision.js
Normal file
808
services/hikvision.js
Normal file
@ -0,0 +1,808 @@
|
|||||||
|
import crypto from 'crypto';
|
||||||
|
import net from 'net';
|
||||||
|
import http from 'http';
|
||||||
|
import https from 'https';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import { execSync } from 'child_process';
|
||||||
|
import { createRequire } from 'module';
|
||||||
|
import BaseService from '../core/BaseService.js';
|
||||||
|
|
||||||
|
let _app; // 构造时保存,避免 WS 回调时 this 丢失
|
||||||
|
|
||||||
|
const _require = createRequire(import.meta.url);
|
||||||
|
let _ffmpegPath = null;
|
||||||
|
try { _ffmpegPath = _require('@ffmpeg-installer/ffmpeg').path; } catch { /* */ }
|
||||||
|
// ffmpeg-static 优先级更高(版本更新)
|
||||||
|
try { const p = _require('ffmpeg-static'); _ffmpegPath = typeof p === 'string' ? p : p.path || p.default; } catch { /* */ }
|
||||||
|
|
||||||
|
class HikvisionService extends BaseService {
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
_app = this.app;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 向服务器拉取待执行任务 / 处理服务器返回的任务列表
|
||||||
|
*/
|
||||||
|
async fetchTasks(data) {
|
||||||
|
// 服务器返回了响应(空或非空数组)→ 不要再次拉取
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
if (data.length > 0) {
|
||||||
|
// 打印第一条,方便确认服务端实际字段名
|
||||||
|
console.log('[Hikvision] fetchTasks 收到', data.length, '个任务, 首条:', JSON.stringify(data[0]));
|
||||||
|
const ad = _app;
|
||||||
|
let created = 0;
|
||||||
|
for (const item of data) {
|
||||||
|
try {
|
||||||
|
// 服务端下发嵌套格式: item.server.{internal_ip,username,...}, item.camera.{channel_id}
|
||||||
|
const srv = item.server || {};
|
||||||
|
const cam = item.camera || {};
|
||||||
|
const uniqueCode = item.uniqueCode || '';
|
||||||
|
|
||||||
|
if (uniqueCode) {
|
||||||
|
const existing = ad.db.get('SELECT id FROM hik_tasks WHERE unique_code = ?', uniqueCode);
|
||||||
|
if (existing) continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const startStr = item.start_time || '';
|
||||||
|
const endStr = item.end_time || '';
|
||||||
|
if (!startStr) { console.log('[Hikvision] fetchTasks 跳过: 无 start_time'); continue; }
|
||||||
|
|
||||||
|
const startTime = new Date(startStr);
|
||||||
|
const endTime = endStr ? new Date(endStr) : new Date(startTime.getTime() + 5 * 60 * 1000);
|
||||||
|
const taskId = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||||||
|
const now = new Date();
|
||||||
|
const dateDir = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(2, '0')}`;
|
||||||
|
const relOutput = `/${dateDir}/task_${taskId.slice(-12)}.mp4`;
|
||||||
|
const videoTime = Math.ceil((endTime - startTime) / 1000);
|
||||||
|
|
||||||
|
const pad = n => String(n).padStart(2, '0');
|
||||||
|
const fmtStart = `${startTime.getFullYear()}-${pad(startTime.getMonth()+1)}-${pad(startTime.getDate())}T${pad(startTime.getHours())}:${pad(startTime.getMinutes())}:${pad(startTime.getSeconds())}`;
|
||||||
|
const fmtEnd = `${endTime.getFullYear()}-${pad(endTime.getMonth()+1)}-${pad(endTime.getDate())}T${pad(endTime.getHours())}:${pad(endTime.getMinutes())}:${pad(endTime.getSeconds())}`;
|
||||||
|
|
||||||
|
ad.db.table('hik_tasks').insert({
|
||||||
|
task_id: taskId, unique_code: uniqueCode,
|
||||||
|
task_params: JSON.stringify({
|
||||||
|
ip: srv.internal_ip || '', port: 7681, httpPort: srv.internal_port || 80,
|
||||||
|
user: srv.username || 'admin', pass: srv.password || '',
|
||||||
|
channel: cam.channel_id || 33,
|
||||||
|
start: fmtStart, end: fmtEnd,
|
||||||
|
speed: 4, output: relOutput, videoTime
|
||||||
|
}),
|
||||||
|
status: 'pending', retry: 0,
|
||||||
|
timeout: videoTime + 60, tmp_file_path: relOutput
|
||||||
|
});
|
||||||
|
created++;
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[Hikvision] 创建任务失败:', e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (created > 0) {
|
||||||
|
ad._lastFetchTime = null;
|
||||||
|
ad._scheduleHikTasks();
|
||||||
|
}
|
||||||
|
console.log('[Hikvision] fetchTasks 完成: 创建了', created, '个任务');
|
||||||
|
}
|
||||||
|
return; // 服务器已响应,不再拉取
|
||||||
|
}
|
||||||
|
// 客户端主动拉取:必须等 app.info 就绪(服务端已确认身份)且是录制电脑
|
||||||
|
if (!_app.info) {
|
||||||
|
console.log('[Hikvision] fetchTasks 跳过: app.info 未就绪,稍后重试');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!_app.info.is_recording) {
|
||||||
|
console.log('[Hikvision] fetchTasks 跳过: 非录制电脑 (is_recording=' + _app.info.is_recording + ')');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log('[Hikvision] fetchTasks → 向服务器拉取任务');
|
||||||
|
if (_app.wsClient && _app.wsClient.status === 'connected') {
|
||||||
|
_app.wsClient.send({ method: 'hikvision.fetchTasks', data: {} });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_fmtTime(date) {
|
||||||
|
const pad = n => String(n).padStart(2, '0');
|
||||||
|
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接收服务器下发的录制任务(WS 调用)
|
||||||
|
* 服务器 → 客户端:{ method: "hikvision.receiveTask", data: { uniqueCode, force?, taskId?, ip, user, pass, channel, start, end, speed, outputPrefix } }
|
||||||
|
*/
|
||||||
|
async receiveTask(data = {}) {
|
||||||
|
const app = _app;
|
||||||
|
console.log('[Hikvision] receiveTask 收到:', JSON.stringify(data));
|
||||||
|
|
||||||
|
// 支持两种格式:扁平 {ip,user,pass,channel} 或嵌套 {server:{internal_ip,...},camera:{channel_id}}
|
||||||
|
const srv = data.server || {};
|
||||||
|
const cam = data.camera || {};
|
||||||
|
const ip = data.ip || srv.internal_ip || '';
|
||||||
|
const user = data.user || srv.username || '';
|
||||||
|
const pass = data.pass || srv.password || '';
|
||||||
|
const channel = data.channel || cam.channel_id || 33;
|
||||||
|
const start = data.start || data.start_time || '';
|
||||||
|
const end = data.end || data.end_time || '';
|
||||||
|
const httpPort = data.httpPort || srv.internal_port || 80;
|
||||||
|
const port = data.port || 7681;
|
||||||
|
const speed = data.speed || 4;
|
||||||
|
|
||||||
|
if (!ip || !user || !pass || !start || !end) {
|
||||||
|
return { ok: false, message: '缺少必要参数: ip, user, pass, start, end' };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
console.log('[Hikvision] receiveTask 解析: ip=%s user=%s channel=%s', ip, user, channel);
|
||||||
|
|
||||||
|
// receiveTask 是强制推送接口,直接覆盖旧任务
|
||||||
|
const uniqueCode = data.uniqueCode || '';
|
||||||
|
if (uniqueCode) {
|
||||||
|
const existing = app.db.get('SELECT id, task_id, tmp_file_path, status FROM hik_tasks WHERE unique_code = ?', uniqueCode);
|
||||||
|
if (existing) {
|
||||||
|
console.log('[Hikvision] receiveTask 覆盖旧任务:', uniqueCode, existing.status, '→', existing.task_id);
|
||||||
|
app.db.run('DELETE FROM hik_tasks WHERE unique_code = ?', uniqueCode);
|
||||||
|
// 删除旧录像文件
|
||||||
|
const oldPath = app._resolvePath ? app._resolvePath(existing.tmp_file_path) : existing.tmp_file_path;
|
||||||
|
try {
|
||||||
|
if (oldPath && require('fs').existsSync(oldPath)) {
|
||||||
|
require('fs').unlinkSync(oldPath);
|
||||||
|
console.log('[Hikvision] receiveTask 已删除旧文件:', oldPath);
|
||||||
|
}
|
||||||
|
} catch (_) { /* 文件可能已不存在 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 服务器可指定 taskId
|
||||||
|
let taskId = data.taskId || '';
|
||||||
|
if (taskId) {
|
||||||
|
const dup = app.db.get('SELECT id FROM hik_tasks WHERE task_id = ?', taskId);
|
||||||
|
if (dup) return { ok: false, message: '任务ID重复: ' + taskId };
|
||||||
|
} else {
|
||||||
|
taskId = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||||||
|
}
|
||||||
|
const prefix = data.outputPrefix || 'hik';
|
||||||
|
const now = new Date();
|
||||||
|
const dateDir = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(2, '0')}`;
|
||||||
|
const relOutput = `/${dateDir}/${prefix}_${taskId.slice(-12)}.mp4`;
|
||||||
|
const videoTime = Math.ceil((new Date(end) - new Date(start)) / 1000);
|
||||||
|
|
||||||
|
app.db.table('hik_tasks').insert({
|
||||||
|
task_id: taskId,
|
||||||
|
unique_code: uniqueCode,
|
||||||
|
task_params: JSON.stringify({
|
||||||
|
ip, port, httpPort,
|
||||||
|
user, pass,
|
||||||
|
channel, start, end,
|
||||||
|
speed, output: relOutput, videoTime
|
||||||
|
}),
|
||||||
|
status: 'pending',
|
||||||
|
retry: 0,
|
||||||
|
timeout: videoTime + 60,
|
||||||
|
tmp_file_path: relOutput
|
||||||
|
});
|
||||||
|
|
||||||
|
// 有新任务 → 重置空闲计时
|
||||||
|
app._lastFetchTime = null;
|
||||||
|
app._scheduleHikTasks();
|
||||||
|
console.log('[Hikvision] receiveTask 创建成功:', taskId, 'uniqueCode:', uniqueCode);
|
||||||
|
return { ok: true, taskId, message: '任务已接收' };
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[Hikvision] receiveTask 异常:', e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 服务器确认收到任务结果回执(WS 调用)
|
||||||
|
* 服务器 → 客户端:{ method: "hikvision.taskAck", data: { taskId } }
|
||||||
|
*/
|
||||||
|
taskAck(data = {}) {
|
||||||
|
const taskId = data.taskId;
|
||||||
|
if (!taskId) return;
|
||||||
|
try {
|
||||||
|
this.app.db.run('UPDATE hik_tasks SET pushed = 1, push_retry = 0, push_next_retry_at = \'\' WHERE task_id = ?', taskId);
|
||||||
|
console.log('[Hikvision] 服务器已确认任务:', taskId);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[Hikvision] taskAck 更新失败:', e.message);
|
||||||
|
}
|
||||||
|
// 不返回值,避免回显
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发起下载(由 main.js 调用,传入已创建的 taskId 和 task 对象)
|
||||||
|
*/
|
||||||
|
startDownload(cfg, taskId, task) {
|
||||||
|
const { ip, port = 7681, httpPort = 80, user, pass, channel = 33, start, end, speed = 4, output } = cfg;
|
||||||
|
if (!user || !pass || !start || !end) {
|
||||||
|
throw new Error('缺少必要参数: user, pass, start, end');
|
||||||
|
}
|
||||||
|
const outPath = output || task.output || `G:/gameauto/recordings/hik_${taskId.slice(-12)}.mp4`;
|
||||||
|
|
||||||
|
task.id = taskId;
|
||||||
|
task.status = 'starting';
|
||||||
|
task.output = outPath;
|
||||||
|
task.startTime = Date.now();
|
||||||
|
task.progress = { chunks: 0, totalBytes: 0, totalMB: 0, speed };
|
||||||
|
task.params = { ip, channel, start, end, speed };
|
||||||
|
|
||||||
|
const params = { ip, port, httpPort, user, pass, channel, start, end, speed, output: outPath };
|
||||||
|
|
||||||
|
// 下载超时保护(视频时长/速度 + 120秒兜底)
|
||||||
|
const downloadTimeout = Math.max(120000, ((new Date(end) - new Date(start)) / 1000 / speed + 60) * 1000);
|
||||||
|
const timeoutTimer = setTimeout(() => {
|
||||||
|
if (task.status === 'running' || task.status === 'starting' || task.status === 'downloading') {
|
||||||
|
const err = new Error(`下载超时(${Math.round(downloadTimeout/1000)}s)`);
|
||||||
|
task._onError?.(err);
|
||||||
|
}
|
||||||
|
}, downloadTimeout);
|
||||||
|
|
||||||
|
process.nextTick(() => {
|
||||||
|
this._doDownload(task, params).then(() => clearTimeout(timeoutTimer)).catch(err => {
|
||||||
|
clearTimeout(timeoutTimer);
|
||||||
|
console.error('[Hikvision] 下载失败:', err.message);
|
||||||
|
task._onError?.(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
getTaskStatus(taskId) {
|
||||||
|
return this._activeDownloads.get(taskId) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通用登录认证,返回 { token, cookieJar, sessionTag }
|
||||||
|
*/
|
||||||
|
async login(ip, httpPort, user, pass) {
|
||||||
|
const httpBase = `http://${ip}:${httpPort}`;
|
||||||
|
const NS = { h: 'http://www.hikvision.com/ver20/XMLSchema' };
|
||||||
|
const { DOMParser } = await import('@xmldom/xmldom');
|
||||||
|
const cookieJar = {};
|
||||||
|
|
||||||
|
const capsUrl = `${httpBase}/ISAPI/Security/sessionLogin/capabilities?username=${user}&random:${String(Date.now()).slice(-8)}`;
|
||||||
|
const capsRes = await this._req('GET', capsUrl, null, {}, cookieJar);
|
||||||
|
const capsXml = new DOMParser().parseFromString(capsRes.body, 'text/xml');
|
||||||
|
const getText = (x) => { const el = capsXml.getElementsByTagNameNS(NS.h, x); return el?.length ? el[0].textContent : ''; };
|
||||||
|
const sid = getText('sessionID'), challenge = getText('challenge'), salt = getText('salt');
|
||||||
|
const itr = parseInt(getText('iterations')) || 1, ver = getText('sessionIDVersion') || '1';
|
||||||
|
const vl = getText('isSessionIDValidLongTerm') || 'false', st = getText('isSupportSessionTag') || 'false';
|
||||||
|
const irreversible = getText('isIrreversible') === 'true';
|
||||||
|
|
||||||
|
let digest;
|
||||||
|
if (irreversible) {
|
||||||
|
digest = crypto.createHash('sha256').update(user + salt + pass).digest('hex');
|
||||||
|
digest = crypto.createHash('sha256').update(digest + challenge).digest('hex');
|
||||||
|
for (let i = 2; i < itr; i++) digest = crypto.createHash('sha256').update(digest).digest('hex');
|
||||||
|
} else {
|
||||||
|
digest = crypto.createHash('sha256').update(pass + challenge).digest('hex');
|
||||||
|
for (let i = 1; i < itr; i++) digest = crypto.createHash('sha256').update(digest).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
let loginXml;
|
||||||
|
if (ver === '2') {
|
||||||
|
loginXml = `<SessionLogin><userName>${user}</userName><password>${digest}</password><sessionID>${sid}</sessionID><isSessionIDValidLongTerm>${vl}</isSessionIDValidLongTerm><sessionIDVersion>2</sessionIDVersion><isNeedSessionTag>${st}</isNeedSessionTag></SessionLogin>`;
|
||||||
|
} else {
|
||||||
|
loginXml = `<SessionLogin><userName>${user}</userName><password>${digest}</password><sessionID>${sid}</sessionID></SessionLogin>`;
|
||||||
|
}
|
||||||
|
const loginRes = await this._req('POST', `${httpBase}/ISAPI/Security/sessionLogin?timeStamp=${Date.now()}`, loginXml, { 'Content-Type': 'text/plain;charset=UTF-8' }, cookieJar);
|
||||||
|
if (loginRes.statusCode !== 200) throw new Error(`登录失败: ${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));
|
||||||
|
return { token, cookieJar, sessionTag, httpBase };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取通道列表 GET /api/hikvision/channels
|
||||||
|
*/
|
||||||
|
async getChannels(ip, httpPort, user, pass) {
|
||||||
|
const { token, cookieJar, sessionTag, httpBase } = await this.login(ip, httpPort, user, pass);
|
||||||
|
console.log('[Hikvision] getChannels sessionTag:', sessionTag ? 'present' : 'EMPTY', 'cookies:', Object.keys(cookieJar).join(','));
|
||||||
|
|
||||||
|
// session cookie + SessionTag header 是经过验证的可用组合
|
||||||
|
const headers = sessionTag ? { 'SessionTag': sessionTag } : {};
|
||||||
|
|
||||||
|
// 主路径: ContentMgmt/InputProxy/channels(XML 格式,最通用)
|
||||||
|
let res = await this._req('GET', `${httpBase}/ISAPI/ContentMgmt/InputProxy/channels`, null, headers, cookieJar);
|
||||||
|
console.log('[Hikvision] getChannels path1 status:', res.statusCode);
|
||||||
|
|
||||||
|
// 回退路径: System/Video/inputs/channels
|
||||||
|
if (res.statusCode !== 200) {
|
||||||
|
res = await this._req('GET', `${httpBase}/ISAPI/System/Video/inputs/channels`, null, headers, cookieJar);
|
||||||
|
console.log('[Hikvision] getChannels path2 status:', res.statusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res.statusCode === 200) {
|
||||||
|
return await this._parseChannelXmlAsync(res.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`获取通道失败: HTTP ${res.statusCode}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async _parseChannelXmlAsync(xml) {
|
||||||
|
const { DOMParser } = await import('@xmldom/xmldom');
|
||||||
|
const doc = new DOMParser().parseFromString(xml, 'text/xml');
|
||||||
|
const NS = { h: 'http://www.hikvision.com/ver20/XMLSchema' };
|
||||||
|
const items = doc.getElementsByTagNameNS(NS.h, 'InputProxyChannel') || doc.getElementsByTagNameNS(NS.h, 'VideoInputChannel');
|
||||||
|
const channels = [];
|
||||||
|
for (let i = 0; i < (items?.length || 0); i++) {
|
||||||
|
const el = items[i];
|
||||||
|
const t = (name) => { const n = el.getElementsByTagNameNS(NS.h, name); return n?.length ? n[0].textContent : ''; };
|
||||||
|
// 嵌套节点查找
|
||||||
|
const srcInfo = el.getElementsByTagNameNS(NS.h, 'sourceInputPortDescriptor')?.[0];
|
||||||
|
const st = (name) => srcInfo ? (srcInfo.getElementsByTagNameNS(NS.h, name)?.[0]?.textContent || '') : '';
|
||||||
|
channels.push({
|
||||||
|
id: parseInt(t('id')) || i + 1,
|
||||||
|
name: t('name')?.trim() || st('ipAddress') || `通道${i + 1}`,
|
||||||
|
ip: st('ipAddress') || '',
|
||||||
|
port: parseInt(st('managePortNo')) || 0,
|
||||||
|
model: st('model') || '',
|
||||||
|
serialNumber: st('serialNumber') || '',
|
||||||
|
streamType: st('streamType') || t('streamType') || 'main',
|
||||||
|
enabled: t('enabled') !== 'false'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return channels;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取实时流 WebSocket URL GET /api/hikvision/live-url
|
||||||
|
*/
|
||||||
|
async getLiveUrl(ip, httpPort, user, pass, port, channel, streamType = 1) {
|
||||||
|
const channelCode = 100 * (channel || 33) + streamType;
|
||||||
|
// 海康 SDK 实时流默认使用 RTSP 协议
|
||||||
|
return {
|
||||||
|
rtspUrl: `rtsp://${encodeURIComponent(user)}:${encodeURIComponent(pass)}@${ip}:554/Streaming/Channels/${channelCode}`,
|
||||||
|
channel: channel || 33,
|
||||||
|
streamType,
|
||||||
|
channelCode
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async _doDownload(task, p) {
|
||||||
|
const { ip, port, httpPort = 80, user, pass, channel = 33, start, end, speed = 4, output } = p;
|
||||||
|
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>`;
|
||||||
|
}
|
||||||
|
const loginRes = await this._req('POST', `${httpBase}/ISAPI/Security/sessionLogin?timeStamp=${Date.now()}`, loginXml, { 'Content-Type': 'text/plain;charset=UTF-8' }, cookieJar);
|
||||||
|
if (!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;
|
||||||
|
|
||||||
|
// [5] WS 下载
|
||||||
|
task.status = 'downloading';
|
||||||
|
const result = await this._wsDownload({ ip, port, channel, start, end, speed, output, token, task });
|
||||||
|
|
||||||
|
// [6] 转码
|
||||||
|
if (result.total === 0) {
|
||||||
|
task._onDone?.({ success: false, output, size: 0 });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const outputBase = output.replace(/\.ps$/i, '').replace(/\.mp4$/i, '');
|
||||||
|
let workFile = outputBase + '.ps';
|
||||||
|
const mp4Path = outputBase + '.mp4';
|
||||||
|
// 如果 _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
|
||||||
|
}
|
||||||
|
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 cmd = `"${ffmpegPath}" ${args} -y`;
|
||||||
|
try {
|
||||||
|
execSync(cmd, { timeout, stdio: 'pipe' });
|
||||||
|
if (fs.existsSync(mp4Path) && fs.statSync(mp4Path).size > 0) return true;
|
||||||
|
return false;
|
||||||
|
} catch (e) {
|
||||||
|
const stderr = e.stderr?.toString() || '';
|
||||||
|
if (stderr) console.error('[Hikvision] ffmpeg stderr:', stderr.slice(-200));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
transcoded = ffRun(`-i "${workFile}" -c:v copy -an "${mp4Path}"`, 60000);
|
||||||
|
if (!transcoded) transcoded = ffRun(`-i "${workFile}" -c:v libx264 -preset fast -crf 23 -an "${mp4Path}"`, 120000);
|
||||||
|
if (transcoded) {
|
||||||
|
const mp4Size = fs.statSync(mp4Path).size;
|
||||||
|
try { fs.unlinkSync(workFile); } catch { /* */ }
|
||||||
|
finalResult = { success: true, output: mp4Path, size: mp4Size, duration: result.elapsed, speed, chunks: result.chunks };
|
||||||
|
} else {
|
||||||
|
// 清理可能产生的 0 字节 mp4
|
||||||
|
try { if (fs.existsSync(mp4Path) && fs.statSync(mp4Path).size === 0) fs.unlinkSync(mp4Path); } catch { /* */ }
|
||||||
|
const psSize = fs.existsSync(workFile) ? fs.statSync(workFile).size : 0;
|
||||||
|
finalResult = { success: true, output: workFile, size: psSize, duration: result.elapsed, speed, rawPs: true };
|
||||||
|
}
|
||||||
|
} else if (fs.existsSync(workFile)) {
|
||||||
|
finalResult = { success: true, output: workFile, size: fs.statSync(workFile).size, duration: result.elapsed, speed, rawPs: true };
|
||||||
|
} else {
|
||||||
|
finalResult = { success: true, output, size: result.total, duration: result.elapsed, speed, rawPs: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
task._onDone?.(finalResult);
|
||||||
|
console.log(`[Hikvision] 完成: ${finalResult.output} ${(finalResult.size / 1048576).toFixed(1)}MB`);
|
||||||
|
}
|
||||||
|
|
||||||
|
_wsDownload({ ip, port, channel, start, end, speed, output, token, task }) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
// 和 Python hik_download.py 完全一致的流程
|
||||||
|
const outDir = path.dirname(output);
|
||||||
|
if (outDir && outDir !== '.') fs.mkdirSync(outDir, { recursive: true });
|
||||||
|
|
||||||
|
const wsKey = crypto.randomBytes(16).toString('base64');
|
||||||
|
const handshake = `GET /?version=1.0&cipherSuites=1&token=${token} HTTP/1.1\r\n` +
|
||||||
|
`Host: ${ip}:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
|
||||||
|
`Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: ${wsKey}\r\n` +
|
||||||
|
`Origin: http://127.0.0.1\r\nUser-Agent: Mozilla/5.0\r\n\r\n`;
|
||||||
|
|
||||||
|
const socket = new net.Socket();
|
||||||
|
socket.setTimeout(120000);
|
||||||
|
socket.connect(port, ip, () => socket.write(handshake));
|
||||||
|
|
||||||
|
// 累积 buffer + Promise 机制模拟 Python 的 sk.recv()
|
||||||
|
let buf = Buffer.alloc(0);
|
||||||
|
let waiter = null;
|
||||||
|
const notify = () => { if (waiter) { const w = waiter; waiter = null; w(); } };
|
||||||
|
|
||||||
|
// recvBytes(n): 阻塞式读取 n 字节,对应 Python 的 sk.recv(n)
|
||||||
|
const recvBytes = (n) => new Promise((resolveRecv) => {
|
||||||
|
const tryRead = () => {
|
||||||
|
if (buf.length >= n) {
|
||||||
|
const data = buf.slice(0, n);
|
||||||
|
buf = buf.slice(n);
|
||||||
|
resolveRecv(data);
|
||||||
|
} else {
|
||||||
|
waiter = tryRead;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
tryRead();
|
||||||
|
});
|
||||||
|
|
||||||
|
// recvAll(n): 循环读取直到拿到 n 字节
|
||||||
|
const recvAll = async (n) => {
|
||||||
|
const chunks = [];
|
||||||
|
let remain = n;
|
||||||
|
while (remain > 0) {
|
||||||
|
const part = await recvBytes(Math.min(remain, buf.length || remain));
|
||||||
|
chunks.push(part);
|
||||||
|
remain -= part.length;
|
||||||
|
// 如果 recvBytes 没给够,等下一次 data 事件
|
||||||
|
if (remain > 0) await new Promise(r => { waiter = r; });
|
||||||
|
}
|
||||||
|
return Buffer.concat(chunks);
|
||||||
|
};
|
||||||
|
|
||||||
|
// ws_recv: 读一个完整 WS 帧,返回 {op, payload}
|
||||||
|
const wsRecv = async () => {
|
||||||
|
const h = await recvBytes(2);
|
||||||
|
const op = h[0] & 0x0F;
|
||||||
|
let len = h[1] & 0x7F;
|
||||||
|
if (len === 126) { const ext = await recvBytes(2); len = ext.readUInt16BE(0); }
|
||||||
|
else if (len === 127) { const ext = await recvBytes(8); len = Number(ext.readBigUInt64BE(0)); }
|
||||||
|
const payload = await recvAll(len);
|
||||||
|
return { op, payload };
|
||||||
|
};
|
||||||
|
|
||||||
|
// ws_send: 发一个 WS 帧
|
||||||
|
const wsSend = (data, opcode) => {
|
||||||
|
const payload = typeof data === 'string' ? Buffer.from(data, 'utf-8') : data;
|
||||||
|
const len = payload.length;
|
||||||
|
const head = [opcode | 0x80];
|
||||||
|
if (len < 126) head.push(len);
|
||||||
|
else if (len < 65536) { head.push(126); const b = Buffer.alloc(2); b.writeUInt16BE(len); socket.write(Buffer.from(head)); socket.write(b); socket.write(payload); return; }
|
||||||
|
else { head.push(127); const b = Buffer.alloc(8); b.writeBigUInt64BE(BigInt(len)); socket.write(Buffer.from(head)); socket.write(b); socket.write(payload); return; }
|
||||||
|
socket.write(Buffer.concat([Buffer.from(head), payload]));
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.on('data', (data) => {
|
||||||
|
buf = Buffer.concat([buf, data]);
|
||||||
|
notify();
|
||||||
|
});
|
||||||
|
socket.on('error', (err) => reject(err));
|
||||||
|
socket.on('close', () => notify()); // 唤醒可能正在等待的 recv
|
||||||
|
|
||||||
|
// 主流程
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
// ===== 步骤 1: 握手 =====
|
||||||
|
// 等待 \r\n\r\n 出现(和 Python 的 while + recv(4096) 一样)
|
||||||
|
while (buf.indexOf('\r\n\r\n') === -1) await new Promise(r => { waiter = r; });
|
||||||
|
// 丢弃握手响应数据
|
||||||
|
const he = buf.indexOf('\r\n\r\n');
|
||||||
|
buf = buf.slice(he + 4);
|
||||||
|
|
||||||
|
// ===== 步骤 2: 发 playback 命令 =====
|
||||||
|
const cmd = { sequence: 0, cmd: 'playback', url: `live://${ip}:${port}/${channel}/0`, startTime: start, endTime: end };
|
||||||
|
wsSend(JSON.stringify(cmd), 0x01);
|
||||||
|
|
||||||
|
// ===== 步骤 3: 主循环,和 Python 完全一致 =====
|
||||||
|
const ws = fs.createWriteStream(output, { highWaterMark: 256 * 1024 });
|
||||||
|
let total = 0, chunks = 0, speedSent = false;
|
||||||
|
const t0 = Date.now();
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
let msg;
|
||||||
|
try { msg = await wsRecv(); } catch { break; }
|
||||||
|
if (!msg) break;
|
||||||
|
|
||||||
|
const { op, payload } = msg;
|
||||||
|
|
||||||
|
if (op === 0x09) {
|
||||||
|
// Ping -> Pong
|
||||||
|
wsSend(payload, 0x0A);
|
||||||
|
} else if (op === 0x01) {
|
||||||
|
// Text frame
|
||||||
|
try {
|
||||||
|
const obj = JSON.parse(payload.toString('utf-8'));
|
||||||
|
const sc = obj.statusCode || 0;
|
||||||
|
if (sc === 1) continue; // 心跳/确认,忽略
|
||||||
|
if (sc !== 0) { console.log('[Hikvision] NVR text response:', JSON.stringify(obj), 'startTime:', start, 'endTime:', end, 'ch:', channel); break; }
|
||||||
|
} catch { /* non-JSON text */ }
|
||||||
|
} else if (op === 0x02) {
|
||||||
|
// Binary frame → 和 Python 一样,收到数据后再发 speed
|
||||||
|
if (!speedSent && chunks >= 10) {
|
||||||
|
wsSend(JSON.stringify({ sequence: 0, cmd: 'speed', rate: speed }), 0x01);
|
||||||
|
speedSent = true;
|
||||||
|
}
|
||||||
|
chunks++; total += payload.length;
|
||||||
|
ws.write(payload);
|
||||||
|
if (task) {
|
||||||
|
task.progress.chunks = chunks;
|
||||||
|
task.progress.totalBytes = total;
|
||||||
|
task.progress.totalMB = Math.round(total / 1048576 * 10) / 10;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 其他 opcode 忽略(Python 也直接 return d 但不处理)
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.end();
|
||||||
|
const elapsed = (Date.now() - t0) / 1000;
|
||||||
|
resolve({ total, chunks, elapsed });
|
||||||
|
} catch (e) {
|
||||||
|
reject(e);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WebSocket 实时预览(公网可用,走 7681 端口,绕过 RTSP 554)
|
||||||
|
* @param {{ ip, port, channel, streamType, token, onData, onError }} opts
|
||||||
|
* @returns {Promise<{ close: function }>}
|
||||||
|
*/
|
||||||
|
_wsLiveView({ ip, port, channel, streamType, token, onData, onError }) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const wsKey = crypto.randomBytes(16).toString('base64');
|
||||||
|
const handshake = `GET /?version=1.0&cipherSuites=1&token=${token} HTTP/1.1\r\n` +
|
||||||
|
`Host: ${ip}:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
|
||||||
|
`Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: ${wsKey}\r\n` +
|
||||||
|
`Origin: http://127.0.0.1\r\nUser-Agent: Mozilla/5.0\r\n\r\n`;
|
||||||
|
|
||||||
|
const socket = new net.Socket();
|
||||||
|
socket.setTimeout(300000);
|
||||||
|
socket.connect(port, ip, () => socket.write(handshake));
|
||||||
|
|
||||||
|
let buf = Buffer.alloc(0);
|
||||||
|
let waiter = null;
|
||||||
|
const notify = () => { if (waiter) { const w = waiter; waiter = null; w(); } };
|
||||||
|
|
||||||
|
const recvBytes = (n) => new Promise((resolveRecv) => {
|
||||||
|
const tryRead = () => {
|
||||||
|
if (buf.length >= n) { const d = buf.slice(0, n); buf = buf.slice(n); resolveRecv(d); }
|
||||||
|
else { waiter = tryRead; }
|
||||||
|
};
|
||||||
|
tryRead();
|
||||||
|
});
|
||||||
|
|
||||||
|
const recvAll = async (n) => {
|
||||||
|
const chunks = []; let remain = n;
|
||||||
|
while (remain > 0) {
|
||||||
|
if (buf.length > 0) { const take = Math.min(remain, buf.length); chunks.push(buf.slice(0, take)); buf = buf.slice(take); remain -= take; }
|
||||||
|
if (remain > 0) await new Promise(r => { waiter = r; });
|
||||||
|
}
|
||||||
|
return Buffer.concat(chunks);
|
||||||
|
};
|
||||||
|
|
||||||
|
const wsRecv = async () => {
|
||||||
|
const h = await recvBytes(2);
|
||||||
|
const op = h[0] & 0x0F;
|
||||||
|
let len = h[1] & 0x7F;
|
||||||
|
if (len === 126) { const ext = await recvBytes(2); len = ext.readUInt16BE(0); }
|
||||||
|
else if (len === 127) { const ext = await recvBytes(8); len = Number(ext.readBigUInt64BE(0)); }
|
||||||
|
return { op, payload: await recvAll(len) };
|
||||||
|
};
|
||||||
|
|
||||||
|
const wsSend = (data, opcode) => {
|
||||||
|
const payload = typeof data === 'string' ? Buffer.from(data, 'utf-8') : data;
|
||||||
|
const len = payload.length;
|
||||||
|
if (len < 126) {
|
||||||
|
socket.write(Buffer.concat([Buffer.from([opcode | 0x80, len]), payload]));
|
||||||
|
} else if (len < 65536) {
|
||||||
|
const b = Buffer.alloc(2); b.writeUInt16BE(len);
|
||||||
|
socket.write(Buffer.from([opcode | 0x80, 126])); socket.write(b); socket.write(payload);
|
||||||
|
} else {
|
||||||
|
const b = Buffer.alloc(8); b.writeBigUInt64BE(BigInt(len));
|
||||||
|
socket.write(Buffer.from([opcode | 0x80, 127])); socket.write(b); socket.write(payload);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.on('data', (data) => { buf = Buffer.concat([buf, data]); notify(); });
|
||||||
|
socket.on('error', (err) => { onError?.(err); reject(err); });
|
||||||
|
socket.on('close', () => notify());
|
||||||
|
|
||||||
|
let closed = false;
|
||||||
|
const close = () => { if (closed) return; closed = true; try { socket.destroy(); } catch {} };
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
while (buf.indexOf('\r\n\r\n') === -1) await new Promise(r => { waiter = r; });
|
||||||
|
const he = buf.indexOf('\r\n\r\n');
|
||||||
|
const respHeader = buf.slice(0, he).toString();
|
||||||
|
buf = buf.slice(he + 4);
|
||||||
|
if (!respHeader.includes('101')) throw new Error('WebSocket 握手失败: ' + respHeader.split('\r\n')[0]);
|
||||||
|
|
||||||
|
const cmd = { sequence: 0, cmd: 'liveview', url: `live://${ip}:${port}/${channel}/${streamType}` };
|
||||||
|
wsSend(JSON.stringify(cmd), 0x01);
|
||||||
|
resolve({ close, socket });
|
||||||
|
|
||||||
|
while (!closed) {
|
||||||
|
let msg; try { msg = await wsRecv(); } catch { break; }
|
||||||
|
if (!msg || closed) break;
|
||||||
|
const { op, payload } = msg;
|
||||||
|
if (op === 0x09) { wsSend(payload, 0x0A); }
|
||||||
|
else if (op === 0x02) { onData?.(payload); }
|
||||||
|
else if (op === 0x01) {
|
||||||
|
try { const obj = JSON.parse(payload.toString('utf-8')); if (obj.statusCode && obj.statusCode !== 0 && obj.statusCode !== 1) break; } catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { onError?.(e); }
|
||||||
|
finally { close(); }
|
||||||
|
})();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async _req(method, url, body, headers, cookieJar, binary = false) {
|
||||||
|
const u = new URL(url);
|
||||||
|
const bodyBuf = body ? Buffer.from(typeof body === 'string' ? body : body, 'utf-8') : null;
|
||||||
|
const cookies = Object.entries(cookieJar || {}).map(([k, v]) => `${k}=${v}`).join('; ');
|
||||||
|
const hdrs = { 'Accept': '*/*', 'User-Agent': 'Mozilla/5.0', ...headers };
|
||||||
|
if (cookies) hdrs['Cookie'] = cookies;
|
||||||
|
if (bodyBuf) hdrs['Content-Length'] = bodyBuf.length;
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const mod = u.protocol === 'https:' ? https : http;
|
||||||
|
const req = mod.request({ hostname: u.hostname, port: u.port || 80, path: u.pathname + u.search, method, headers: hdrs, timeout: 10000 }, (res) => {
|
||||||
|
const ck = [];
|
||||||
|
res.on('data', c => ck.push(c));
|
||||||
|
res.on('end', () => {
|
||||||
|
req.destroy();
|
||||||
|
const raw = Buffer.concat(ck);
|
||||||
|
const body = binary ? raw : raw.toString('utf-8');
|
||||||
|
if (res.headers['set-cookie'] && cookieJar) {
|
||||||
|
(Array.isArray(res.headers['set-cookie']) ? res.headers['set-cookie'] : [res.headers['set-cookie']]).forEach(sc => {
|
||||||
|
const m = sc.match(/^([^=;]+)=([^;]*)/); if (m) cookieJar[m[1]] = m[2];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
resolve({ statusCode: res.statusCode, headers: res.headers, body });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
req.on('error', reject);
|
||||||
|
req.on('timeout', () => { req.destroy(); reject(new Error('请求超时')); });
|
||||||
|
if (bodyBuf) req.write(bodyBuf);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async _digestGet(url, user, pass, returnBody) {
|
||||||
|
const u = new URL(url);
|
||||||
|
const first = await this._req('GET', url, null, {}, {});
|
||||||
|
const ah = first.statusCode === 401 ? this._digestParse(first.body, first) : null;
|
||||||
|
if (!ah && first.statusCode === 200 && returnBody) return first;
|
||||||
|
if (!ah) throw new Error('无法获取 Digest 认证信息');
|
||||||
|
|
||||||
|
const ha1 = crypto.createHash('md5').update(`${user}:${ah.realm}:${pass}`).digest('hex');
|
||||||
|
const ha2 = crypto.createHash('md5').update(`GET:${u.pathname + u.search}`).digest('hex');
|
||||||
|
const nc = '00000001', cnonce = '0a4f113b';
|
||||||
|
const resp = crypto.createHash('md5').update(`${ha1}:${ah.nonce}:${nc}:${cnonce}:${ah.qop || 'auth'}:${ha2}`).digest('hex');
|
||||||
|
let authStr = `Digest username="${user}", realm="${ah.realm}", nonce="${ah.nonce}", uri="${u.pathname + u.search}", response="${resp}", algorithm=MD5`;
|
||||||
|
if (ah.qop) authStr += `, qop=${ah.qop}, nc=${nc}, cnonce="${cnonce}"`;
|
||||||
|
if (ah.opaque) authStr += `, opaque="${ah.opaque}"`;
|
||||||
|
return this._req('GET', url, null, { 'Authorization': authStr }, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
_digestParse(resBody, res) {
|
||||||
|
const hdr = res?.headers?.['www-authenticate'];
|
||||||
|
if (hdr) { const m = hdr.match(/^Digest\s+(.+)/i); if (m) return this._digestParams(m[1]); }
|
||||||
|
if (typeof resBody === 'string') { const m = resBody.match(/WWW-Authenticate:\s*Digest\s+(.+)/i); if (m) return this._digestParams(m[1]); }
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
_digestParams(str) {
|
||||||
|
const p = {}; for (const m of str.matchAll(/(\w+)\s*=\s*(?:"([^"]*)"|([^,\s]+))/g)) p[m[1]] = m[2] !== undefined ? m[2] : m[3]; return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
_findFfmpeg() {
|
||||||
|
// 0) Electron 打包后:asar.unpacked 中的 ffmpeg(可执行)
|
||||||
|
if (process.versions?.electron && process.resourcesPath) {
|
||||||
|
const unpackedExe = path.join(process.resourcesPath, 'app.asar.unpacked', 'node_modules', '@ffmpeg-installer', 'win32-x64', 'ffmpeg.exe');
|
||||||
|
if (fs.existsSync(unpackedExe)) return unpackedExe;
|
||||||
|
}
|
||||||
|
// 1) 项目内 npm 包(最可靠,开发/打包都可用)
|
||||||
|
if (_ffmpegPath && fs.existsSync(_ffmpegPath)) return _ffmpegPath;
|
||||||
|
// 2) 全局 npm 安装路径
|
||||||
|
for (const base of [process.env.APPDATA, process.env.LOCALAPPDATA].filter(Boolean)) {
|
||||||
|
const p = path.join(base, 'npm', 'node_modules', '@ffmpeg-installer', 'ffmpeg', 'node_modules', '@ffmpeg-installer', 'win32-x64', 'ffmpeg.exe');
|
||||||
|
if (fs.existsSync(p)) return p;
|
||||||
|
}
|
||||||
|
// 3) 系统 PATH
|
||||||
|
try { const r = execSync('where ffmpeg 2>nul', { encoding: 'utf-8', stdio: 'pipe' }).trim().split(/\r?\n/).filter(Boolean); if (r.length) return r[0]; } catch { /* */ }
|
||||||
|
// 4) winget 路径
|
||||||
|
try {
|
||||||
|
const wb = path.join(process.env.LOCALAPPDATA || '', 'Microsoft', 'WinGet', 'Packages');
|
||||||
|
for (const d of fs.readdirSync(wb)) {
|
||||||
|
if (d.startsWith('Gyan.FFmpeg')) {
|
||||||
|
const p = path.join(wb, d, 'ffmpeg-8.1.2-full_build', 'bin', 'ffmpeg.exe');
|
||||||
|
if (fs.existsSync(p)) return p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch { /* */ }
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default HikvisionService;
|
||||||
|
|
||||||
|
// DEBUG
|
||||||
@ -4,6 +4,8 @@ import fs from 'fs';
|
|||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { pathToFileURL } from 'url';
|
import { pathToFileURL } from 'url';
|
||||||
import lodopUtil from '../utils/lodop.js';
|
import lodopUtil from '../utils/lodop.js';
|
||||||
|
import { isRecordingMode } from '../utils/runtime.js';
|
||||||
|
|
||||||
// 打印机服务类
|
// 打印机服务类
|
||||||
class PrinterService extends service {
|
class PrinterService extends service {
|
||||||
constructor() {
|
constructor() {
|
||||||
@ -12,8 +14,16 @@ class PrinterService extends service {
|
|||||||
this.print = this.print.bind(this); // 确保上下文绑定
|
this.print = this.print.bind(this); // 确保上下文绑定
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 录制模式守卫:非 Windows 或纯录制模式拒绝打印相关操作
|
||||||
|
_guardRecordingMode() {
|
||||||
|
if (isRecordingMode(this.config)) {
|
||||||
|
throw new Error('当前运行在录制模式,不支持打印相关操作');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 读取 Windows 打印服务的打印机列表,返回 Promise<json>
|
// 读取 Windows 打印服务的打印机列表,返回 Promise<json>
|
||||||
async getWindowsPrinters() {
|
async getWindowsPrinters() {
|
||||||
|
this._guardRecordingMode();
|
||||||
const res = new Promise((resolve, reject) => {
|
const res = new Promise((resolve, reject) => {
|
||||||
const command = `powershell -NoProfile -Command "$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[System.Text.Encoding]::UTF8; Get-CimInstance Win32_Printer | Select-Object Name,WorkOffline | ConvertTo-Json -Compress"`;
|
const command = `powershell -NoProfile -Command "$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[System.Text.Encoding]::UTF8; Get-CimInstance Win32_Printer | Select-Object Name,WorkOffline | ConvertTo-Json -Compress"`;
|
||||||
exec(command, { encoding: 'buffer', maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
|
exec(command, { encoding: 'buffer', maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
|
||||||
@ -44,6 +54,7 @@ class PrinterService extends service {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
print(data) {
|
print(data) {
|
||||||
|
this._guardRecordingMode();
|
||||||
console.log("打印服务收到打印请求,数据:", data);
|
console.log("打印服务收到打印请求,数据:", data);
|
||||||
const { printerComponents } = this.app;
|
const { printerComponents } = this.app;
|
||||||
console.log("所有打印组件", printerComponents.components);
|
console.log("所有打印组件", printerComponents.components);
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
import service from '../core/BaseService.js';
|
import service from '../core/BaseService.js';
|
||||||
|
import { isRecordingMode } from '../utils/runtime.js';
|
||||||
|
|
||||||
class PrinterComponentService extends service {
|
class PrinterComponentService extends service {
|
||||||
constructor() {
|
constructor() {
|
||||||
@ -7,8 +8,15 @@ class PrinterComponentService extends service {
|
|||||||
this.getStatus = this.getStatus.bind(this);
|
this.getStatus = this.getStatus.bind(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_guardRecordingMode() {
|
||||||
|
if (isRecordingMode(this.config)) {
|
||||||
|
throw new Error('当前运行在录制模式,不支持打印组件操作');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 获取所有打印组件
|
// 获取所有打印组件
|
||||||
getAll() {
|
getAll() {
|
||||||
|
this._guardRecordingMode();
|
||||||
const { app } = this;
|
const { app } = this;
|
||||||
if (app && app.printerComponents) {
|
if (app && app.printerComponents) {
|
||||||
const components = app.printerComponents.getAllPorts();
|
const components = app.printerComponents.getAllPorts();
|
||||||
@ -21,6 +29,7 @@ class PrinterComponentService extends service {
|
|||||||
|
|
||||||
// 获取指定组件状态
|
// 获取指定组件状态
|
||||||
getStatus(name) {
|
getStatus(name) {
|
||||||
|
this._guardRecordingMode();
|
||||||
const { app } = this;
|
const { app } = this;
|
||||||
if (app && app.printerComponents) {
|
if (app && app.printerComponents) {
|
||||||
return app.printerComponents.getStatus(name);
|
return app.printerComponents.getStatus(name);
|
||||||
|
|||||||
@ -32,15 +32,25 @@ class SettingService extends service {
|
|||||||
this.restartBackend = this.restartBackend.bind(this);
|
this.restartBackend = this.restartBackend.bind(this);
|
||||||
this.setToken = this.setToken.bind(this);
|
this.setToken = this.setToken.bind(this);
|
||||||
this.setInfo = this.setInfo.bind(this);
|
this.setInfo = this.setInfo.bind(this);
|
||||||
|
this.frpcDisconnect = this.frpcDisconnect.bind(this);
|
||||||
|
this.setCameraOSD = this.setCameraOSD.bind(this);
|
||||||
|
this.clearCameraOSD = this.clearCameraOSD.bind(this);
|
||||||
}
|
}
|
||||||
// 判断是否已绑定
|
// 判断是否已绑定
|
||||||
info() {
|
info() {
|
||||||
const {config} = this;
|
const {config} = this;
|
||||||
|
const hik = config.hikvision || {};
|
||||||
return {
|
return {
|
||||||
isBind: !!config.token,
|
isBind: !!config.token,
|
||||||
name: config.name || '',
|
name: config.name || '',
|
||||||
isService: !!config.isService,
|
isService: !!config.isService,
|
||||||
wsPort: Number(config.wsPort) || 3001
|
wsPort: Number(config.wsPort) || 17301,
|
||||||
|
recording: {
|
||||||
|
isRecording: !!hik.isRecording,
|
||||||
|
maxStorage: hik.maxStorage || '50GB',
|
||||||
|
downloadDir: hik.downloadDir || '',
|
||||||
|
remotePlayUrl: hik.remotePlayUrl || ''
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -69,7 +79,7 @@ class SettingService extends service {
|
|||||||
|
|
||||||
async restartBackend(data = {}) {
|
async restartBackend(data = {}) {
|
||||||
const { app } = this;
|
const { app } = this;
|
||||||
const targetWsPort = Number(data.wsPort) || Number(app.config?.wsPort) || 3001;
|
const targetWsPort = Number(data.wsPort) || Number(app.config?.wsPort) || 17301;
|
||||||
|
|
||||||
if (isManagedBackendRunnerProcess()) {
|
if (isManagedBackendRunnerProcess()) {
|
||||||
scheduleCurrentProcessExit();
|
scheduleCurrentProcessExit();
|
||||||
@ -111,6 +121,12 @@ class SettingService extends service {
|
|||||||
config.token = '';
|
config.token = '';
|
||||||
configUtil.write(config);
|
configUtil.write(config);
|
||||||
app.isBind = false;
|
app.isBind = false;
|
||||||
|
|
||||||
|
// 停止 frpc
|
||||||
|
if (app.services.frpc && typeof app.services.frpc.stop === 'function') {
|
||||||
|
app.services.frpc.stop();
|
||||||
|
}
|
||||||
|
|
||||||
// 解绑后主动请求新绑定码
|
// 解绑后主动请求新绑定码
|
||||||
if (app.wsClient?.status === 'connected') {
|
if (app.wsClient?.status === 'connected') {
|
||||||
app.wsClient.send({ method: 'bind.generateCode', data: {} });
|
app.wsClient.send({ method: 'bind.generateCode', data: {} });
|
||||||
@ -198,10 +214,75 @@ class SettingService extends service {
|
|||||||
}
|
}
|
||||||
async setInfo(data) {
|
async setInfo(data) {
|
||||||
const { config, app } = this;
|
const { config, app } = this;
|
||||||
|
// 更新名称
|
||||||
config.name = data.computerInfo?.name || data.name || '';
|
config.name = data.computerInfo?.name || data.name || '';
|
||||||
console.log("设置打印台信息", data);
|
console.log("设置打印台信息", data);
|
||||||
app.info = data;
|
app.info = data;
|
||||||
|
|
||||||
|
// 身份就绪 → 重置空闲计时,立即触发任务拉取
|
||||||
|
app._lastFetchTime = null;
|
||||||
|
app._scheduleHikTasks();
|
||||||
|
|
||||||
|
// 服务器下发的录制配置 → 覆盖 config.hikvision
|
||||||
|
if (!config.hikvision) config.hikvision = {};
|
||||||
|
const hik = config.hikvision;
|
||||||
|
if (data.hasOwnProperty('is_recording')) {
|
||||||
|
hik.isRecording = !!data.is_recording;
|
||||||
|
}
|
||||||
|
if (data.hasOwnProperty('recording_size_value')) {
|
||||||
|
const val = Number(data.recording_size_value) || 0;
|
||||||
|
const unit = data.recording_size_unit || 'GB';
|
||||||
|
hik.maxStorage = val > 0 ? String(val) + unit : hik.maxStorage || '50GB';
|
||||||
|
}
|
||||||
|
if (data.hasOwnProperty('recording_directory')) {
|
||||||
|
const newDir = data.recording_directory || '';
|
||||||
|
const oldDir = hik.downloadDir || '';
|
||||||
|
if (newDir && oldDir && newDir !== oldDir) {
|
||||||
|
// 目录变更,通知前端询问是否迁移
|
||||||
|
app.emit('migrationNeeded', { oldDir, newDir });
|
||||||
|
}
|
||||||
|
hik.downloadDir = newDir;
|
||||||
|
}
|
||||||
|
// 忽视服务端下发的 remote_play_url,使用本地 /recordings/ 直接访问
|
||||||
|
|
||||||
configUtil.write(config);
|
configUtil.write(config);
|
||||||
|
|
||||||
|
// 服务端下发的 frp 配置 → 转换为 frpc 配置并驱动启停
|
||||||
|
if (data.frp && app.services.frpc && typeof app.services.frpc.updateConfig === 'function') {
|
||||||
|
const frp = data.frp;
|
||||||
|
// 读取运行时实际绑定的 HTTP 端口
|
||||||
|
let localPort = this.config.httpPort || 17311;
|
||||||
|
try {
|
||||||
|
const { readRuntimeState } = await import('../utils/runtime.js');
|
||||||
|
const rt = readRuntimeState();
|
||||||
|
if (rt.httpPort) localPort = rt.httpPort;
|
||||||
|
} catch (_) { /* use config fallback */ }
|
||||||
|
const frpcCfg = {
|
||||||
|
enabled: true,
|
||||||
|
serverAddr: frp.server_addr || '',
|
||||||
|
serverPort: Number(frp.server_port) || 6005,
|
||||||
|
authToken: frp.auth_token || '',
|
||||||
|
token: frp.token || '',
|
||||||
|
proxies: [{
|
||||||
|
name: frp.subdomain || 'printer',
|
||||||
|
type: 'http',
|
||||||
|
localIp: '127.0.0.1',
|
||||||
|
localPort: localPort,
|
||||||
|
subdomain: frp.subdomain || ''
|
||||||
|
}]
|
||||||
|
};
|
||||||
|
|
||||||
|
if (data.is_recording) {
|
||||||
|
// 录制开启:强制更新配置并启动 frpc(不比对 key,直接重启)
|
||||||
|
app.services.frpc.updateConfig(frpcCfg);
|
||||||
|
} else {
|
||||||
|
// 录制关闭:停止 frpc
|
||||||
|
if (typeof app.services.frpc.stop === 'function') {
|
||||||
|
app.services.frpc.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 登录成功后主动全量同步一次组件状态,避免服务端只收到后续增量变化
|
// 登录成功后主动全量同步一次组件状态,避免服务端只收到后续增量变化
|
||||||
if (app.wsClient && app.printerComponents) {
|
if (app.wsClient && app.printerComponents) {
|
||||||
const allStatus = app.printerComponents.getAllStatus();
|
const allStatus = app.printerComponents.getAllStatus();
|
||||||
@ -210,7 +291,123 @@ class SettingService extends service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { ok: true };
|
// 通知本地 Web 客户端信息已更新(名称 + 录制配置)
|
||||||
|
app.emit('infoChanged', {
|
||||||
|
name: config.name,
|
||||||
|
isRecording: hik.isRecording,
|
||||||
|
maxStorage: hik.maxStorage,
|
||||||
|
downloadDir: hik.downloadDir
|
||||||
|
});
|
||||||
|
|
||||||
|
// 不返回值,避免 wsClient 将服务端推送回显为请求
|
||||||
|
}
|
||||||
|
|
||||||
|
// 服务端通知断开 frpc(录制电脑被替换时)
|
||||||
|
frpcDisconnect() {
|
||||||
|
const { app } = this;
|
||||||
|
if (app.services.frpc && typeof app.services.frpc.stop === 'function') {
|
||||||
|
app.services.frpc.stop();
|
||||||
|
}
|
||||||
|
// 不返回值,避免回显
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 服务端下发 OSD 设置 WS method: camera.osd.set
|
||||||
|
* data: { rtspUrl, text, x?, y? }
|
||||||
|
*/
|
||||||
|
async setCameraOSD(data) {
|
||||||
|
if (!data || !data.rtspUrl || !data.text) return;
|
||||||
|
try {
|
||||||
|
const { setCameraOSD } = await import('../utils/cameraOsd.js');
|
||||||
|
await setCameraOSD(data.rtspUrl, data.text, data.x, data.y);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[CameraOSD] set 执行失败:', e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 服务端下发 OSD 清空 WS method: camera.osd.clear
|
||||||
|
* data: { rtspUrl }
|
||||||
|
*/
|
||||||
|
async clearCameraOSD(data) {
|
||||||
|
if (!data || !data.rtspUrl) return;
|
||||||
|
try {
|
||||||
|
const { clearCameraOSD } = await import('../utils/cameraOsd.js');
|
||||||
|
await clearCameraOSD(data.rtspUrl);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[CameraOSD] clear 执行失败:', e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 迁移录制文件到新目录 + 更新 DB 路径
|
||||||
|
* 前端确认迁移后调用
|
||||||
|
*/
|
||||||
|
async migrateFiles(data = {}) {
|
||||||
|
const { app } = this;
|
||||||
|
const oldDirRaw = data.oldDir || '';
|
||||||
|
const newDirRaw = data.newDir || '';
|
||||||
|
if (!oldDirRaw || !newDirRaw || oldDirRaw === newDirRaw) {
|
||||||
|
return { ok: false, message: '目录未变化,无需迁移' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 规范化目录(裸盘符 → 路径)
|
||||||
|
const normDir = (d) => {
|
||||||
|
d = (d || '').replace(/[\\\/]+$/, '');
|
||||||
|
if (/^[A-Za-z]$/.test(d)) d = d + ':/hikvision_recordings';
|
||||||
|
return d.replace(/\\/g, '/');
|
||||||
|
};
|
||||||
|
const oldDir = normDir(oldDirRaw);
|
||||||
|
const newDir = normDir(newDirRaw);
|
||||||
|
|
||||||
|
const fs = await import('fs');
|
||||||
|
const path = await import('path');
|
||||||
|
const db = app.db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!fs.existsSync(newDir)) fs.mkdirSync(newDir, { recursive: true });
|
||||||
|
const rows = db.all('SELECT id, output_path FROM hik_downloads WHERE deleted = 0');
|
||||||
|
let migrated = 0, skipped = 0;
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
const storedPath = row.output_path || '';
|
||||||
|
if (!storedPath) { skipped++; continue; }
|
||||||
|
|
||||||
|
// 解析为绝对路径
|
||||||
|
let absPath;
|
||||||
|
if (storedPath.startsWith('/')) {
|
||||||
|
// 相对路径:拼接到旧目录
|
||||||
|
absPath = path.join(oldDir, storedPath).replace(/\\/g, '/');
|
||||||
|
} else {
|
||||||
|
// 旧格式绝对路径
|
||||||
|
absPath = storedPath.replace(/\\/g, '/');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fs.existsSync(absPath)) { skipped++; continue; }
|
||||||
|
|
||||||
|
// 计算相对于旧目录的路径,拼接到新目录
|
||||||
|
let relPath;
|
||||||
|
if (absPath.startsWith(oldDir + '/')) {
|
||||||
|
relPath = absPath.slice(oldDir.length); // "/2026/07/26/xxx.mp4"
|
||||||
|
} else {
|
||||||
|
relPath = '/' + path.basename(absPath);
|
||||||
|
}
|
||||||
|
const newAbsPath = (newDir + relPath).replace(/\\/g, '/');
|
||||||
|
|
||||||
|
// 复制文件
|
||||||
|
const newParent = path.dirname(newAbsPath);
|
||||||
|
if (!fs.existsSync(newParent)) fs.mkdirSync(newParent, { recursive: true });
|
||||||
|
fs.copyFileSync(absPath, newAbsPath);
|
||||||
|
|
||||||
|
// 更新 DB 为相对路径
|
||||||
|
db.run('UPDATE hik_downloads SET output_path = ? WHERE id = ?', relPath, row.id);
|
||||||
|
migrated++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ok: true, message: `迁移完成:${migrated} 个文件,跳过 ${skipped} 个`, migrated, skipped };
|
||||||
|
} catch (e) {
|
||||||
|
return { ok: false, message: `迁移失败:${e.message}` };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
46
test_batch.mjs
Normal file
46
test_batch.mjs
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
import http from 'http';
|
||||||
|
const PORT = 17311;
|
||||||
|
|
||||||
|
async function callApi(path, options = {}) {
|
||||||
|
const m = options.method || 'GET';
|
||||||
|
const body = options.body ? JSON.stringify(options.body) : null;
|
||||||
|
const h = body ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } : {};
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const req = http.request(`http://127.0.0.1:${PORT}${path}`, { method: m, headers: h }, (res) => {
|
||||||
|
const c = []; res.on('data', x => c.push(x));
|
||||||
|
res.on('end', () => { try { resolve(JSON.parse(Buffer.concat(c).toString('utf-8'))); } catch { resolve({}); } });
|
||||||
|
});
|
||||||
|
req.on('error', reject);
|
||||||
|
if (body) req.write(body);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 连续提交 4 个任务
|
||||||
|
const tasks = [];
|
||||||
|
for (let i = 1; i <= 4; i++) {
|
||||||
|
const body = {
|
||||||
|
ip: '192.168.8.241', port: 7681, httpPort: 80,
|
||||||
|
user: 'admin', pass: 'ky666888', channel: 33,
|
||||||
|
start: '2026-07-08T10:00:00', end: '2026-07-08T10:00:10',
|
||||||
|
speed: 4, outputPrefix: `batch${i}`
|
||||||
|
};
|
||||||
|
const r = await callApi('/api/hikvision/download', { method: 'POST', body });
|
||||||
|
console.log(`#${i} ${r.taskId.slice(-10)} ${r.status}`);
|
||||||
|
tasks.push(r.taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n=== 调度状态(并发上限 2) ===');
|
||||||
|
const start = Date.now();
|
||||||
|
for (let round = 0; round < 60; round++) {
|
||||||
|
await new Promise(r => setTimeout(r, 1500));
|
||||||
|
const list = await callApi('/api/hikvision/tasks?pageSize=10');
|
||||||
|
const t = ((Date.now() - start) / 1000).toFixed(0) + 's';
|
||||||
|
const statuses = (list.data?.list || []).filter(x => tasks.includes(x.task_id))
|
||||||
|
.map(x => `${x.task_id.slice(-8)}:${x.status}`).join(' | ');
|
||||||
|
console.log(`[${t}] ${statuses}`);
|
||||||
|
|
||||||
|
const running = (list.data?.list || []).filter(x => tasks.includes(x.task_id) && x.status === 'running').length;
|
||||||
|
const done = (list.data?.list || []).filter(x => tasks.includes(x.task_id) && (x.status === 'completed' || x.status === 'done')).length;
|
||||||
|
if (done === 4) { console.log('\n全部完成!'); break; }
|
||||||
|
}
|
||||||
1
test_cfg.json
Normal file
1
test_cfg.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{"ip":"192.168.8.241","port":7681,"httpPort":80,"user":"admin","pass":"ky666888","channel":33,"start":"2026-07-01T08:00:00","end":"2026-07-01T08:05:00","speed":4,"output":"G:/gameauto/recordings/output.ps"}
|
||||||
92
test_channels.mjs
Normal file
92
test_channels.mjs
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
import crypto from 'crypto';
|
||||||
|
import http from 'http';
|
||||||
|
import { DOMParser } from '@xmldom/xmldom';
|
||||||
|
|
||||||
|
const _req = (method, url, body, headers, cookieJar) => new Promise((resolve, reject) => {
|
||||||
|
const u = new URL(url);
|
||||||
|
const bodyBuf = body ? Buffer.from(typeof body === 'string' ? body : body, 'utf-8') : null;
|
||||||
|
const cookies = Object.entries(cookieJar || {}).map(([k, v]) => `${k}=${v}`).join('; ');
|
||||||
|
const hdrs = { 'Accept': '*/*', 'User-Agent': 'Mozilla/5.0', ...headers };
|
||||||
|
if (cookies) hdrs['Cookie'] = cookies;
|
||||||
|
if (bodyBuf) hdrs['Content-Length'] = bodyBuf.length;
|
||||||
|
const req = http.request({ hostname: u.hostname, port: u.port || 80, path: u.pathname + u.search, method, headers: hdrs, timeout: 10000 }, (res) => {
|
||||||
|
const ck = [];
|
||||||
|
res.on('data', c => ck.push(c));
|
||||||
|
res.on('end', () => {
|
||||||
|
req.destroy();
|
||||||
|
const body = Buffer.concat(ck).toString('utf-8');
|
||||||
|
if (res.headers['set-cookie'] && cookieJar) {
|
||||||
|
(Array.isArray(res.headers['set-cookie']) ? res.headers['set-cookie'] : [res.headers['set-cookie']]).forEach(sc => {
|
||||||
|
const m = sc.match(/^([^=;]+)=([^;]*)/); if (m) cookieJar[m[1]] = m[2];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
resolve({ statusCode: res.statusCode, headers: res.headers, body });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
req.on('error', reject);
|
||||||
|
req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
|
||||||
|
if (bodyBuf) req.write(bodyBuf);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
|
||||||
|
const ip = '192.168.8.241', httpPort = 80, user = 'admin', pass = 'ky666888';
|
||||||
|
const httpBase = `http://${ip}:${httpPort}`;
|
||||||
|
const ns = { h: 'http://www.hikvision.com/ver20/XMLSchema' };
|
||||||
|
const cookieJar = {};
|
||||||
|
|
||||||
|
// [1] Caps
|
||||||
|
const capsUrl = `${httpBase}/ISAPI/Security/sessionLogin/capabilities?username=${user}&random:12345678`;
|
||||||
|
const capsRes = await _req('GET', capsUrl, null, {}, cookieJar);
|
||||||
|
console.log('caps:', capsRes.statusCode);
|
||||||
|
const capsXml = new DOMParser().parseFromString(capsRes.body, 'text/xml');
|
||||||
|
const gt = (x) => { const el = capsXml.getElementsByTagNameNS(ns.h, x); return el?.length ? el[0].textContent : ''; };
|
||||||
|
const sid = gt('sessionID'), ch = gt('challenge'), salt = gt('salt');
|
||||||
|
const itr = parseInt(gt('iterations')) || 1, ver = gt('sessionIDVersion') || '1';
|
||||||
|
const vl = gt('isSessionIDValidLongTerm') || 'false', st = gt('isSupportSessionTag') || 'false';
|
||||||
|
const irr = gt('isIrreversible') === 'true';
|
||||||
|
|
||||||
|
// [2] Password
|
||||||
|
let digest;
|
||||||
|
if (irr) {
|
||||||
|
digest = crypto.createHash('sha256').update(user + salt + pass).digest('hex');
|
||||||
|
digest = crypto.createHash('sha256').update(digest + ch).digest('hex');
|
||||||
|
for (let i = 2; i < itr; i++) digest = crypto.createHash('sha256').update(digest).digest('hex');
|
||||||
|
} else {
|
||||||
|
digest = crypto.createHash('sha256').update(pass + ch).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>`;
|
||||||
|
}
|
||||||
|
const loginRes = await _req('POST', `${httpBase}/ISAPI/Security/sessionLogin?timeStamp=${Date.now()}`, loginXml, { 'Content-Type': 'text/plain;charset=UTF-8' }, cookieJar);
|
||||||
|
console.log('login:', loginRes.statusCode, 'set-cookie:', JSON.stringify(loginRes.headers['set-cookie']));
|
||||||
|
console.log('cookieJar:', JSON.stringify(cookieJar));
|
||||||
|
|
||||||
|
const loginParsed = new DOMParser().parseFromString(loginRes.body, 'text/xml');
|
||||||
|
const sessionTag = (() => { const el = loginParsed.getElementsByTagNameNS(ns.h, 'sessionTag'); return el?.length ? el[0].textContent : ''; })();
|
||||||
|
console.log('sessionTag:', sessionTag?.slice(0, 16) + '...');
|
||||||
|
|
||||||
|
// [4] Test channels with cookie + SessionTag
|
||||||
|
const headers = sessionTag ? { 'SessionTag': sessionTag } : {};
|
||||||
|
console.log('\n--- Request channels with headers:', JSON.stringify(headers), 'cookies:', JSON.stringify(cookieJar));
|
||||||
|
const channelsRes = await _req('GET', `${httpBase}/ISAPI/ContentMgmt/InputProxy/channels`, null, headers, cookieJar);
|
||||||
|
console.log('channels status:', channelsRes.statusCode);
|
||||||
|
console.log('channels body:', channelsRes.body.slice(0, 800));
|
||||||
|
|
||||||
|
// 测试解析
|
||||||
|
console.log('\n--- Parse test ---');
|
||||||
|
const doc = new DOMParser().parseFromString(channelsRes.body, 'text/xml');
|
||||||
|
const items = doc.getElementsByTagNameNS(ns.h, 'InputProxyChannel');
|
||||||
|
console.log('items found:', items?.length || 0);
|
||||||
|
if (items) {
|
||||||
|
for (let i = 0; i < Math.min(items.length, 5); i++) {
|
||||||
|
const el = items[i];
|
||||||
|
const t = (name) => { const n = el.getElementsByTagNameNS(ns.h, name); return n?.length ? n[0].textContent : ''; };
|
||||||
|
console.log(` [${i}] id=${t('id')} name="${t('name')}" ip="${el.getElementsByTagNameNS(ns.h, 'ipAddress')?.[0]?.textContent || ''}"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
test_frame.jpg
Normal file
BIN
test_frame.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 286 KiB |
44
test_hik_storage.mjs
Normal file
44
test_hik_storage.mjs
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
import http from 'http';
|
||||||
|
const PORT = 17311;
|
||||||
|
|
||||||
|
async function callApi(path, options = {}) {
|
||||||
|
const method = options.method || 'GET';
|
||||||
|
const body = options.body ? JSON.stringify(options.body) : null;
|
||||||
|
const headers = body ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } : {};
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const req = http.request(`http://127.0.0.1:${PORT}${path}`, { method, headers }, (res) => {
|
||||||
|
const chunks = [];
|
||||||
|
res.on('data', c => chunks.push(c));
|
||||||
|
res.on('end', () => { try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf-8'))); } catch { resolve({}); } });
|
||||||
|
});
|
||||||
|
req.on('error', reject);
|
||||||
|
if (body) req.write(body);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
ip: '192.168.8.241', port: 7681, httpPort: 80,
|
||||||
|
user: 'admin', pass: 'ky666888', channel: 33,
|
||||||
|
start: '2026-07-08T10:00:00', end: '2026-07-08T10:04:00',
|
||||||
|
speed: 4, outputPrefix: 'test_4min'
|
||||||
|
};
|
||||||
|
|
||||||
|
const dlRes = await callApi('/api/hikvision/download', { method: 'POST', body });
|
||||||
|
console.log('taskId:', dlRes.taskId, dlRes.status);
|
||||||
|
|
||||||
|
const start = Date.now();
|
||||||
|
for (let i = 0; i < 300; i++) {
|
||||||
|
await new Promise(r => setTimeout(r, 2000));
|
||||||
|
const s = await callApi(`/api/hikvision/status?taskId=${dlRes.taskId}`);
|
||||||
|
const t = ((Date.now() - start) / 1000).toFixed(0);
|
||||||
|
if (s.status === 'done' || s.status === 'completed') {
|
||||||
|
console.log(`[${t}s] ✅ ${(s.result?.size/1024/1024).toFixed(1)}MB ${s.result?.output}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (s.status === 'failed' || s.status === 'timeout') {
|
||||||
|
console.log(`[${t}s] ❌ ${s.status}: ${s.message}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
console.log(`[${t}s] ${s.status} chunks=${s.progress?.chunks || 0}`);
|
||||||
|
}
|
||||||
175
utils/cameraOsd.js
Normal file
175
utils/cameraOsd.js
Normal file
@ -0,0 +1,175 @@
|
|||||||
|
/**
|
||||||
|
* 摄像头 OSD(屏幕叠加文字)处理工具
|
||||||
|
*
|
||||||
|
* 用法:
|
||||||
|
* import { setCameraOSD } from '../utils/cameraOsd.js';
|
||||||
|
* await setCameraOSD('rtsp://admin:pass@192.168.1.100:554/stream', '通道名称');
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { createRequire } from 'module';
|
||||||
|
import { promisify } from 'util';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import os from 'os';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const { Cam } = require('onvif');
|
||||||
|
|
||||||
|
// ─── 文件日志 ───
|
||||||
|
function _logDir() {
|
||||||
|
const appData = process.env.ProgramData || path.join(process.env.SystemDrive || 'C:', 'ProgramData');
|
||||||
|
const dir = path.join(appData, 'printServer');
|
||||||
|
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
function _writeLog(level, ...args) {
|
||||||
|
const msg = args.join(' ');
|
||||||
|
console.log(`[CameraOSD] ${msg}`);
|
||||||
|
try {
|
||||||
|
const ts = new Date().toISOString().replace('T', ' ').substring(0, 19);
|
||||||
|
fs.appendFileSync(path.join(_logDir(), 'cameraOsd.log'), `[${ts}] [${level}] ${msg}\n`, 'utf-8');
|
||||||
|
} catch (_) { /* ignore */ }
|
||||||
|
}
|
||||||
|
const _log = (...a) => _writeLog('INFO', ...a);
|
||||||
|
const _err = (...a) => _writeLog('ERR', ...a);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析 RTSP URL 提取 [用户名, 密码, 主机]
|
||||||
|
* 格式: rtsp://username:password@host:port/path
|
||||||
|
*/
|
||||||
|
function extractRTSPInfo(rtspUrl) {
|
||||||
|
const match = rtspUrl.match(/^rtsp:\/\/([^:]+):(.+)@([^:/]+)/);
|
||||||
|
if (!match) {
|
||||||
|
throw new Error('RTSP URL 格式无效,期望: rtsp://用户名:密码@主机:端口/路径');
|
||||||
|
}
|
||||||
|
return { username: match[1], password: match[2], host: match[3] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 给摄像头设置 OSD 文字
|
||||||
|
* @param {string} rtspUrl - 摄像头 RTSP 地址
|
||||||
|
* @param {string} osdText - 要显示的 OSD 文字
|
||||||
|
* @returns {Promise<{ok: boolean, message: string}>}
|
||||||
|
*/
|
||||||
|
export async function setCameraOSD(rtspUrl, osdText, posX = -0.9, posY = 0.8) {
|
||||||
|
return _osdAction(rtspUrl, osdText, posX, posY, 'replace');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清空 OSD(删除全部文本 OSD,不创建新的)
|
||||||
|
*/
|
||||||
|
export async function clearCameraOSD(rtspUrl) {
|
||||||
|
return _osdAction(rtspUrl, '', 0, 0, 'clear');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OSD 核心操作
|
||||||
|
* @param {string} mode - 'replace'=删旧建新, 'append'=叠加追加, 'clear'=只删不建
|
||||||
|
*/
|
||||||
|
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);
|
||||||
|
|
||||||
|
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 {
|
||||||
|
// 转为 Promise 风格
|
||||||
|
const getOSDs = promisify(cam.getOSDs).bind(cam);
|
||||||
|
const createOSD = promisify(cam.createOSD).bind(cam);
|
||||||
|
const setOSD = promisify(cam.setOSD).bind(cam);
|
||||||
|
|
||||||
|
const token = cam.defaultProfile.videoSourceConfiguration.$.token;
|
||||||
|
_log('videoSourceConfigurationToken:', token);
|
||||||
|
|
||||||
|
// 检查是否已有文本 OSD(过滤掉时间 OSD 等非 Plain 类型)
|
||||||
|
let osdList = [];
|
||||||
|
try {
|
||||||
|
const resp = await getOSDs(token);
|
||||||
|
osdList = resp?.getOSDsResponse?.OSDs || [];
|
||||||
|
_log('已有 OSD 数量:', osdList.length, JSON.stringify(osdList));
|
||||||
|
} catch (e) {
|
||||||
|
_err('获取已有 OSD 失败:', e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 只取 Plain 类型的文本 OSD token
|
||||||
|
const textOSD = osdList.find(o => o.textString?.type === 'Plain');
|
||||||
|
const osdToken = textOSD?.$?.token;
|
||||||
|
const createOptions = {
|
||||||
|
videoSourceConfigurationToken: token,
|
||||||
|
plaintext: osdText,
|
||||||
|
position: { x: posX, y: posY }
|
||||||
|
};
|
||||||
|
|
||||||
|
if (mode === 'clear') {
|
||||||
|
// clear 模式:只删不建
|
||||||
|
_log('clear 模式,删除所有文本 OSD');
|
||||||
|
const deleteOSD = promisify(cam.deleteOSD).bind(cam);
|
||||||
|
for (const o of osdList.filter(x => x.textString?.type === 'Plain')) {
|
||||||
|
try { await deleteOSD(o.$.token); _log('已删除:', o.$.token); } catch (e) { _err('删除失败:', e.message); }
|
||||||
|
}
|
||||||
|
_log('clear 完成');
|
||||||
|
resolve({ ok: true, message: 'OSD 已清空', count: 0 });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// replace 模式:删除已有文本 OSD,再创建新的
|
||||||
|
if (osdToken) {
|
||||||
|
_log('replace 模式,删除已有文本 OSD');
|
||||||
|
const deleteOSD = promisify(cam.deleteOSD).bind(cam);
|
||||||
|
for (const o of osdList.filter(x => x.textString?.type === 'Plain')) {
|
||||||
|
try { await deleteOSD(o.$.token); _log('已删除:', o.$.token); } catch (e) { _err('删除失败:', e.message); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建新 OSD,最多重试 3 次
|
||||||
|
_log('创建新 OSD, text:', osdText, 'pos:', posX, posY);
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
try {
|
||||||
|
await createOSD(createOptions);
|
||||||
|
_log('第', i + 1, '次尝试成功');
|
||||||
|
break;
|
||||||
|
} catch (e) {
|
||||||
|
_err('第', i + 1, '次尝试失败:', e.message);
|
||||||
|
if (i === 2) throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证写入
|
||||||
|
const verifyResp = await getOSDs(token);
|
||||||
|
const verifyList = verifyResp?.getOSDsResponse?.OSDs || [];
|
||||||
|
const textOSDs = verifyList.filter(o => o.textString?.type === 'Plain');
|
||||||
|
const verifyTexts = textOSDs.map(o => o.textString?.plainText || '').join(',');
|
||||||
|
_log('验证读取 OSD: 共', textOSDs.length, '个文本, texts=[', verifyTexts, ']');
|
||||||
|
|
||||||
|
const found = textOSDs.some(o => {
|
||||||
|
const txt = String(o?.textString?.plainText ?? '');
|
||||||
|
return txt === String(osdText) || txt.includes(String(osdText));
|
||||||
|
});
|
||||||
|
if (found) {
|
||||||
|
_log('OK OSD 写入成功:', osdText);
|
||||||
|
resolve({ ok: true, message: 'OSD 设置成功: ' + osdText, count: textOSDs.length });
|
||||||
|
} else {
|
||||||
|
_err('FAIL OSD 写入失败: 期望="' + osdText + '" 实际=[' + verifyTexts + ']');
|
||||||
|
resolve({ ok: false, message: 'OSD 写入验证失败' });
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
_err('操作失败:', e.message);
|
||||||
|
resolve({ ok: false, message: `OSD 操作失败: ${e.message}` });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
342
utils/db.js
Normal file
342
utils/db.js
Normal file
@ -0,0 +1,342 @@
|
|||||||
|
/**
|
||||||
|
* SQLite 通用轻量存储工具
|
||||||
|
*
|
||||||
|
* 特性:
|
||||||
|
* - 自动创建 DB 文件在应用数据目录(开发态在项目根,打包态在 ProgramData/printServer)
|
||||||
|
* - WAL 模式,支持并发读写
|
||||||
|
* - 同步 API,简单直接
|
||||||
|
* - 表辅助器(TableHelper):insert / update / delete / find / count
|
||||||
|
*
|
||||||
|
* 用法:
|
||||||
|
* import db from '../utils/db.js';
|
||||||
|
* db.exec('CREATE TABLE IF NOT EXISTS logs (id INTEGER PRIMARY KEY AUTOINCREMENT, msg TEXT, ts INTEGER)');
|
||||||
|
* db.table('logs').insert({ msg: 'hello', ts: Date.now() });
|
||||||
|
* const rows = db.table('logs').where({ msg: 'hello' }).orderBy('ts', 'desc').limit(10).find();
|
||||||
|
*/
|
||||||
|
|
||||||
|
import Database from 'better-sqlite3';
|
||||||
|
import path from 'path';
|
||||||
|
import fs from 'fs';
|
||||||
|
import { getAppDataDir, isElectronRuntime } from './runtime.js';
|
||||||
|
|
||||||
|
let _instance = null;
|
||||||
|
|
||||||
|
class DB {
|
||||||
|
constructor() {
|
||||||
|
if (_instance) return _instance;
|
||||||
|
_instance = this;
|
||||||
|
|
||||||
|
this._db = null;
|
||||||
|
this._stmtCache = new Map();
|
||||||
|
this._open();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 生命周期 ───
|
||||||
|
|
||||||
|
_open() {
|
||||||
|
const dir = getAppDataDir();
|
||||||
|
if (!fs.existsSync(dir)) {
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
}
|
||||||
|
const dbPath = path.join(dir, 'printserver.db');
|
||||||
|
this._db = new Database(dbPath);
|
||||||
|
this._db.pragma('journal_mode = WAL');
|
||||||
|
this._db.pragma('foreign_keys = ON');
|
||||||
|
console.log('[DB] 已打开:', dbPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭数据库(进程退出前调用)
|
||||||
|
*/
|
||||||
|
close() {
|
||||||
|
if (this._db) {
|
||||||
|
this._stmtCache.clear();
|
||||||
|
this._db.close();
|
||||||
|
this._db = null;
|
||||||
|
_instance = null;
|
||||||
|
console.log('[DB] 已关闭');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取底层 better-sqlite3 实例(高级用法)
|
||||||
|
*/
|
||||||
|
raw() {
|
||||||
|
return this._db;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 原生 SQL ───
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行一条或多条 SQL(不返回行)
|
||||||
|
*/
|
||||||
|
exec(sql) {
|
||||||
|
return this._db.exec(sql);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行 INSERT / UPDATE / DELETE / DDL
|
||||||
|
* @returns {{ changes: number, lastInsertRowid: number|bigint }}
|
||||||
|
*/
|
||||||
|
run(sql, ...params) {
|
||||||
|
const stmt = this._prepare(sql);
|
||||||
|
return stmt.run(...params);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询单行
|
||||||
|
* @returns {object|undefined}
|
||||||
|
*/
|
||||||
|
get(sql, ...params) {
|
||||||
|
const stmt = this._prepare(sql);
|
||||||
|
return stmt.get(...params);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询多行
|
||||||
|
* @returns {object[]}
|
||||||
|
*/
|
||||||
|
all(sql, ...params) {
|
||||||
|
const stmt = this._prepare(sql);
|
||||||
|
return stmt.all(...params);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 迭代查询(大数据集)
|
||||||
|
*/
|
||||||
|
iterate(sql, ...params) {
|
||||||
|
const stmt = this._prepare(sql);
|
||||||
|
return stmt.iterate(...params);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 事务包装
|
||||||
|
*/
|
||||||
|
transaction(fn) {
|
||||||
|
const txn = this._db.transaction(fn);
|
||||||
|
return txn();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 表辅助器 ───
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取表辅助器,提供链式 CRUD
|
||||||
|
* @param {string} tableName
|
||||||
|
* @returns {TableHelper}
|
||||||
|
*/
|
||||||
|
table(tableName) {
|
||||||
|
return new TableHelper(this, tableName);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 内部 ───
|
||||||
|
|
||||||
|
_prepare(sql) {
|
||||||
|
let stmt = this._stmtCache.get(sql);
|
||||||
|
if (!stmt) {
|
||||||
|
stmt = this._db.prepare(sql);
|
||||||
|
this._stmtCache.set(sql, stmt);
|
||||||
|
}
|
||||||
|
return stmt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 表辅助器 ───
|
||||||
|
|
||||||
|
class TableHelper {
|
||||||
|
constructor(db, tableName) {
|
||||||
|
this._db = db;
|
||||||
|
this._table = tableName;
|
||||||
|
this._where = [];
|
||||||
|
this._whereParams = [];
|
||||||
|
this._order = '';
|
||||||
|
this._limitVal = null;
|
||||||
|
this._offsetVal = null;
|
||||||
|
this._selectCols = '*';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 等值条件:.where({ name: 'foo', status: 1 })
|
||||||
|
*/
|
||||||
|
where(conditions) {
|
||||||
|
for (const [key, value] of Object.entries(conditions)) {
|
||||||
|
this._where.push(`${key} = ?`);
|
||||||
|
this._whereParams.push(value);
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自定义条件:.whereRaw('age > ? AND name LIKE ?', 18, '%张%')
|
||||||
|
*/
|
||||||
|
whereRaw(clause, ...params) {
|
||||||
|
this._where.push(clause);
|
||||||
|
this._whereParams.push(...params);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 排序:.orderBy('id', 'desc') 或 .orderBy('name')
|
||||||
|
*/
|
||||||
|
orderBy(column, direction = 'asc') {
|
||||||
|
const dir = direction.toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
|
||||||
|
this._order = `ORDER BY ${column} ${dir}`;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 限制行数
|
||||||
|
*/
|
||||||
|
limit(n) {
|
||||||
|
this._limitVal = n;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 偏移
|
||||||
|
*/
|
||||||
|
offset(n) {
|
||||||
|
this._offsetVal = n;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指定查询列:.select('id, name')
|
||||||
|
*/
|
||||||
|
select(cols) {
|
||||||
|
this._selectCols = cols;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 查询方法 ───
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询多行
|
||||||
|
*/
|
||||||
|
find() {
|
||||||
|
const { sql, params } = this._buildSelect();
|
||||||
|
return this._db.all(sql, ...params);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询单行
|
||||||
|
*/
|
||||||
|
first() {
|
||||||
|
this._limitVal = 1;
|
||||||
|
const rows = this.find();
|
||||||
|
return rows[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计数
|
||||||
|
*/
|
||||||
|
count() {
|
||||||
|
let whereClause = '';
|
||||||
|
const params = [...this._whereParams];
|
||||||
|
if (this._where.length > 0) {
|
||||||
|
whereClause = 'WHERE ' + this._where.join(' AND ');
|
||||||
|
}
|
||||||
|
const sql = `SELECT COUNT(*) as cnt FROM ${this._table} ${whereClause}`;
|
||||||
|
const row = this._db.get(sql, ...params);
|
||||||
|
return row ? row.cnt : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否存在
|
||||||
|
*/
|
||||||
|
exists() {
|
||||||
|
return this.count() > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 写入方法 ───
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 插入一行
|
||||||
|
* @returns {{ changes: number, lastInsertRowid: number|bigint }}
|
||||||
|
*/
|
||||||
|
insert(data) {
|
||||||
|
const keys = Object.keys(data);
|
||||||
|
const values = Object.values(data);
|
||||||
|
const placeholders = keys.map(() => '?').join(', ');
|
||||||
|
const sql = `INSERT INTO ${this._table} (${keys.join(', ')}) VALUES (${placeholders})`;
|
||||||
|
return this._db.run(sql, ...values);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量插入
|
||||||
|
*/
|
||||||
|
insertMany(rows) {
|
||||||
|
if (rows.length === 0) return 0;
|
||||||
|
const keys = Object.keys(rows[0]);
|
||||||
|
const placeholders = keys.map(() => '?').join(', ');
|
||||||
|
const sql = `INSERT INTO ${this._table} (${keys.join(', ')}) VALUES (${placeholders})`;
|
||||||
|
const stmt = this._db._prepare(sql);
|
||||||
|
const insertAll = this._db.raw().transaction((items) => {
|
||||||
|
for (const row of items) {
|
||||||
|
stmt.run(...keys.map(k => row[k]));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
insertAll(rows);
|
||||||
|
return rows.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新满足条件的行
|
||||||
|
*/
|
||||||
|
update(data) {
|
||||||
|
const setClauses = Object.keys(data).map(k => `${k} = ?`);
|
||||||
|
const setParams = Object.values(data);
|
||||||
|
const whereClause = this._where.length > 0 ? 'WHERE ' + this._where.join(' AND ') : '';
|
||||||
|
const sql = `UPDATE ${this._table} SET ${setClauses.join(', ')} ${whereClause}`;
|
||||||
|
return this._db.run(sql, ...setParams, ...this._whereParams);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除满足条件的行
|
||||||
|
*/
|
||||||
|
delete() {
|
||||||
|
const whereClause = this._where.length > 0 ? 'WHERE ' + this._where.join(' AND ') : '';
|
||||||
|
const sql = `DELETE FROM ${this._table} ${whereClause}`;
|
||||||
|
return this._db.run(sql, ...this._whereParams);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* UPSERT:存在则更新,不存在则插入
|
||||||
|
* 需要表有 UNIQUE 约束
|
||||||
|
*/
|
||||||
|
upsert(data, conflictColumns) {
|
||||||
|
const keys = Object.keys(data);
|
||||||
|
const values = Object.values(data);
|
||||||
|
const placeholders = keys.map(() => '?').join(', ');
|
||||||
|
const updates = keys.map(k => `${k} = excluded.${k}`).join(', ');
|
||||||
|
const conflict = conflictColumns ? conflictColumns.join(', ') : keys[0];
|
||||||
|
const sql = `INSERT INTO ${this._table} (${keys.join(', ')}) VALUES (${placeholders})
|
||||||
|
ON CONFLICT(${conflict}) DO UPDATE SET ${updates}`;
|
||||||
|
return this._db.run(sql, ...values);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 内部 ───
|
||||||
|
|
||||||
|
_buildSelect() {
|
||||||
|
let sql = `SELECT ${this._selectCols} FROM ${this._table}`;
|
||||||
|
const params = [...this._whereParams];
|
||||||
|
|
||||||
|
if (this._where.length > 0) {
|
||||||
|
sql += ' WHERE ' + this._where.join(' AND ');
|
||||||
|
}
|
||||||
|
if (this._order) {
|
||||||
|
sql += ' ' + this._order;
|
||||||
|
}
|
||||||
|
if (this._limitVal !== null) {
|
||||||
|
sql += ' LIMIT ?';
|
||||||
|
params.push(this._limitVal);
|
||||||
|
}
|
||||||
|
if (this._offsetVal !== null) {
|
||||||
|
sql += ' OFFSET ?';
|
||||||
|
params.push(this._offsetVal);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { sql, params };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default new DB();
|
||||||
@ -14,6 +14,30 @@ export function isPackagedElectron() {
|
|||||||
return isElectronRuntime() && !process.defaultApp;
|
return isElectronRuntime() && !process.defaultApp;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断当前是否为"录制专用"模式
|
||||||
|
* - Linux/非 Windows 平台:强制录制模式(无打印能力)
|
||||||
|
* - config.mode === 'recording':显式指定录制模式
|
||||||
|
* - config.mode === 'minimal':最简模式(仅 HTTP+WS)
|
||||||
|
*/
|
||||||
|
export function isRecordingMode(config) {
|
||||||
|
// 非 Windows 平台强制录制模式
|
||||||
|
if (process.platform !== 'win32') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// Windows 平台按配置决定
|
||||||
|
const mode = (config && config.mode) || 'full';
|
||||||
|
return mode === 'recording' || mode === 'minimal';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前运行模式标签
|
||||||
|
*/
|
||||||
|
export function getRunMode(config) {
|
||||||
|
if (process.platform !== 'win32') return 'recording';
|
||||||
|
return (config && config.mode) || 'full';
|
||||||
|
}
|
||||||
|
|
||||||
export function getProjectRoot() {
|
export function getProjectRoot() {
|
||||||
return projectRoot;
|
return projectRoot;
|
||||||
}
|
}
|
||||||
@ -107,3 +131,57 @@ export function ensureWritableConfigFile() {
|
|||||||
|
|
||||||
return writableConfigPath;
|
return writableConfigPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 运行时状态文件路径(记录后端实际选中的端口等动态信息)
|
||||||
|
*/
|
||||||
|
export function getRuntimeStatePath() {
|
||||||
|
if (!isElectronRuntime()) {
|
||||||
|
return path.join(projectRoot, 'runtime.json');
|
||||||
|
}
|
||||||
|
return path.join(getAppDataDir(), 'runtime.json');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readRuntimeState() {
|
||||||
|
try {
|
||||||
|
const p = getRuntimeStatePath();
|
||||||
|
if (fs.existsSync(p)) {
|
||||||
|
return JSON.parse(fs.readFileSync(p, 'utf-8'));
|
||||||
|
}
|
||||||
|
} catch (_) { /* ignore */ }
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function writeRuntimeState(state) {
|
||||||
|
try {
|
||||||
|
const p = getRuntimeStatePath();
|
||||||
|
fs.writeFileSync(p, JSON.stringify(state, null, 2), 'utf-8');
|
||||||
|
} catch (_) { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析端口配置,支持单端口(Number)或端口数组([Number])
|
||||||
|
* @param {number|number[]} raw
|
||||||
|
* @returns {number[]}
|
||||||
|
*/
|
||||||
|
export function resolvePortCandidates(raw) {
|
||||||
|
if (Array.isArray(raw)) {
|
||||||
|
return raw.filter(p => Number.isFinite(p) && p > 0 && p < 65536);
|
||||||
|
}
|
||||||
|
if (Number.isFinite(raw) && raw > 0 && raw < 65536) {
|
||||||
|
return [raw];
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从服务构造函数参数中提取安全端口候选(兼容旧字段名与新字段名)
|
||||||
|
*/
|
||||||
|
export function extractPortCandidates(config, key, fallbackKey, defaultPorts) {
|
||||||
|
const raw = config[key] || config[fallbackKey];
|
||||||
|
const candidates = resolvePortCandidates(raw);
|
||||||
|
if (candidates.length > 0) {
|
||||||
|
return candidates;
|
||||||
|
}
|
||||||
|
return resolvePortCandidates(defaultPorts);
|
||||||
|
}
|
||||||
374
views/index.html
374
views/index.html
@ -542,6 +542,7 @@
|
|||||||
|
|
||||||
<div class="tabbar">
|
<div class="tabbar">
|
||||||
<button class="tab" :class="{ active: activeTab === 'overview' }" @click="activeTab = 'overview'">运行总览</button>
|
<button class="tab" :class="{ active: activeTab === 'overview' }" @click="activeTab = 'overview'">运行总览</button>
|
||||||
|
<button class="tab" :class="{ active: activeTab === 'playback' }" @click="activeTab = 'playback'; loadHikTasks()" v-if="recording.isRecording">录像回放</button>
|
||||||
<button class="tab" :class="{ active: activeTab === 'extension' }" @click="activeTab = 'extension'">设置</button>
|
<button class="tab" :class="{ active: activeTab === 'extension' }" @click="activeTab = 'extension'">设置</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -590,6 +591,98 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="tab-panel" v-show="activeTab === 'playback'">
|
||||||
|
<div class="main-grid">
|
||||||
|
<div class="left">
|
||||||
|
<div class="panel">
|
||||||
|
<h2 class="panel-title">海康 NVR 下载任务</h2>
|
||||||
|
<div class="list-title-row">
|
||||||
|
<div class="list-title">
|
||||||
|
存储 {{ formatBytes(hikStorageUsed) }} / {{ formatBytes(hikStorageMax) }}
|
||||||
|
</div>
|
||||||
|
<button @click="loadHikTasks" class="refresh-btn">刷新</button>
|
||||||
|
</div>
|
||||||
|
<div v-if="hikTasks.length === 0" style="color:#999;padding:16px;text-align:center;">暂无任务</div>
|
||||||
|
<div v-else style="max-height:460px;overflow-y:auto;border:1px solid #e0e0e0;border-radius:6px;">
|
||||||
|
<table style="width:100%;border-collapse:collapse;font-size:11px;">
|
||||||
|
<thead>
|
||||||
|
<tr style="background:#f5f6f8;position:sticky;top:0;z-index:1;">
|
||||||
|
<th style="padding:5px 6px;text-align:left;white-space:nowrap;border-bottom:2px solid #ddd;">任务ID</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:left;white-space:nowrap;border-bottom:2px solid #ddd;">倍速</th>
|
||||||
|
<th style="padding:5px 6px;text-align:left;min-width:100px;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: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>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="t in hikTasks" :key="t.task_id" style="border-bottom:1px solid #eee;" :style="t.status === 'running' ? {background:'#f0f7ff'} : {}">
|
||||||
|
<td style="padding:4px 6px;white-space:nowrap;font-weight:600;">{{ t.unique_code || '-' }}</td>
|
||||||
|
<td style="padding:4px 6px;white-space:nowrap;">
|
||||||
|
<span :style="{color: taskStatusColor(t.status),fontWeight:'600'}">{{ taskStatusText(t.status) }}</span>
|
||||||
|
<div v-if="t.status === 'running'" style="margin-top:2px;background:#d0e0f0;border-radius:2px;height:3px;overflow:hidden;width:48px;">
|
||||||
|
<div style="height:100%;background:linear-gradient(90deg,#0b69c7,#2f87de);width:60%;"></div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td style="padding:4px 6px;white-space:nowrap;">{{ t.ip || '-' }}<br><span style="font-size:9px;color:#888;">ch{{ t.channel }}</span></td>
|
||||||
|
<td style="padding:4px 6px;white-space:nowrap;">{{ fmtDuration(t.videoTime) }}</td>
|
||||||
|
<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>
|
||||||
|
</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;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>
|
||||||
|
<button v-if="t.status === 'failed' || t.status === 'timeout'" style="font-size:10px;padding:1px 5px;margin:1px;border-color:#c42b1c;color:#c42b1c;" @click="retryHikTask(t.task_id)">重试</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<!-- 分页控件 -->
|
||||||
|
<div v-if="hikTotal > hikPageSize" style="display:flex;align-items:center;justify-content:center;gap:8px;padding:8px 0;font-size:13px;color:#555;">
|
||||||
|
<button @click="loadHikTasks(1)" :disabled="hikPage <= 1" style="font-size:11px;padding:2px 8px;">首页</button>
|
||||||
|
<button @click="loadHikTasks(hikPage - 1)" :disabled="hikPage <= 1" style="font-size:11px;padding:2px 8px;">上一页</button>
|
||||||
|
<span>第</span>
|
||||||
|
<input type="number" v-model.number="hikJumpPage" @keyup.enter="loadHikTasks(hikJumpPage)" :min="1" :max="hikTotalPages" style="width:44px;text-align:center;font-size:12px;padding:2px 4px;border:1px solid #ccc;border-radius:3px;" />
|
||||||
|
<span>/ {{ hikTotalPages }} 页(共 {{ hikTotal }} 条)</span>
|
||||||
|
<button @click="loadHikTasks(hikJumpPage)" :disabled="!hikJumpPage || hikJumpPage < 1 || hikJumpPage > hikTotalPages" style="font-size:11px;padding:2px 8px;">跳转</button>
|
||||||
|
<button @click="loadHikTasks(hikPage + 1)" :disabled="hikPage >= hikTotalPages" style="font-size:11px;padding:2px 8px;">下一页</button>
|
||||||
|
<button @click="loadHikTasks(hikTotalPages)" :disabled="hikPage >= hikTotalPages" style="font-size:11px;padding:2px 8px;">末页</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="right" v-if="previewFile">
|
||||||
|
<div class="panel">
|
||||||
|
<h2 class="panel-title">录像预览</h2>
|
||||||
|
<div style="margin-top:8px;">
|
||||||
|
<video v-if="previewFile.downloadUrl" :src="previewFile.downloadUrl" controls
|
||||||
|
style="width:100%;max-height:360px;background:#000;border-radius:8px;"
|
||||||
|
@error="previewError = true">
|
||||||
|
</video>
|
||||||
|
<div v-if="previewError" class="error">视频加载失败</div>
|
||||||
|
<div style="margin-top:6px;font-size:13px;color:#555;">
|
||||||
|
<strong>{{ getFileName(previewFile.output_path) }}</strong><br>
|
||||||
|
<span style="font-size:11px;color:#999;">{{ formatBytes(previewFile.file_size || 0) }} · {{ previewFile.duration || 0 }}s</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="tab-panel" v-show="activeTab === 'extension'">
|
<div class="tab-panel" v-show="activeTab === 'extension'">
|
||||||
<div class="update-card">
|
<div class="update-card">
|
||||||
<h4 class="update-title">应用更新</h4>
|
<h4 class="update-title">应用更新</h4>
|
||||||
@ -613,6 +706,36 @@
|
|||||||
<button @click="openDownloadedInstaller()" :disabled="!updateState.filePath || updatingInApp">再次打开安装包</button>
|
<button @click="openDownloadedInstaller()" :disabled="!updateState.filePath || updatingInApp">再次打开安装包</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="update-card" style="margin-top: 18px;">
|
||||||
|
<h4 class="update-title">录制设置(由服务器下发)</h4>
|
||||||
|
<div class="form-row">
|
||||||
|
<label>录制状态</label>
|
||||||
|
<span :style="{ color: recording.isRecording ? '#107c10' : '#c42b1c', fontWeight: 'bold' }">{{ recording.isRecording ? '已启用' : '未启用' }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<label>存储上限</label>
|
||||||
|
<span>{{ recording.maxStorage || '-' }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<label>录制目录</label>
|
||||||
|
<span style="font-size:13px;word-break:break-all;">{{ recording.downloadDir || '-' }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="form-row" v-if="recording.remotePlayUrl">
|
||||||
|
<label>远程回放</label>
|
||||||
|
<a :href="recording.remotePlayUrl" target="_blank" style="font-size:13px;color:#0b69c7;">{{ recording.remotePlayUrl }}</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="update-card" style="margin-top: 18px;">
|
||||||
|
<h4 class="update-title">内网穿透(frpc)</h4>
|
||||||
|
<div class="form-row">
|
||||||
|
<label>穿透状态</label>
|
||||||
|
<span :style="{ color: frpcStatusColor, fontWeight: 'bold' }">{{ frpcStatusText }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<label>说明</label>
|
||||||
|
<span style="font-size:13px;color:#888;">frpc 配置由服务器下发,自动管理启停</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -633,6 +756,10 @@
|
|||||||
</div>
|
</div>
|
||||||
<button class="status-action" id="btnCheckUpdate">{{ updateChecking ? '检查中...' : '检查更新' }}</button>
|
<button class="status-action" id="btnCheckUpdate">{{ updateChecking ? '检查中...' : '检查更新' }}</button>
|
||||||
<button class="status-action restart" id="btnRestartBackend">{{ restartingBackend ? '重启中...' : '重启服务' }}</button>
|
<button class="status-action restart" id="btnRestartBackend">{{ restartingBackend ? '重启中...' : '重启服务' }}</button>
|
||||||
|
<div class="status-item" style="margin-left:auto;">
|
||||||
|
<span class="status-dot" :style="{ backgroundColor: frpcStatusColor }"></span>
|
||||||
|
<span>穿透:<strong :style="{color: frpcStatusColor}">{{ frpcStatusText }}</strong></span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -688,6 +815,35 @@
|
|||||||
'connected': { title: '已连接', color: 'green' },
|
'connected': { title: '已连接', color: 'green' },
|
||||||
'error': { title: '连接错误', color: 'red' },
|
'error': { title: '连接错误', color: 'red' },
|
||||||
},
|
},
|
||||||
|
// 海康录像回放
|
||||||
|
hikFiles: [],
|
||||||
|
hikFilePage: 1,
|
||||||
|
hikFileTotal: 0,
|
||||||
|
hikFileTotalPages: 1,
|
||||||
|
hikStorageUsed: 0,
|
||||||
|
hikStorageMax: 0,
|
||||||
|
hikStoragePercent: 0,
|
||||||
|
previewFile: null,
|
||||||
|
previewError: false,
|
||||||
|
// 海康任务
|
||||||
|
hikTasks: [],
|
||||||
|
hikPage: 1,
|
||||||
|
hikPageSize: 20,
|
||||||
|
hikTotal: 0,
|
||||||
|
hikJumpPage: 1,
|
||||||
|
// 海康配置
|
||||||
|
hikConfig: { downloadDir: '', maxStorageNum: 50, maxStorageUnit: 'GB', circularRecording: true },
|
||||||
|
hikConfigSaving: false,
|
||||||
|
hikConfigSaved: false,
|
||||||
|
// 服务器下发的录制配置(只读)
|
||||||
|
recording: {
|
||||||
|
isRecording: false,
|
||||||
|
maxStorage: '-',
|
||||||
|
downloadDir: '-',
|
||||||
|
remotePlayUrl: ''
|
||||||
|
},
|
||||||
|
// frpc 内网穿透状态
|
||||||
|
frpcStatus: 'stopped',
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
updateProgressPercent() {
|
updateProgressPercent() {
|
||||||
@ -707,6 +863,17 @@
|
|||||||
failed: '失败'
|
failed: '失败'
|
||||||
};
|
};
|
||||||
return map[this.updateState.status] || '空闲';
|
return map[this.updateState.status] || '空闲';
|
||||||
|
},
|
||||||
|
frpcStatusText() {
|
||||||
|
const map = { stopped: '未启动', starting: '启动中', running: '已连接', error: '异常' };
|
||||||
|
return map[this.frpcStatus] || this.frpcStatus;
|
||||||
|
},
|
||||||
|
frpcStatusColor() {
|
||||||
|
const map = { stopped: '#888', starting: '#f59f00', running: '#107c10', error: '#c42b1c' };
|
||||||
|
return map[this.frpcStatus] || '#888';
|
||||||
|
},
|
||||||
|
hikTotalPages() {
|
||||||
|
return Math.max(1, Math.ceil(this.hikTotal / this.hikPageSize));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
@ -726,6 +893,159 @@
|
|||||||
|
|
||||||
return `${size.toFixed(idx === 0 ? 0 : 2)} ${units[idx]}`;
|
return `${size.toFixed(idx === 0 ? 0 : 2)} ${units[idx]}`;
|
||||||
},
|
},
|
||||||
|
getFileName(filePath) {
|
||||||
|
if (!filePath) return '';
|
||||||
|
return filePath.replace(/\\/g, '/').split('/').pop() || filePath;
|
||||||
|
},
|
||||||
|
// ─── 海康录像回放 ───
|
||||||
|
loadHikFiles(page) {
|
||||||
|
page = page || 1;
|
||||||
|
var self = this;
|
||||||
|
window.printServerAPI.callApi('/api/hikvision/files?page=' + page + '&pageSize=20')
|
||||||
|
.then(function(res) {
|
||||||
|
if (res.success) {
|
||||||
|
self.hikFiles = res.data.list || [];
|
||||||
|
self.hikFilePage = res.data.page || 1;
|
||||||
|
self.hikFileTotal = res.data.total || 0;
|
||||||
|
self.hikFileTotalPages = Math.ceil(self.hikFileTotal / (res.data.pageSize || 20)) || 1;
|
||||||
|
self.hikStorageUsed = res.data.storage.used || 0;
|
||||||
|
self.hikStorageMax = res.data.storage.max || 0;
|
||||||
|
self.hikStoragePercent = res.data.storage.percent || 0;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(function(e) { console.error('加载录像列表失败:', e); });
|
||||||
|
},
|
||||||
|
loadHikTasks(page) {
|
||||||
|
var self = this;
|
||||||
|
if (typeof page === 'number') self.hikPage = page;
|
||||||
|
else page = self.hikPage;
|
||||||
|
self.hikJumpPage = page;
|
||||||
|
var url = '/api/hikvision/tasks?page=' + page + '&pageSize=' + self.hikPageSize;
|
||||||
|
window.printServerAPI.callApi(url)
|
||||||
|
.then(function(res) {
|
||||||
|
if (res.success) {
|
||||||
|
self.hikTasks = res.data.list || [];
|
||||||
|
self.hikTotal = res.data.total || 0;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(function(e) { console.error('加载任务列表失败:', e); });
|
||||||
|
// 同时刷新存储统计
|
||||||
|
window.printServerAPI.callApi('/api/hikvision/files?pageSize=1')
|
||||||
|
.then(function(res) {
|
||||||
|
if (res.success && res.data) {
|
||||||
|
self.hikStorageUsed = res.data.storage.used || 0;
|
||||||
|
self.hikStorageMax = res.data.storage.max || 0;
|
||||||
|
self.hikStoragePercent = res.data.storage.percent || 0;
|
||||||
|
}
|
||||||
|
}).catch(function(){});
|
||||||
|
},
|
||||||
|
previewHikTask(t) {
|
||||||
|
var result = t.result || {};
|
||||||
|
var outputPath = t.output || (result.output || '');
|
||||||
|
var downloadUrl = result.downloadUrl || '';
|
||||||
|
// 如果没有 downloadUrl(来自 DB 查询),构造一个
|
||||||
|
if (!downloadUrl && outputPath) {
|
||||||
|
downloadUrl = 'http://127.0.0.1:17311/api/hikvision/file?path=' + encodeURIComponent(outputPath);
|
||||||
|
}
|
||||||
|
this.previewFile = {
|
||||||
|
output_path: outputPath,
|
||||||
|
downloadUrl: downloadUrl,
|
||||||
|
file_size: result.size || 0,
|
||||||
|
duration: result.duration || 0
|
||||||
|
};
|
||||||
|
this.previewError = false;
|
||||||
|
},
|
||||||
|
retryHikTask(taskId) {
|
||||||
|
var self = this;
|
||||||
|
window.printServerAPI.callApi('/api/hikvision/retry', { method: 'POST', body: { taskId: taskId } })
|
||||||
|
.then(function(res) {
|
||||||
|
if (res.success) self.loadHikTasks();
|
||||||
|
else alert('重试失败: ' + (res.message || ''));
|
||||||
|
});
|
||||||
|
},
|
||||||
|
taskStatusText(status) {
|
||||||
|
var map = { pending: '⏳ 等待中', running: '⬇ 下载中', completed: '✅ 完成', done: '✅ 完成', failed: '❌ 失败', timeout: '⏰ 超时' };
|
||||||
|
return map[status] || status;
|
||||||
|
},
|
||||||
|
taskStatusColor(status) {
|
||||||
|
var map = { pending: '#f59f00', running: '#0b69c7', completed: '#107c10', done: '#107c10', failed: '#c42b1c', timeout: '#c42b1c' };
|
||||||
|
return map[status] || '#888';
|
||||||
|
},
|
||||||
|
fmtDuration(seconds) {
|
||||||
|
var s = parseInt(seconds) || 0;
|
||||||
|
if (s < 60) return s + 's';
|
||||||
|
var m = Math.floor(s / 60);
|
||||||
|
var sec = s % 60;
|
||||||
|
return m + ':' + (sec < 10 ? '0' : '') + sec;
|
||||||
|
},
|
||||||
|
previewHikFile(file) {
|
||||||
|
this.previewFile = file;
|
||||||
|
this.previewError = false;
|
||||||
|
},
|
||||||
|
// ─── 海康配置 ───
|
||||||
|
selectDownloadDir() {
|
||||||
|
var self = this;
|
||||||
|
window.printServerAPI.selectFolder().then(function(result) {
|
||||||
|
if (!result.canceled && result.path) {
|
||||||
|
self.hikConfig.downloadDir = result.path;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
loadHikConfig() {
|
||||||
|
var self = this;
|
||||||
|
window.printServerAPI.callApi('/api/hikvision/config')
|
||||||
|
.then(function(res) {
|
||||||
|
if (res.success && res.hikvision) {
|
||||||
|
var c = res.hikvision;
|
||||||
|
self.hikConfig.downloadDir = c.downloadDir || '';
|
||||||
|
self.hikConfig.circularRecording = c.circularRecording !== false;
|
||||||
|
// 解析 "50GB" → num=50, unit=GB
|
||||||
|
var m = String(c.maxStorage || '50GB').match(/^([\d.]+)\s*(TB|GB|MB|KB)$/i);
|
||||||
|
if (m) {
|
||||||
|
self.hikConfig.maxStorageNum = parseFloat(m[1]) || 50;
|
||||||
|
self.hikConfig.maxStorageUnit = m[2].toUpperCase();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
saveHikConfig() {
|
||||||
|
var self = this;
|
||||||
|
self.hikConfigSaving = true;
|
||||||
|
self.hikConfigSaved = false;
|
||||||
|
var payload = {
|
||||||
|
downloadDir: self.hikConfig.downloadDir,
|
||||||
|
maxStorage: String(self.hikConfig.maxStorageNum || 50) + (self.hikConfig.maxStorageUnit || 'GB'),
|
||||||
|
circularRecording: self.hikConfig.circularRecording
|
||||||
|
};
|
||||||
|
window.printServerAPI.callApi('/api/hikvision/config', {
|
||||||
|
method: 'POST',
|
||||||
|
body: payload
|
||||||
|
})
|
||||||
|
.then(function(res) {
|
||||||
|
self.hikConfigSaving = false;
|
||||||
|
if (res.success) {
|
||||||
|
self.hikConfigSaved = true;
|
||||||
|
// 用服务器返回的实际值更新本地状态
|
||||||
|
if (res.hikvision) {
|
||||||
|
var c = res.hikvision;
|
||||||
|
self.hikConfig.downloadDir = c.downloadDir || '';
|
||||||
|
self.hikConfig.circularRecording = c.circularRecording !== false;
|
||||||
|
var m2 = String(c.maxStorage || '50GB').match(/^([\d.]+)\s*(TB|GB|MB|KB)$/i);
|
||||||
|
if (m2) {
|
||||||
|
self.hikConfig.maxStorageNum = parseFloat(m2[1]) || 50;
|
||||||
|
self.hikConfig.maxStorageUnit = m2[2].toUpperCase();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setTimeout(function() { self.hikConfigSaved = false; }, 3000);
|
||||||
|
} else {
|
||||||
|
alert('保存失败: ' + (res.message || '未知错误'));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(function(e) {
|
||||||
|
self.hikConfigSaving = false;
|
||||||
|
alert('保存失败: ' + e.message);
|
||||||
|
});
|
||||||
|
},
|
||||||
loadComponents() {
|
loadComponents() {
|
||||||
window.printServerAPI.callService('printerComponent.getAll', {}).then((data) => {
|
window.printServerAPI.callService('printerComponent.getAll', {}).then((data) => {
|
||||||
console.log('获取组件列表:', data);
|
console.log('获取组件列表:', data);
|
||||||
@ -770,6 +1090,15 @@
|
|||||||
if (data.success) {
|
if (data.success) {
|
||||||
this.isBind = data.result.isBind || false;
|
this.isBind = data.result.isBind || false;
|
||||||
this.name = data.result.name || '';
|
this.name = data.result.name || '';
|
||||||
|
if (data.result.recording) {
|
||||||
|
const r = data.result.recording;
|
||||||
|
this.recording = {
|
||||||
|
isRecording: !!r.isRecording,
|
||||||
|
maxStorage: r.maxStorage || '-',
|
||||||
|
downloadDir: r.downloadDir || '-',
|
||||||
|
remotePlayUrl: r.remotePlayUrl || ''
|
||||||
|
};
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
alert(data.message || '获取绑定状态失败!');
|
alert(data.message || '获取绑定状态失败!');
|
||||||
}
|
}
|
||||||
@ -960,6 +1289,15 @@
|
|||||||
if (data.success) {
|
if (data.success) {
|
||||||
this.isBind = data.result.isBind || false;
|
this.isBind = data.result.isBind || false;
|
||||||
this.name = data.result.name || '';
|
this.name = data.result.name || '';
|
||||||
|
if (data.result.recording) {
|
||||||
|
const r = data.result.recording;
|
||||||
|
this.recording = {
|
||||||
|
isRecording: !!r.isRecording,
|
||||||
|
maxStorage: r.maxStorage || '-',
|
||||||
|
downloadDir: r.downloadDir || '-',
|
||||||
|
remotePlayUrl: r.remotePlayUrl || ''
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
@ -1032,6 +1370,27 @@
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
this._unsubFns.push(
|
||||||
|
window.printServerAPI.onEvent('setting.infoChanged', (data) => {
|
||||||
|
if (data.success && data.result) {
|
||||||
|
const r = data.result;
|
||||||
|
if (r.name !== undefined) this.name = r.name;
|
||||||
|
this.recording = {
|
||||||
|
isRecording: !!r.isRecording,
|
||||||
|
maxStorage: r.maxStorage || '-',
|
||||||
|
downloadDir: r.downloadDir || '-',
|
||||||
|
remotePlayUrl: r.remotePlayUrl || ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
this._unsubFns.push(
|
||||||
|
window.printServerAPI.onEvent('frpc.statusChange', (data) => {
|
||||||
|
if (data.success && data.result) {
|
||||||
|
this.frpcStatus = data.result.status || 'stopped';
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
@ -1062,6 +1421,13 @@
|
|||||||
this.refreshBindStatus();
|
this.refreshBindStatus();
|
||||||
this.loadComponents();
|
this.loadComponents();
|
||||||
this.loadPrinters();
|
this.loadPrinters();
|
||||||
|
this.loadHikConfig();
|
||||||
|
// 拉取 frpc 初始状态
|
||||||
|
window.printServerAPI.callService('frpc.getStatus', {}).then((data) => {
|
||||||
|
if (data.success && data.result) {
|
||||||
|
this.frpcStatus = data.result.status || 'stopped';
|
||||||
|
}
|
||||||
|
});
|
||||||
// 主动拉取远端服务器连接状态(弥补 IPC 事件早于监听注册的时序问题)
|
// 主动拉取远端服务器连接状态(弥补 IPC 事件早于监听注册的时序问题)
|
||||||
window.printServerAPI.callService('wsClient.getStatus', {}).then((data) => {
|
window.printServerAPI.callService('wsClient.getStatus', {}).then((data) => {
|
||||||
if (data.success && data.result) {
|
if (data.success && data.result) {
|
||||||
@ -1093,6 +1459,13 @@
|
|||||||
this.refreshBindStatus();
|
this.refreshBindStatus();
|
||||||
}, 10000);
|
}, 10000);
|
||||||
|
|
||||||
|
// 录像回放 Tab 快速轮询(2秒)
|
||||||
|
this._hikPollTimer = setInterval(() => {
|
||||||
|
if (this.activeTab === 'playback') {
|
||||||
|
this.loadHikTasks();
|
||||||
|
}
|
||||||
|
}, 2000);
|
||||||
|
|
||||||
// 延迟检查更新
|
// 延迟检查更新
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
this.checkUpdate(false);
|
this.checkUpdate(false);
|
||||||
@ -1126,6 +1499,7 @@
|
|||||||
this._unsubFns = [];
|
this._unsubFns = [];
|
||||||
}
|
}
|
||||||
if (this._qrTimer) { clearInterval(this._qrTimer); this._qrTimer = null; }
|
if (this._qrTimer) { clearInterval(this._qrTimer); this._qrTimer = null; }
|
||||||
|
if (this._hikPollTimer) { clearInterval(this._hikPollTimer); this._hikPollTimer = null; }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user