1
This commit is contained in:
parent
4e9135c9f4
commit
35fefaeddf
25
config.linux.json
Normal file
25
config.linux.json
Normal file
@ -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"
|
||||
}
|
||||
66
core/main.js
66
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));
|
||||
}
|
||||
|
||||
@ -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,
|
||||
|
||||
BIN
printserver.db
BIN
printserver.db
Binary file not shown.
Binary file not shown.
Binary file not shown.
20
q.mjs
Normal file
20
q.mjs
Normal file
@ -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();
|
||||
@ -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 {
|
||||
|
||||
@ -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 {
|
||||
|
||||
@ -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),
|
||||
|
||||
@ -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 = `<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}`);
|
||||
console.log('[Hikvision][DEBUG] login XML: %s', loginXml);
|
||||
// 登录重试:403 表示会话冲突,延迟重试一次
|
||||
let loginRes, loginRetry = 0;
|
||||
do {
|
||||
loginRes = await this._req('POST', `${httpBase}/ISAPI/Security/sessionLogin?timeStamp=${Date.now()}`, loginXml, { 'Content-Type': 'text/plain;charset=UTF-8' }, cookieJar);
|
||||
console.log('[Hikvision][DEBUG] login response status=%d body(前200): %s (retry=%d)', loginRes.statusCode, (loginRes.body||'').substring(0,200), loginRetry);
|
||||
if (loginRes.statusCode === 403 && loginRetry < 2) {
|
||||
console.log('[Hikvision][DEBUG] login 403, 延迟重试...');
|
||||
await new Promise(r => setTimeout(r, 1500));
|
||||
loginRetry++;
|
||||
// 清除旧 cookie 后重试
|
||||
for (const k of Object.keys(cookieJar)) delete cookieJar[k];
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} while (true);
|
||||
if (loginRes.statusCode !== 200 || !loginRes.body) throw new Error(`登录失败: ${loginRes.statusCode}`);
|
||||
|
||||
const loginParsed = new DOMParser().parseFromString(loginRes.body, 'text/xml');
|
||||
const sessionTagEl = loginParsed.getElementsByTagNameNS(NS.h, 'sessionTag');
|
||||
@ -455,7 +485,10 @@ class HikvisionService extends BaseService {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
transcoded = ffRun(`-i "${workFile}" -c:v copy -an "${mp4Path}"`, 60000);
|
||||
// 海康 WS playback 输出的是 PS/TS 格式,需要指定输入格式+bitstream filter
|
||||
// -f mpegts 强制按 TS 解析,-bsf:v h264_mp4toannexb 转换 AnnexB → MP4 格式
|
||||
transcoded = ffRun(`-f mpegts -i "${workFile}" -c:v copy -bsf:v h264_mp4toannexb -an "${mp4Path}"`, 60000);
|
||||
if (!transcoded) transcoded = ffRun(`-f mpegps -i "${workFile}" -c:v copy -bsf:v h264_mp4toannexb -an "${mp4Path}"`, 60000);
|
||||
if (!transcoded) transcoded = ffRun(`-i "${workFile}" -c:v libx264 -preset fast -crf 23 -an "${mp4Path}"`, 120000);
|
||||
if (transcoded) {
|
||||
const mp4Size = fs.statSync(mp4Path).size;
|
||||
@ -488,6 +521,7 @@ class HikvisionService extends BaseService {
|
||||
`Host: ${ip}:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
|
||||
`Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: ${wsKey}\r\n` +
|
||||
`Origin: http://127.0.0.1\r\nUser-Agent: Mozilla/5.0\r\n\r\n`;
|
||||
console.log('[Hikvision][DEBUG] WS握手请求(下载):\n%s', handshake.replace(/Sec-WebSocket-Key: \S+/, 'Sec-WebSocket-Key: ***'));
|
||||
|
||||
const socket = new net.Socket();
|
||||
socket.setTimeout(120000);
|
||||
@ -559,14 +593,18 @@ class HikvisionService extends BaseService {
|
||||
(async () => {
|
||||
try {
|
||||
// ===== 步骤 1: 握手 =====
|
||||
console.log('[Hikvision][DEBUG] WS握手已发送, 等待响应... ip=%s port=%d token_len=%d', ip, port, token.length);
|
||||
// 等待 \r\n\r\n 出现(和 Python 的 while + recv(4096) 一样)
|
||||
while (buf.indexOf('\r\n\r\n') === -1) await new Promise(r => { waiter = r; });
|
||||
// 丢弃握手响应数据
|
||||
const he = buf.indexOf('\r\n\r\n');
|
||||
const respHeader = buf.slice(0, he).toString();
|
||||
console.log('[Hikvision][DEBUG] WS握手响应: %s', respHeader.split('\r\n')[0] || respHeader.substring(0,80));
|
||||
buf = buf.slice(he + 4);
|
||||
|
||||
// ===== 步骤 2: 发 playback 命令 =====
|
||||
const cmd = { sequence: 0, cmd: 'playback', url: `live://${ip}:${port}/${channel}/0`, startTime: start, endTime: end };
|
||||
console.log('[Hikvision][DEBUG] 发送playback: %s', JSON.stringify(cmd));
|
||||
wsSend(JSON.stringify(cmd), 0x01);
|
||||
|
||||
// ===== 步骤 3: 主循环,和 Python 完全一致 =====
|
||||
@ -721,6 +759,12 @@ class HikvisionService extends BaseService {
|
||||
const hdrs = { 'Accept': '*/*', 'User-Agent': 'Mozilla/5.0', ...headers };
|
||||
if (cookies) hdrs['Cookie'] = cookies;
|
||||
if (bodyBuf) hdrs['Content-Length'] = bodyBuf.length;
|
||||
// 日志:只对敏感路径打印请求信息
|
||||
if (u.pathname.includes('sessionLogin') || u.pathname.includes('token')) {
|
||||
console.log('[Hikvision][DEBUG] _req %s %s%s headers=%s body_len=%d',
|
||||
method, u.hostname, u.pathname,
|
||||
JSON.stringify(Object.keys(hdrs)), (bodyBuf||'').length);
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const mod = u.protocol === 'https:' ? https : http;
|
||||
@ -737,6 +781,11 @@ class HikvisionService extends BaseService {
|
||||
});
|
||||
}
|
||||
resolve({ statusCode: res.statusCode, headers: res.headers, body });
|
||||
if (u.pathname.includes('sessionLogin') || u.pathname.includes('token')) {
|
||||
console.log('[Hikvision][DEBUG] _req RESP %d len=%d type=%s',
|
||||
res.statusCode, body.length,
|
||||
res.headers['content-type'] || 'unknown');
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
|
||||
184
views/index.html
184
views/index.html
@ -596,17 +596,30 @@
|
||||
<div class="left">
|
||||
<div class="panel">
|
||||
<h2 class="panel-title">海康 NVR 下载任务</h2>
|
||||
<div class="list-title-row">
|
||||
<div class="list-title-row" style="flex-wrap:wrap;gap:6px;">
|
||||
<div class="list-title">
|
||||
存储 {{ formatBytes(hikStorageUsed) }} / {{ formatBytes(hikStorageMax) }}
|
||||
</div>
|
||||
<select v-model="hikStatusFilter" @change="loadHikTasks(1)" style="font-size:11px;padding:2px 6px;border:1px solid #ccc;border-radius:3px;background:#fff;">
|
||||
<option value="">全部状态</option>
|
||||
<option value="pending">待处理</option>
|
||||
<option value="running">录制中</option>
|
||||
<option value="completed">已完成</option>
|
||||
<option value="failed">失败</option>
|
||||
<option value="timeout">超时</option>
|
||||
</select>
|
||||
<button @click="loadHikTasks" class="refresh-btn">刷新</button>
|
||||
<button @click="batchRetryHikTasks" class="refresh-btn" style="border-color:#f59f00;color:#f59f00;background:#fff8f0;" :disabled="!hikTasks.some(function(t){return t._checked})">批量强制重录</button>
|
||||
<span v-if="batchRetryMsg" style="font-size:11px;color:#107c10;">{{ batchRetryMsg }}</span>
|
||||
</div>
|
||||
<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 4px;text-align:center;border-bottom:2px solid #ddd;width:28px;">
|
||||
<input type="checkbox" v-model="hikSelectAll" @change="toggleSelectAllHikTasks">
|
||||
</th>
|
||||
<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>
|
||||
@ -622,6 +635,7 @@
|
||||
</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;text-align:center;"><input type="checkbox" v-model="t._checked"></td>
|
||||
<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>
|
||||
@ -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;
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user