diff --git a/config.linux.json b/config.linux.json
new file mode 100644
index 0000000..1b367b0
--- /dev/null
+++ b/config.linux.json
@@ -0,0 +1,25 @@
+{
+ "wsPort": 17301,
+ "wsPorts": [17301, 17302, 17303],
+ "httpPort": 17311,
+ "httpPorts": [17311, 17312, 17313],
+ "logLevel": "info",
+ "printerDefault": "",
+ "maxPrintJobs": 10,
+ "isService": false,
+ "remoteWs": {
+ "url": "ws://printer.wms.gztbyc.com/ws",
+ "reconnectInterval": 3000
+ },
+ "hikvision": {
+ "downloadDir": "/home/wwwroot/hikvision_recordings",
+ "maxStorage": "500GB",
+ "circularRecording": true
+ },
+ "mode": "recording",
+ "refreshTokenExpireTime": 0,
+ "tokenExpireTime": 0,
+ "token": "",
+ "refreshToken": "",
+ "name": "linux-recorder"
+}
diff --git a/core/main.js b/core/main.js
index d30a6ba..e740c92 100644
--- a/core/main.js
+++ b/core/main.js
@@ -4,7 +4,7 @@ import PrinterComponentCore from './printerComponentCore.js';
import PrinterComponentMessageHandler from './printerComponentMessageHandler.js';
import WSClient from './wsClient.js';
import fs from 'fs';
-import { pathToFileURL } from 'url';
+import { pathToFileURL, fileURLToPath } from 'url';
import path from 'path';
import EventEmitter from 'events';
import { getResourcePath, getProjectRoot, extractPortCandidates, writeRuntimeState, isRecordingMode, getRunMode } from '../utils/runtime.js';
@@ -498,48 +498,38 @@ class Main extends EventEmitter {
/**
* 重试任务 POST /api/hikvision/retry
- * 支持 failed/timeout 重试,也支持 completed 任务重新录制
+ * 支持单任务 taskId 或批量 taskIds,支持 failed/timeout/completed 状态
*/
async _handleHikvisionRetry(res, body) {
const taskId = body && body.taskId;
- if (!taskId) {
- this._sendJson(res, 400, { success: false, message: '缺少 taskId' });
+ const taskIds = body && body.taskIds;
+ const ids = taskId ? [taskId] : (Array.isArray(taskIds) ? taskIds : []);
+ if (ids.length === 0) {
+ this._sendJson(res, 400, { success: false, message: '缺少 taskId 或 taskIds' });
return;
}
try {
- const task = this.db.get('SELECT status FROM hik_tasks WHERE task_id = ?', taskId);
- if (!task) {
- this._sendJson(res, 404, { success: false, message: '任务不存在' });
- return;
- }
- if (task.status === 'completed' || task.status === 'done') {
- // 重录已完成任务:先删除旧文件,再重置为 pending
- console.log('[Retry] 重录已完成任务:', taskId, '原状态:', task.status);
- const oldRow = this.db.get('SELECT tmp_file_path FROM hik_tasks WHERE task_id = ?', taskId);
- if (oldRow && oldRow.tmp_file_path) {
- try {
- const fp = this._resolvePath(oldRow.tmp_file_path);
- if (fp && fs.existsSync(fp)) { fs.unlinkSync(fp); console.log('[Retry] 已删除旧文件:', fp); }
- } catch (e) { console.error('[Retry] 删除旧文件失败:', e.message); }
+ let okCount = 0, skipCount = 0;
+ for (const tid of ids) {
+ const task = this.db.get('SELECT status, tmp_file_path FROM hik_tasks WHERE task_id = ?', tid);
+ if (!task) { skipCount++; continue; }
+ if (task.status === 'completed' || task.status === 'done') {
+ console.log('[Retry] 重录已完成任务:', tid);
+ if (task.tmp_file_path) {
+ try { const fp = this._resolvePath(task.tmp_file_path); if (fp && fs.existsSync(fp)) { fs.unlinkSync(fp); console.log('[Retry] 已删除旧文件:', fp); } } catch (e) {}
+ }
+ this.db.run(`UPDATE hik_tasks SET status='pending', retry=0, error_message=NULL, result=NULL, end_time=NULL, pushed=0, push_retry=0, push_next_retry_at='' WHERE task_id=?`, tid);
+ okCount++;
+ } else if (task.status === 'failed' || task.status === 'timeout') {
+ console.log('[Retry] 重试失败任务:', tid);
+ this.db.run(`UPDATE hik_tasks SET status='pending', retry=retry+1, error_message=NULL WHERE task_id=?`, tid);
+ okCount++;
+ } else {
+ skipCount++;
}
- this.db.run(
- `UPDATE hik_tasks SET status='pending', retry=0, error_message=NULL, result=NULL,
- end_time=NULL, pushed=0, push_retry=0, push_next_retry_at='' WHERE task_id=?`,
- taskId
- );
- this._scheduleHikTasks();
- this._sendJson(res, 200, { success: true, message: '已重新加入录制队列' });
- } else if (task.status === 'failed' || task.status === 'timeout') {
- console.log('[Retry] 重试失败任务:', taskId);
- this.db.run(
- `UPDATE hik_tasks SET status='pending', retry=retry+1, error_message=NULL WHERE task_id=?`,
- taskId
- );
- this._scheduleHikTasks();
- this._sendJson(res, 200, { success: true, message: '已重新加入队列' });
- } else {
- this._sendJson(res, 400, { success: false, message: '当前状态不支持重试: ' + task.status });
}
+ this._scheduleHikTasks();
+ this._sendJson(res, 200, { success: true, message: `已处理: ${okCount}个加入队列, ${skipCount}个跳过`, okCount, skipCount });
} catch (e) {
this._sendJson(res, 500, { success: false, message: e.message });
}
@@ -1824,9 +1814,9 @@ class Main extends EventEmitter {
}
return result;
};
- // 使用 pathToFileURL 修复路径解析
- console.log("import.meta.url", import.meta.url);
- const __dirname = path.dirname(decodeURIComponent(new URL(import.meta.url).pathname.replace(/^\//, '')));
+ // 使用 fileURLToPath 正确解析跨平台路径
+ const __filename = fileURLToPath(import.meta.url);
+ const __dirname = path.dirname(__filename);
this.services = await walk(path.join(__dirname, '../services'));
console.log('[WSServer] 已加载服务:', Object.keys(this.services));
}
diff --git a/core/wsServer.js b/core/wsServer.js
index c4f216c..893b0e1 100644
--- a/core/wsServer.js
+++ b/core/wsServer.js
@@ -250,9 +250,9 @@ class WSServer {
ws.send(JSON.stringify({ success: false, message: '消息解析失败' }));
return;
}
- const { method, data } = parsed;
+ const { method, data, _callId } = parsed;
if (!method) {
- ws.send(JSON.stringify({ success: false, message: 'method不能为空' }));
+ ws.send(JSON.stringify({ success: false, message: 'method不能为空', _callId }));
return;
}
// 支持多级目录结构,如 index.index.index
@@ -265,15 +265,17 @@ class WSServer {
if (typeof serviceFn === 'function') {
try {
const result = await serviceFn(data);
- ws.send(JSON.stringify({ success: true, method, result }));
+ ws.send(JSON.stringify({ success: true, method, result, _callId }));
} catch (err) {
//console.log(err);
- ws.send(JSON.stringify({ success: false, message: '服务方法执行失败: ' + err.message }));
+ ws.send(JSON.stringify({ success: false, method, message: '服务方法执行失败: ' + err.message, _callId }));
}
} else {
ws.send(JSON.stringify({
success: false,
+ method,
message: '未找到对应服务方法',
+ _callId,
debug: {
method,
methodPath,
diff --git a/printserver.db b/printserver.db
index 4a3492c..6ca026e 100644
Binary files a/printserver.db and b/printserver.db differ
diff --git a/printserver.db-shm b/printserver.db-shm
deleted file mode 100644
index 8a8c2c7..0000000
Binary files a/printserver.db-shm and /dev/null differ
diff --git a/printserver.db-wal b/printserver.db-wal
deleted file mode 100644
index a34416c..0000000
Binary files a/printserver.db-wal and /dev/null differ
diff --git a/q.mjs b/q.mjs
new file mode 100644
index 0000000..5779469
--- /dev/null
+++ b/q.mjs
@@ -0,0 +1,20 @@
+import Database from 'better-sqlite3';
+import { existsSync } from 'fs';
+const dbPath = existsSync('printserver.db') ? 'printserver.db' : '/opt/printserver/printserver.db';
+const db = new Database(dbPath);
+
+console.log('=== 成功任务(completed/done) ===');
+const done = db.prepare(`SELECT task_id,status,json_extract(task_params,'$.ip') as ip,json_extract(task_params,'$.channel') as ch,json_extract(task_params,'$.start') as st,json_extract(task_params,'$.end') as et,json_extract(task_params,'$.port') as port, result FROM hik_tasks WHERE status IN ('completed','done') ORDER BY id DESC LIMIT 10`).all();
+done.forEach(r => {
+ const res = r.result ? JSON.parse(r.result) : {};
+ console.log(` ${r.task_id.slice(-12)} | ${r.status} | ${r.ip} ch${r.ch} | ${r.st}→${r.et} | port=${r.port} | output=${res.output||'-'} | size=${res.size||0}`);
+});
+
+console.log('\n=== 失败任务(最近10条) ===');
+const failed = db.prepare(`SELECT task_id,status,json_extract(task_params,'$.ip') as ip,json_extract(task_params,'$.channel') as ch,json_extract(task_params,'$.start') as st,json_extract(task_params,'$.end') as et,json_extract(task_params,'$.port') as port, error_message, retry FROM hik_tasks WHERE status='failed' ORDER BY id DESC LIMIT 10`).all();
+failed.forEach(r => {
+ console.log(` ${r.task_id.slice(-12)} | ${r.status} | ${r.ip} ch${r.ch} | ${r.st}→${r.et} | port=${r.port} | retry=${r.retry} | ${r.error_message}`);
+});
+
+console.log(`\n总任务: ${db.prepare('SELECT count(*) as c FROM hik_tasks').get().c}`);
+db.close();
diff --git a/services/bind.js b/services/bind.js
index a546065..74f777f 100644
--- a/services/bind.js
+++ b/services/bind.js
@@ -1,8 +1,9 @@
import fs from 'fs';
import path from 'path';
+import { fileURLToPath } from 'url';
import configUtil from '../utils/config.js';
import service from '../core/BaseService.js';
-const __dirname = path.dirname(decodeURIComponent(new URL(import.meta.url).pathname.replace(/^\//, '')));
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
const configPath = path.join(__dirname, '../config.json');
class BindService extends service {
diff --git a/services/config.js b/services/config.js
index 88b0b22..89ef52b 100644
--- a/services/config.js
+++ b/services/config.js
@@ -1,7 +1,8 @@
import fs from 'fs';
import path from 'path';
+import { fileURLToPath } from 'url';
import service from '../core/BaseService.js';
-const __dirname = path.dirname(decodeURIComponent(new URL(import.meta.url).pathname.replace(/^\//, '')));
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
const configPath = path.join(__dirname, '../config.json');
class ConfigService extends service {
diff --git a/services/frpc.js b/services/frpc.js
index fe0a49c..c98fa5f 100644
--- a/services/frpc.js
+++ b/services/frpc.js
@@ -136,6 +136,7 @@ class FrpcService extends service {
this._frpcSearchPaths = [
'/usr/bin/frpc',
'/usr/local/bin/frpc',
+ '/www/server/frpc/frpc',
'/opt/frp/frpc',
path.join(root, 'frpc', exeName),
path.join(root, exeName),
diff --git a/services/hikvision.js b/services/hikvision.js
index 1ff05be..5668782 100644
--- a/services/hikvision.js
+++ b/services/hikvision.js
@@ -365,7 +365,22 @@ class HikvisionService extends BaseService {
}
async _doDownload(task, p) {
- const { ip, port, httpPort = 80, user, pass, channel = 33, start, end, speed = 4, output } = p;
+ let { ip, port, httpPort = 80, user, pass, channel = 33, start, end, speed = 4, output } = p;
+
+ // 时间格式规范化:NVR WebSocket playback 只接受 "YYYY-MM-DDTHH:MM:SS"
+ // 服务器下发可能带毫秒和时区如 "2026-07-28T22:10:32.000+08:00",需裁剪
+ const normTime = (t) => {
+ if (!t) return t;
+ const m = String(t).match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})/);
+ return m ? m[1] : t;
+ };
+ const origStart = start, origEnd = end;
+ start = normTime(start);
+ end = normTime(end);
+ if (start !== origStart || end !== origEnd) {
+ console.log(`[Hikvision] 时间已规范化: ${origStart} → ${start}, ${origEnd} → ${end}`);
+ }
+
console.log(`[Hikvision] taskId=${task.id} ${ip} ch=${channel}`);
const httpBase = `http://${ip}:${httpPort}`;
@@ -405,8 +420,23 @@ class HikvisionService extends BaseService {
} else {
loginXml = `
| + + | 任务ID | 状态 | 通道 | @@ -622,6 +635,7 @@
|---|---|---|---|
| {{ t.unique_code || '-' }} | {{ taskStatusText(t.status) }} @@ -781,6 +795,139 @@ // callService(method, data) → Promise // onEvent(method, callback) → unsubscribe function + // ─── 浏览器模式兼容层(非 Electron 环境自动启用 WebSocket 直连)─── + if (!window.printServerAPI) { + (function () { + var wsUrl = 'ws://' + location.hostname + ':17301'; + var httpBase = 'http://' + location.hostname + ':17311'; + var ws = null; + var eventListeners = {}; + var statusListeners = []; + var pendingCalls = {}; + var callId = 0; + var currentStatus = 'disconnected'; + var reconnectTimer = null; + + function setStatus(s) { + if (currentStatus === s) return; + currentStatus = s; + statusListeners.forEach(function (fn) { try { fn(s); } catch (e) {} }); + } + + function connect() { + if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) return; + setStatus('connecting'); + try { + ws = new WebSocket(wsUrl); + ws.onopen = function () { + setStatus('connected'); + console.log('[BrowserAPI] WebSocket 已连接:', wsUrl); + }; + ws.onclose = function () { + setStatus('disconnected'); + ws = null; + // 3 秒后重连 + clearTimeout(reconnectTimer); + reconnectTimer = setTimeout(connect, 3000); + }; + ws.onerror = function () { + setStatus('error'); + }; + ws.onmessage = function (evt) { + try { + var msg = JSON.parse(evt.data); + // 处理 RPC 回调 + if (msg._callId && pendingCalls[msg._callId]) { + var cb = pendingCalls[msg._callId]; + delete pendingCalls[msg._callId]; + if (msg.success === false) { + cb.reject(new Error(msg.message || '调用失败')); + } else { + cb.resolve(msg); + } + return; + } + // 处理事件推送 + if (msg.method) { + var list = eventListeners[msg.method]; + if (list) { + list.forEach(function (fn) { try { fn(msg); } catch (e) {} }); + } + } + } catch (e) { /* 非 JSON 消息忽略 */ } + }; + } catch (e) { + setStatus('error'); + clearTimeout(reconnectTimer); + reconnectTimer = setTimeout(connect, 3000); + } + } + + connect(); + + window.printServerAPI = { + callService: function (method, data) { + return new Promise(function (resolve, reject) { + if (!ws || ws.readyState !== WebSocket.OPEN) { + reject(new Error('WebSocket 未连接')); + return; + } + var id = ++callId; + pendingCalls[id] = { resolve: resolve, reject: reject }; + try { + ws.send(JSON.stringify({ method: method, data: data, _callId: id })); + } catch (e) { + delete pendingCalls[id]; + reject(e); + } + // 10 秒超时 + setTimeout(function () { + if (pendingCalls[id]) { + delete pendingCalls[id]; + reject(new Error('调用超时')); + } + }, 10000); + }); + }, + callApi: function (path, options) { + var url = httpBase + path; + var fetchOpts = { headers: { 'Content-Type': 'application/json' } }; + if (options && options.method) fetchOpts.method = options.method; + if (options && options.body) fetchOpts.body = JSON.stringify(options.body); + return fetch(url, fetchOpts).then(function (r) { return r.json(); }); + }, + onEvent: function (method, callback) { + if (!eventListeners[method]) eventListeners[method] = []; + eventListeners[method].push(callback); + return function () { + var arr = eventListeners[method]; + if (arr) { + eventListeners[method] = arr.filter(function (f) { return f !== callback; }); + } + }; + }, + onBackendStatusChange: function (callback) { + statusListeners.push(callback); + // 立即发送当前状态 + try { callback && callback(currentStatus); } catch (e) {} + return function () { + statusListeners = statusListeners.filter(function (f) { return f !== callback; }); + }; + }, + getBackendStatus: function () { + return Promise.resolve(currentStatus); + }, + getHttpPort: function () { + return Promise.resolve(17311); + }, + selectFolder: function () { + return Promise.resolve({ canceled: true }); + } + }; + console.log('[BrowserAPI] 浏览器兼容模式已启用, wsUrl=' + wsUrl); + })(); + } + new Vue({ el: '#app', data: { @@ -831,6 +978,9 @@ hikPageSize: 20, hikTotal: 0, hikJumpPage: 1, + hikStatusFilter: '', + hikSelectAll: false, + batchRetryMsg: '', // 海康配置 hikConfig: { downloadDir: '', maxStorageNum: 50, maxStorageUnit: 'GB', circularRecording: true }, hikConfigSaving: false, @@ -920,11 +1070,16 @@ if (typeof page === 'number') self.hikPage = page; else page = self.hikPage; self.hikJumpPage = page; + self.hikSelectAll = false; var url = '/api/hikvision/tasks?page=' + page + '&pageSize=' + self.hikPageSize; + if (self.hikStatusFilter) url += '&status=' + self.hikStatusFilter; window.printServerAPI.callApi(url) .then(function(res) { if (res.success) { - self.hikTasks = res.data.list || []; + var list = res.data.list || []; + // 保留已有 _checked 状态 + list.forEach(function(t) { t._checked = false; }); + self.hikTasks = list; self.hikTotal = res.data.total || 0; } }) @@ -943,9 +1098,9 @@ var result = t.result || {}; var outputPath = t.output || (result.output || ''); var downloadUrl = result.downloadUrl || ''; - // 如果没有 downloadUrl(来自 DB 查询),构造一个 + // 如果没有 downloadUrl(来自 DB 查询),构造一个(用当前页面的 host 而不是 127.0.0.1) if (!downloadUrl && outputPath) { - downloadUrl = 'http://127.0.0.1:17311/api/hikvision/file?path=' + encodeURIComponent(outputPath); + downloadUrl = location.protocol + '//' + location.host + '/api/hikvision/file?path=' + encodeURIComponent(outputPath); } this.previewFile = { output_path: outputPath, @@ -963,6 +1118,27 @@ else alert('重试失败: ' + (res.message || '')); }); }, + toggleSelectAllHikTasks() { + var val = this.hikSelectAll; + this.hikTasks.forEach(function(t) { t._checked = val; }); + }, + batchRetryHikTasks() { + var self = this; + var ids = this.hikTasks.filter(function(t) { return t._checked; }).map(function(t) { return t.task_id; }); + if (ids.length === 0) return; + if (!confirm('确定要强制重录选中的 ' + ids.length + ' 个任务吗?已完成的任务会删除旧文件重新录制。')) return; + self.batchRetryMsg = '处理中...'; + window.printServerAPI.callApi('/api/hikvision/retry', { method: 'POST', body: { taskIds: ids } }) + .then(function(res) { + self.batchRetryMsg = res.message || ('已处理 ' + ids.length + ' 个'); + setTimeout(function() { self.batchRetryMsg = ''; }, 5000); + self.loadHikTasks(); + }) + .catch(function(e) { + self.batchRetryMsg = '批量重录失败'; + console.error(e); + }); + }, taskStatusText(status) { var map = { pending: '⏳ 等待中', running: '⬇ 下载中', completed: '✅ 完成', done: '✅ 完成', failed: '❌ 失败', timeout: '⏰ 超时' }; return map[status] || status; |