printServer/services/setting.js
liufumingren f56ca33a8d feat: 每NVR 3并发 + ffmpeg纯复制修复 + onvif依赖 + OSD日志
- 调度器: maxPerNvr 1→3, running追踪从Set改Map计数
- ffmpeg: 移除libx264重编码兜底, 修正-f mpegps→自动检测
- 新增 onvif 依赖用于摄像头OSD
- setting.setCameraOSD 增加入口/参数/结果日志
- wsClient 心跳更新
2026-07-31 23:31:33 +08:00

421 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import service from '../core/BaseService.js';
import configUtil from '../utils/config.js';
import { startService, uninstallService } from '../utils/windowsService.js';
function isServiceRunnerProcess() {
return process.argv.includes('--service-runner');
}
function isManagedBackendRunnerProcess() {
return process.argv.includes('--backend-runner') || process.argv.includes('--service-runner');
}
function scheduleCurrentProcessExit() {
// 给 WS 响应留出时间,再退出当前前台后端以释放端口。
setTimeout(() => {
try {
process.exit(0);
} catch (error) {
console.error('[SettingService] 退出前台后端失败:', error);
}
}, 500);
}
class SettingService extends service {
constructor() {
super();
this.info = this.info.bind(this);
this.unbind = this.unbind.bind(this);
this.register = this.register.bind(this);
this.unregister = this.unregister.bind(this);
this.updatePorts = this.updatePorts.bind(this);
this.restartBackend = this.restartBackend.bind(this);
this.setToken = this.setToken.bind(this);
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() {
const {config} = this;
const hik = config.hikvision || {};
return {
isBind: !!config.token,
name: config.name || '',
isService: !!config.isService,
wsPort: Number(config.wsPort) || 17301,
recording: {
isRecording: !!hik.isRecording,
maxStorage: hik.maxStorage || '50GB',
downloadDir: hik.downloadDir || '',
remotePlayUrl: hik.remotePlayUrl || ''
}
};
}
async updatePorts(data = {}) {
const { config, app } = this;
const nextWsPort = Number(data.wsPort);
if (!Number.isInteger(nextWsPort) || nextWsPort < 1 || nextWsPort > 65535) {
return { ok: false, message: 'WS 端口无效,范围应为 1-65535' };
}
const wsPortChanged = Number(config.wsPort) !== nextWsPort;
config.wsPort = nextWsPort;
configUtil.write(config);
app.config = config;
return {
ok: true,
message: wsPortChanged ? 'WS 端口已更新,重启后端后生效' : 'WS 端口未变化',
wsPort: nextWsPort,
wsPortChanged,
requiresBackendRestart: !!wsPortChanged
};
}
async restartBackend(data = {}) {
const { app } = this;
const targetWsPort = Number(data.wsPort) || Number(app.config?.wsPort) || 17301;
if (isManagedBackendRunnerProcess()) {
scheduleCurrentProcessExit();
return {
ok: true,
restarting: true,
wsPort: targetWsPort,
message: '后端正在重启,请稍候重连'
};
}
if (!app || typeof app.restartBackendRuntime !== 'function') {
return {
ok: false,
restarting: false,
message: '当前运行态不支持重启后端'
};
}
try {
const result = await app.restartBackendRuntime({ wsPort: targetWsPort });
return {
ok: true,
restarting: false,
wsPort: result.wsPort,
message: '后端已重启'
};
} catch (error) {
return {
ok: false,
restarting: false,
message: `后端重启失败:${error.message}`
};
}
}
// 解绑(WebSocket/HTTP 通用,无 ctx 依赖)
unbind() {
const { config, app } = this;
config.token = '';
configUtil.write(config);
app.isBind = false;
// 停止 frpc
if (app.services.frpc && typeof app.services.frpc.stop === 'function') {
app.services.frpc.stop();
}
// 解绑后主动请求新绑定码
if (app.wsClient?.status === 'connected') {
app.wsClient.send({ method: 'bind.generateCode', data: {} });
}
return { ok: true, message: '解绑成功' };
}
// WebSocket 注册服务,切换为“系统服务管理后端”的状态
async register() {
const { config } = this;
const previousIsService = !!config.isService;
try {
await startService();
} catch (error) {
config.isService = previousIsService;
configUtil.write(config);
this.app.isService = previousIsService;
return {
ok: false,
message: `系统服务注册失败:${error.message}`,
isService: previousIsService
};
}
config.isService = true;
configUtil.write(config);
this.app.isService = true;
if (!isServiceRunnerProcess()) {
scheduleCurrentProcessExit();
}
return {
ok: true,
message: isServiceRunnerProcess()
? '服务模式已启用'
: '服务模式已启用,当前前台后端将退出,由系统服务接管',
isService: true
};
}
// WebSocket 注销服务,切回“桌面壳直接拉起后端”的状态
async unregister() {
const { config } = this;
const previousIsService = !!config.isService;
if (!isServiceRunnerProcess()) {
try {
await uninstallService();
} catch (error) {
config.isService = previousIsService;
configUtil.write(config);
this.app.isService = previousIsService;
return {
ok: false,
message: `系统服务注销失败:${error.message}`,
isService: previousIsService
};
}
}
config.isService = false;
configUtil.write(config);
this.app.isService = false;
return {
ok: true,
message: isServiceRunnerProcess()
? '服务模式已关闭,桌面壳会切回本地后端启动并清理系统服务'
: '服务已注销,后端将恢复为桌面壳直接启动',
isService: false
};
}
async setToken(data) {
const { config } = this;
config.token = data.token;
config.tokenExpireTime = data.tokenExpireTime;
configUtil.write(config);
this.app.isBind = !!data.token;
//重载设置
await this.app.wsClient._checkAuth();
}
async setInfo(data) {
const { config, app } = this;
// 更新名称
config.name = data.computerInfo?.name || data.name || '';
console.log("设置打印台信息", 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);
// 服务端下发的 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) {
const allStatus = app.printerComponents.getAllStatus();
for (const item of allStatus) {
app.wsClient.send({ method: 'printerComponent.statusChange', data: item });
}
}
// 通知本地 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) {
console.log('[CameraOSD] set 收到请求:', JSON.stringify(data));
if (!data || !data.rtspUrl || !data.text) {
console.log('[CameraOSD] set 参数不完整,跳过:', { hasRtsp: !!data?.rtspUrl, hasText: !!data?.text });
return;
}
try {
console.log('[CameraOSD] set 开始执行 rtspUrl=%s text=%s x=%d y=%d', data.rtspUrl, data.text, data.x, data.y);
const { setCameraOSD } = await import('../utils/cameraOsd.js');
await setCameraOSD(data.rtspUrl, data.text, data.x, data.y);
console.log('[CameraOSD] set 执行成功');
} catch (e) {
console.error('[CameraOSD] set 执行失败:', e.message);
}
}
/**
* 服务端下发 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}` };
}
}
}
export default new SettingService();