diff --git a/README.md b/README.md
index 7327366..f06916e 100644
--- a/README.md
+++ b/README.md
@@ -33,8 +33,6 @@ printServer 是一个面向 Windows 的本地打印服务应用。
- 业务服务,如打印机、设置、绑定
- views/
- 页面模板,目前主要是 index.html
-- daemon/
- - 守护或服务相关配置文件
- 临时/
- 临时分析文档、测试脚本、临时日志的统一目录,可在任务结束后整体清理
@@ -65,8 +63,7 @@ npm run dev
- WebSocket 服务按 method 路由到 services/ 下对应实例方法
示例:
-- setting.register -> services/setting.js
-- setting.unregister -> services/setting.js
+- setting.info -> services/setting.js
- printer.getWindowsPrinters -> services/printer.js
## 当前打包方向
diff --git a/build.ps1 b/build.ps1
index 35193e2..44bffdd 100644
--- a/build.ps1
+++ b/build.ps1
@@ -209,10 +209,8 @@ function Invoke-SignFile([string]$TargetPath, [string]$Label) {
function Sign-AppArtifacts {
$appExePath = Join-Path $root 'dist\win-unpacked\printServer.exe'
- $serviceWrapperPath = Join-Path $root 'dist\win-unpacked\resources\daemon\printserver.exe'
Invoke-SignFile -TargetPath $appExePath -Label 'app executable'
- Invoke-SignFile -TargetPath $serviceWrapperPath -Label 'service wrapper'
}
function Sign-InstallerArtifacts {
@@ -354,7 +352,7 @@ function Ensure-PackagedResources() {
Copy-Item -Path $iconSourcePath -Destination $iconTargetPath -Force
}
- foreach ($dirName in @('daemon', 'frpc')) {
+ foreach ($dirName in @('frpc')) {
$sourcePath = Join-Path $root $dirName
$targetPath = Join-Path $resourcesDir $dirName
diff --git a/daemon/printserver.exe b/daemon/printserver.exe
deleted file mode 100644
index 507707a..0000000
Binary files a/daemon/printserver.exe and /dev/null differ
diff --git a/daemon/printserver.exe.config b/daemon/printserver.exe.config
deleted file mode 100644
index 48f571c..0000000
--- a/daemon/printserver.exe.config
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
diff --git a/daemon/printserver.xml b/daemon/printserver.xml
deleted file mode 100644
index d878566..0000000
--- a/daemon/printserver.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-
- printserver.exe
- PrintServer
- printServer backend service
- D:\printServer\node_modules\electron\dist\electron.exe
- D:\printServer
- --service-runner
- rotate
- Automatic
- 30sec
- D:\printServer
-
diff --git a/services/setting.js b/services/setting.js
index f5d5734..bd13d81 100644
--- a/services/setting.js
+++ b/services/setting.js
@@ -1,13 +1,9 @@
import service from '../core/BaseService.js';
import configUtil from '../utils/config.js';
-import { startService, uninstallService } from '../utils/windowsService.js';
-
-function isServiceRunnerProcess() {
- return process.argv.includes('--service-runner');
-}
+import { isElectronRuntime } from '../utils/runtime.js';
function isManagedBackendRunnerProcess() {
- return process.argv.includes('--backend-runner') || process.argv.includes('--service-runner');
+ return process.argv.includes('--backend-runner');
}
function scheduleCurrentProcessExit() {
@@ -26,8 +22,6 @@ class SettingService extends service {
super();
this.info = this.info.bind(this);
this.unbind = this.unbind.bind(this);
- this.register = this.register.bind(this);
- this.unregister = this.unregister.bind(this);
this.updatePorts = this.updatePorts.bind(this);
this.restartBackend = this.restartBackend.bind(this);
this.setToken = this.setToken.bind(this);
@@ -43,7 +37,6 @@ class SettingService extends service {
return {
isBind: !!config.token,
name: config.name || '',
- isService: !!config.isService,
wsPort: Number(config.wsPort) || 17301,
recording: {
isRecording: !!hik.isRecording,
@@ -81,6 +74,7 @@ class SettingService extends service {
const { app } = this;
const targetWsPort = Number(data.wsPort) || Number(app.config?.wsPort) || 17301;
+ // 托管后端子进程(打包态):退出后由桌面壳 reconcile 循环重新拉起
if (isManagedBackendRunnerProcess()) {
scheduleCurrentProcessExit();
return {
@@ -91,6 +85,42 @@ class SettingService extends service {
};
}
+ // Electron 主进程内嵌后端(开发模式):无法自我重启,重启整个桌面应用
+ if (isElectronRuntime()) {
+ if (targetWsPort !== Number(app.config?.wsPort)) {
+ app.config.wsPort = targetWsPort;
+ configUtil.write(app.config);
+ }
+ try {
+ const electron = await import('electron');
+ const electronApp = electron.app || electron.default?.app;
+ if (!electronApp || typeof electronApp.relaunch !== 'function') {
+ throw new Error('electron app 对象不可用');
+ }
+ // 给 WS 响应留出时间,再重启整个应用
+ setTimeout(() => {
+ try {
+ electronApp.relaunch();
+ electronApp.exit(0);
+ } catch (error) {
+ console.error('[SettingService] 应用重启失败:', error);
+ }
+ }, 500);
+ return {
+ ok: true,
+ restarting: true,
+ wsPort: targetWsPort,
+ message: '应用正在重启,请稍候'
+ };
+ } catch (error) {
+ return {
+ ok: false,
+ restarting: false,
+ message: `应用重启失败:${error.message}`
+ };
+ }
+ }
+
if (!app || typeof app.restartBackendRuntime !== 'function') {
return {
ok: false,
@@ -134,74 +164,8 @@ class SettingService extends service {
return { ok: true, message: '解绑成功' };
}
+ // WebSocket 注册服务,切换为“系统服务管理后端”的状态(已弃用,系统服务功能已移除)
- // WebSocket 注册服务,切换为“系统服务管理后端”的状态
- async register() {
- const { config } = this;
- const previousIsService = !!config.isService;
-
- try {
- await startService();
- } catch (error) {
- config.isService = previousIsService;
- configUtil.write(config);
- this.app.isService = previousIsService;
- return {
- ok: false,
- message: `系统服务注册失败:${error.message}`,
- isService: previousIsService
- };
- }
-
- config.isService = true;
- configUtil.write(config);
- this.app.isService = true;
-
- if (!isServiceRunnerProcess()) {
- scheduleCurrentProcessExit();
- }
-
- return {
- ok: true,
- message: isServiceRunnerProcess()
- ? '服务模式已启用'
- : '服务模式已启用,当前前台后端将退出,由系统服务接管',
- isService: true
- };
- }
-
- // WebSocket 注销服务,切回“桌面壳直接拉起后端”的状态
- async unregister() {
- const { config } = this;
- const previousIsService = !!config.isService;
-
- if (!isServiceRunnerProcess()) {
- try {
- await uninstallService();
- } catch (error) {
- config.isService = previousIsService;
- configUtil.write(config);
- this.app.isService = previousIsService;
- return {
- ok: false,
- message: `系统服务注销失败:${error.message}`,
- isService: previousIsService
- };
- }
- }
-
- config.isService = false;
- configUtil.write(config);
- this.app.isService = false;
-
- return {
- ok: true,
- message: isServiceRunnerProcess()
- ? '服务模式已关闭,桌面壳会切回本地后端启动并清理系统服务'
- : '服务已注销,后端将恢复为桌面壳直接启动',
- isService: false
- };
- }
async setToken(data) {
const { config } = this;
config.token = data.token;
diff --git a/utils/windowsService.js b/utils/windowsService.js
deleted file mode 100644
index 7422d80..0000000
--- a/utils/windowsService.js
+++ /dev/null
@@ -1,289 +0,0 @@
-import fs from 'fs';
-import path from 'path';
-import { execFile } from 'child_process';
-import { promisify } from 'util';
-import { getProjectRoot, getResourcePath, isElectronRuntime, isPackagedElectron } from './runtime.js';
-
-const execFileAsync = promisify(execFile);
-const SERVICE_NAME = 'PrintServer';
-const SERVICE_ID = 'printserver.exe';
-
-function assertWindows() {
- if (process.platform !== 'win32') {
- throw new Error('Windows 服务能力仅支持 Windows 环境');
- }
-}
-
-function escapeXml(value) {
- return String(value)
- .replace(/&/g, '&')
- .replace(//g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
-}
-
-function getServiceWrapperPath() {
- return getResourcePath('daemon', SERVICE_ID);
-}
-
-function getServiceXmlPath() {
- return getResourcePath('daemon', 'printserver.xml');
-}
-
-function getServiceWorkingDirectory() {
- if (isPackagedElectron()) {
- return path.dirname(process.execPath);
- }
-
- return getProjectRoot();
-}
-
-function getServiceCommandDefinition() {
- if (isElectronRuntime()) {
- return {
- executable: process.execPath,
- arguments: isPackagedElectron() ? ['--service-runner'] : [getProjectRoot(), '--service-runner'],
- workingDirectory: getServiceWorkingDirectory()
- };
- }
-
- return {
- executable: process.execPath,
- arguments: [path.join(getProjectRoot(), 'index.js')],
- workingDirectory: getProjectRoot()
- };
-}
-
-function buildServiceXml() {
- const command = getServiceCommandDefinition();
- const argumentLines = command.arguments
- .map((argument) => ` ${escapeXml(argument)}`)
- .join('\n');
-
- return [
- '',
- ` ${SERVICE_ID}`,
- ` ${SERVICE_NAME}`,
- ' printServer backend service',
- ` ${escapeXml(command.executable)}`,
- argumentLines,
- ' rotate',
- ' Automatic',
- ' 30sec',
- ` ${escapeXml(command.workingDirectory)}`,
- '',
- ''
- ].join('\n');
-}
-
-export function ensureServiceDefinition() {
- assertWindows();
-
- const wrapperPath = getServiceWrapperPath();
- const xmlPath = getServiceXmlPath();
-
- if (!fs.existsSync(wrapperPath)) {
- throw new Error(`服务包装器不存在: ${wrapperPath}`);
- }
-
- const expectedXml = buildServiceXml();
- const currentXml = fs.existsSync(xmlPath) ? fs.readFileSync(xmlPath, 'utf8') : '';
- if (currentXml !== expectedXml) {
- fs.writeFileSync(xmlPath, expectedXml, 'utf8');
- }
-
- return {
- name: SERVICE_NAME,
- id: SERVICE_ID,
- wrapperPath,
- xmlPath,
- workingDirectory: getServiceWorkingDirectory()
- };
-}
-
-function isAccessDeniedErrorMessage(message) {
- if (!message) {
- return false;
- }
-
- return /AccessDenied|拒绝访问|\b0x5\b|\berror\s*5\b/i.test(String(message));
-}
-
-function isServiceAlreadyExistsErrorMessage(message) {
- if (!message) {
- return false;
- }
-
- return /already exists|已存在|Service with id\s*'?.+?'?\s*already exists/i.test(String(message));
-}
-
-function isServiceAlreadyRunningErrorMessage(message) {
- if (!message) {
- return false;
- }
-
- return /already started|already running|已启动|正在运行/i.test(String(message));
-}
-
-async function runWrapperCommandElevated(command, metadata) {
- const escapedWrapperPath = metadata.wrapperPath.replace(/'/g, "''");
- const escapedCommand = String(command).replace(/'/g, "''");
- const escapedWorkingDirectory = path.dirname(metadata.wrapperPath).replace(/'/g, "''");
- const psCommand = [
- "$proc = Start-Process",
- `-FilePath '${escapedWrapperPath}'`,
- `-ArgumentList '${escapedCommand}'`,
- `-WorkingDirectory '${escapedWorkingDirectory}'`,
- '-Verb RunAs',
- '-WindowStyle Hidden',
- '-PassThru',
- '-Wait;',
- 'exit $proc.ExitCode'
- ].join(' ');
-
- try {
- await execFileAsync('powershell.exe', ['-NoProfile', '-Command', psCommand], {
- windowsHide: true
- });
- } catch (error) {
- const stdout = (error.stdout || '').trim();
- const stderr = (error.stderr || '').trim();
- const details = [stdout, stderr, error.message].filter(Boolean).join(' | ');
- throw new Error(`提权执行服务命令 ${command} 失败: ${details}`);
- }
-
- return {
- stdout: '',
- stderr: ''
- };
-}
-
-async function runWrapperCommand(command, options = {}) {
- const {
- allowElevation = true
- } = options;
- const metadata = ensureServiceDefinition();
-
- try {
- const result = await execFileAsync(metadata.wrapperPath, [command], {
- cwd: path.dirname(metadata.wrapperPath),
- windowsHide: true
- });
-
- return {
- stdout: (result.stdout || '').trim(),
- stderr: (result.stderr || '').trim()
- };
- } catch (error) {
- const stdout = (error.stdout || '').trim();
- const stderr = (error.stderr || '').trim();
- const details = [stdout, stderr, error.message].filter(Boolean).join(' | ');
-
- if (allowElevation && command !== 'status' && isAccessDeniedErrorMessage(details)) {
- try {
- return await runWrapperCommandElevated(command, metadata);
- } catch (elevatedError) {
- throw new Error(`执行服务命令 ${command} 失败: ${details} | ${elevatedError.message}`);
- }
- }
-
- throw new Error(`执行服务命令 ${command} 失败: ${details}`);
- }
-}
-
-function parseServiceStatus(rawStatus) {
- const normalized = (rawStatus || '').trim();
-
- if (!normalized || normalized === 'NonExistent') {
- return {
- installed: false,
- running: false,
- rawStatus: normalized || 'NonExistent'
- };
- }
-
- return {
- installed: true,
- running: /started|running|active/i.test(normalized),
- rawStatus: normalized
- };
-}
-
-export async function getServiceStatus(options = {}) {
- const { stdout } = await runWrapperCommand('status', options);
- return parseServiceStatus(stdout);
-}
-
-export async function ensureServiceInstalled(options = {}) {
- let status = null;
- try {
- status = await getServiceStatus(options);
- } catch (error) {
- status = null;
- }
-
- if (status && status.installed) {
- return status;
- }
-
- try {
- await runWrapperCommand('install', options);
- } catch (error) {
- if (!isServiceAlreadyExistsErrorMessage(error.message)) {
- throw error;
- }
- }
-
- try {
- return await getServiceStatus(options);
- } catch (error) {
- // 某些机器上 status 读取异常,但 install 已提示“已存在”。此时按已安装处理。
- return {
- installed: true,
- running: false,
- rawStatus: 'Existing'
- };
- }
-}
-
-export async function startService(options = {}) {
- const status = await ensureServiceInstalled(options);
- if (status.running) {
- return status;
- }
-
- try {
- await runWrapperCommand('start', options);
- } catch (error) {
- if (!isServiceAlreadyRunningErrorMessage(error.message)) {
- throw error;
- }
- }
-
- return getServiceStatus(options);
-}
-
-export async function stopService(options = {}) {
- const status = await getServiceStatus(options);
- if (!status.installed || !status.running) {
- return status;
- }
-
- await runWrapperCommand('stop', options);
- return getServiceStatus(options);
-}
-
-export async function uninstallService(options = {}) {
- const status = await getServiceStatus(options);
- if (!status.installed) {
- return status;
- }
-
- if (status.running) {
- await runWrapperCommand('stop', options);
- }
-
- await runWrapperCommand('uninstall', options);
- return getServiceStatus(options);
-}
\ No newline at end of file
diff --git a/views/index_new.html b/views/index_new.html
index 7849cce..dd85b1f 100644
--- a/views/index_new.html
+++ b/views/index_new.html
@@ -227,10 +227,6 @@
本地服务:
{{ wsStatus[wsClientStatus].title }}
-
- 服务注册:
- {{ isServices ? '已注册' : '未注册' }}
-
服务器连接:
{{ wsStatus[wsServerStatus].title }}
@@ -350,8 +346,7 @@ new Vue({
'disconnected': { title: '未连接', color: 'red' },
'connected': { title: '已连接', color: 'green' },
'error': { title: '连接错误', color: 'red' },
- },
- isServices: false
+ }
},
methods: {
loadComponents() {
@@ -387,20 +382,6 @@ new Vue({
}
});
},
- register() {
- wsSendWithCallback('setting.register', {}, (data) => {
- if (data.success) {
- this.isServices = data.result || '';
- }
- });
- },
- unregister() {
- wsSendWithCallback('setting.unregister', {}, (data) => {
- if (data.success) {
- this.isServices = data.result || '';
- }
- });
- },
isBind() {
wsSendWithCallback('setting.info', {}, (data) => {
if (data.success) {