printServer/utils/windowsService.js

289 lines
7.4 KiB
JavaScript

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, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
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) => ` <argument>${escapeXml(argument)}</argument>`)
.join('\n');
return [
'<service>',
` <id>${SERVICE_ID}</id>`,
` <name>${SERVICE_NAME}</name>`,
' <description>printServer backend service</description>',
` <executable>${escapeXml(command.executable)}</executable>`,
argumentLines,
' <logmode>rotate</logmode>',
' <startmode>Automatic</startmode>',
' <stoptimeout>30sec</stoptimeout>',
` <workingdirectory>${escapeXml(command.workingDirectory)}</workingdirectory>`,
'</service>',
''
].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);
}