244 lines
6.5 KiB
JavaScript
244 lines
6.5 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, '<')
|
|
.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) => ` <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));
|
|
}
|
|
|
|
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 = {}) {
|
|
const status = await getServiceStatus(options);
|
|
if (status.installed) {
|
|
return status;
|
|
}
|
|
|
|
await runWrapperCommand('install', options);
|
|
return getServiceStatus(options);
|
|
}
|
|
|
|
export async function startService(options = {}) {
|
|
const status = await ensureServiceInstalled(options);
|
|
if (status.running) {
|
|
return status;
|
|
}
|
|
|
|
await runWrapperCommand('start', options);
|
|
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);
|
|
} |