printServer/services/update.js
2026-03-29 19:32:28 +08:00

545 lines
15 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 fs from 'fs';
import path from 'path';
import http from 'http';
import https from 'https';
import crypto from 'crypto';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { ensureDirectory, getAppDataDir, getProjectRoot } from '../utils/runtime.js';
const execFileAsync = promisify(execFile);
const DEFAULT_FEED_URL = 'https://wms.wms.gztbyc.com/printServer/latest.json';
function parseVersionFromFileName(fileName) {
if (!fileName) {
return '';
}
const matched = String(fileName).match(/(\d+\.\d+\.\d+)/);
return matched ? matched[1] : '';
}
function normalizeVersion(version) {
return String(version || '')
.trim()
.replace(/^v/i, '')
.split('.')
.map((part) => {
const num = Number(part.replace(/\D.*$/, ''));
return Number.isFinite(num) && num >= 0 ? num : 0;
});
}
function compareVersion(a, b) {
const va = normalizeVersion(a);
const vb = normalizeVersion(b);
const length = Math.max(va.length, vb.length, 3);
for (let i = 0; i < length; i += 1) {
const left = va[i] || 0;
const right = vb[i] || 0;
if (left > right) {
return 1;
}
if (left < right) {
return -1;
}
}
return 0;
}
function resolveCurrentVersion() {
const candidates = [
path.join(getProjectRoot(), 'package.json'),
process.resourcesPath ? path.join(process.resourcesPath, 'app.asar', 'package.json') : '',
process.resourcesPath ? path.join(process.resourcesPath, 'app', 'package.json') : ''
].filter(Boolean);
for (const packagePath of candidates) {
try {
if (!fs.existsSync(packagePath)) {
continue;
}
const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
if (pkg && pkg.version) {
return String(pkg.version);
}
} catch (error) {
// Try next candidate path.
}
}
return '0.0.0';
}
function requestJson(feedUrl, timeoutMs = 8000) {
return new Promise((resolve, reject) => {
let parsedUrl;
try {
parsedUrl = new URL(feedUrl);
} catch (error) {
reject(new Error(`更新地址无效: ${feedUrl}`));
return;
}
const isHttps = parsedUrl.protocol === 'https:';
const client = isHttps ? https : http;
const options = {
method: 'GET',
timeout: timeoutMs,
headers: {
Accept: 'application/json'
}
};
const req = client.request(parsedUrl, options, (res) => {
let raw = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
raw += chunk;
});
res.on('end', () => {
if (res.statusCode < 200 || res.statusCode >= 300) {
reject(new Error(`更新清单请求失败: HTTP ${res.statusCode}`));
return;
}
try {
const normalizedRaw = raw.replace(/^\uFEFF/, '').trim();
resolve(JSON.parse(normalizedRaw));
} catch (error) {
reject(new Error('更新清单 JSON 格式无效'));
}
});
});
req.on('timeout', () => {
req.destroy(new Error('更新清单请求超时'));
});
req.on('error', (error) => {
reject(error);
});
req.end();
});
}
async function fetchFeedJson(feedUrl) {
try {
return await requestJson(feedUrl, 8000);
} catch (error) {
const urlObj = new URL(feedUrl);
if (urlObj.protocol === 'https:') {
// 某些 Windows 环境下 Node TLS 校验会失败,回退到 HTTP 读取更新清单。
const fallbackUrl = `http://${urlObj.host}${urlObj.pathname}${urlObj.search}`;
return requestJson(fallbackUrl, 8000);
}
throw error;
}
}
function buildDownloadUrl(feedUrl, feedJson, config) {
if (feedJson.url) {
return String(feedJson.url);
}
const fileName = String(feedJson.file || '').trim();
if (!fileName) {
return '';
}
const baseUrl = String(config?.update?.downloadBaseUrl || '').trim();
if (baseUrl) {
return `${baseUrl.replace(/\/$/, '')}/${fileName}`;
}
const urlObj = new URL(feedUrl);
const basePath = urlObj.pathname.replace(/\/[^/]*$/, '');
urlObj.pathname = `${basePath}/${fileName}`.replace(/\/+/g, '/');
urlObj.search = '';
urlObj.hash = '';
return urlObj.toString();
}
class UpdateService extends service {
constructor() {
super();
this.check = this.check.bind(this);
this.getDownloadState = this.getDownloadState.bind(this);
this.downloadAndInstall = this.downloadAndInstall.bind(this);
this.openDownloadedInstaller = this.openDownloadedInstaller.bind(this);
this._downloadState = {
status: 'idle',
percent: 0,
downloadedBytes: 0,
totalBytes: 0,
message: '',
downloadUrl: '',
filePath: '',
latestVersion: '',
currentVersion: resolveCurrentVersion(),
startedAt: '',
updatedAt: new Date().toISOString()
};
this._activeDownload = null;
}
_emitDownloadState(patch = {}) {
this._downloadState = {
...this._downloadState,
...patch,
updatedAt: new Date().toISOString()
};
this.app.emit('updateDownloadProgress', this._downloadState);
}
_safeFileName(fileName) {
const cleaned = String(fileName || '').replace(/[\\/:*?"<>|]/g, '_').trim();
return cleaned || `printServer-${Date.now()}-setup.exe`;
}
_requestDownloadStream(downloadUrl, redirectCount = 0) {
return new Promise((resolve, reject) => {
const maxRedirects = 5;
const parsed = new URL(downloadUrl);
const client = parsed.protocol === 'https:' ? https : http;
const request = client.get(parsed, { timeout: 12000 }, (response) => {
const status = Number(response.statusCode || 0);
if (status >= 300 && status < 400 && response.headers.location) {
if (redirectCount >= maxRedirects) {
reject(new Error('下载重定向次数过多'));
return;
}
const nextUrl = new URL(response.headers.location, parsed).toString();
response.resume();
resolve(this._requestDownloadStream(nextUrl, redirectCount + 1));
return;
}
if (status < 200 || status >= 300) {
response.resume();
reject(new Error(`下载失败: HTTP ${status}`));
return;
}
resolve({
response,
finalUrl: parsed.toString()
});
});
request.on('timeout', () => {
request.destroy(new Error('下载超时'));
});
request.on('error', (error) => {
if (parsed.protocol === 'https:') {
const fallbackUrl = `http://${parsed.host}${parsed.pathname}${parsed.search}`;
this._requestDownloadStream(fallbackUrl, redirectCount)
.then(resolve)
.catch(reject);
return;
}
reject(error);
});
});
}
async _downloadInstaller(downloadUrl, targetPath, onProgress) {
const { response, finalUrl } = await this._requestDownloadStream(downloadUrl);
const totalBytes = Number(response.headers['content-length'] || 0) || 0;
let downloadedBytes = 0;
const fileHash = crypto.createHash('sha256');
await new Promise((resolve, reject) => {
const dirPath = path.dirname(targetPath);
ensureDirectory(dirPath);
const tempPath = `${targetPath}.part`;
const writer = fs.createWriteStream(tempPath);
const fail = (error) => {
try {
writer.destroy();
} catch (e) {
// Ignore cleanup error.
}
try {
if (fs.existsSync(tempPath)) {
fs.unlinkSync(tempPath);
}
} catch (e) {
// Ignore cleanup error.
}
reject(error);
};
writer.on('error', fail);
response.on('error', fail);
response.on('data', (chunk) => {
downloadedBytes += chunk.length;
fileHash.update(chunk);
const percent = totalBytes > 0
? Math.min(100, Math.round((downloadedBytes / totalBytes) * 100))
: null;
onProgress({
status: 'downloading',
downloadedBytes,
totalBytes,
percent,
message: totalBytes > 0
? `正在下载更新包(${percent}%)`
: '正在下载更新包'
});
});
writer.on('finish', () => {
writer.close(() => {
fs.rename(tempPath, targetPath, (renameError) => {
if (renameError) {
fail(renameError);
return;
}
resolve();
});
});
});
response.pipe(writer);
});
return {
finalUrl,
downloadedBytes,
totalBytes,
sha256: fileHash.digest('hex').toUpperCase()
};
}
_launchInstaller(installerPath) {
if (!installerPath || !fs.existsSync(installerPath)) {
throw new Error('安装包不存在,无法启动安装向导');
}
if (process.platform !== 'win32') {
throw new Error('当前系统不支持自动启动安装程序');
}
if (process.argv.includes('--service-runner')) {
throw new Error('服务模式无法弹出安装向导,请在前台模式下重试');
}
if (this.app?.config?.isService) {
throw new Error('当前处于服务模式,无法直接弹出安装向导,请先注销服务后再更新');
}
const escapedPath = installerPath.replace(/'/g, "''");
const psArgs = [
'-NoProfile',
'-Command',
`Start-Process -FilePath '${escapedPath}' -Verb RunAs -ErrorAction Stop | Out-Null`
];
return execFileAsync('powershell.exe', psArgs, {
windowsHide: false
}).catch((error) => {
const details = [error.stdout, error.stderr, error.message]
.filter(Boolean)
.join(' | ');
throw new Error(details || '启动安装向导失败');
});
}
getDownloadState() {
return {
ok: true,
...this._downloadState
};
}
async openDownloadedInstaller(data = {}) {
const requestedPath = String(data.filePath || '').trim();
const installerPath = requestedPath || this._downloadState.filePath;
if (!installerPath) {
return {
ok: false,
message: '未找到已下载安装包'
};
}
try {
await this._launchInstaller(installerPath);
this._emitDownloadState({
status: 'installing',
message: '安装程序已启动,请在安装向导中完成升级'
});
return {
ok: true,
message: '安装程序已启动',
filePath: installerPath
};
} catch (error) {
this._emitDownloadState({
status: 'failed',
message: `启动安装失败:${error.message}`
});
return {
ok: false,
message: `启动安装失败:${error.message}`,
filePath: installerPath
};
}
}
async check(data = {}) {
const configFeedUrl = this.config?.update?.feedUrl;
const feedUrl = String(data.feedUrl || configFeedUrl || DEFAULT_FEED_URL).trim();
const currentVersion = resolveCurrentVersion();
try {
const feedJson = await fetchFeedJson(feedUrl);
const latestVersion = String(feedJson.version || parseVersionFromFileName(feedJson.file || '')).trim();
if (!latestVersion) {
throw new Error('更新清单缺少 version/file 字段');
}
const downloadUrl = buildDownloadUrl(feedUrl, feedJson, this.config);
const hasUpdate = compareVersion(latestVersion, currentVersion) > 0;
return {
ok: true,
hasUpdate,
currentVersion,
latestVersion,
downloadUrl,
file: String(feedJson.file || ''),
sha256: String(feedJson.sha256 || ''),
checkedAt: new Date().toISOString()
};
} catch (error) {
return {
ok: false,
hasUpdate: false,
currentVersion,
latestVersion: currentVersion,
downloadUrl: '',
message: `检查更新失败:${error.message}`
};
}
}
async downloadAndInstall(data = {}) {
if (this._activeDownload) {
return {
ok: false,
message: '已有更新任务正在执行,请稍候',
state: this._downloadState
};
}
const checkResult = await this.check({});
const currentVersion = checkResult.currentVersion || resolveCurrentVersion();
const latestVersion = String(data.version || checkResult.latestVersion || currentVersion).trim();
const requestedUrl = String(data.downloadUrl || checkResult.downloadUrl || '').trim();
if (!requestedUrl) {
return {
ok: false,
message: '未获取到更新下载地址'
};
}
const fileNameFromUrl = (() => {
try {
return path.basename(new URL(requestedUrl).pathname || '');
} catch (error) {
return '';
}
})();
const fileName = this._safeFileName(fileNameFromUrl || `printServer-${latestVersion || Date.now()}-setup.exe`);
const updateDir = ensureDirectory(path.join(getAppDataDir(), 'updates'));
const targetPath = path.join(updateDir, fileName);
this._emitDownloadState({
status: 'starting',
percent: 0,
downloadedBytes: 0,
totalBytes: 0,
message: '开始下载更新包',
downloadUrl: requestedUrl,
filePath: targetPath,
latestVersion,
currentVersion,
startedAt: new Date().toISOString()
});
this._activeDownload = (async () => {
try {
const downloadResult = await this._downloadInstaller(requestedUrl, targetPath, (progress) => {
this._emitDownloadState(progress);
});
this._emitDownloadState({
status: 'downloaded',
percent: 100,
downloadedBytes: downloadResult.downloadedBytes,
totalBytes: downloadResult.totalBytes,
message: '更新包下载完成,正在启动安装程序',
filePath: targetPath,
sha256: downloadResult.sha256
});
await this._launchInstaller(targetPath);
this._emitDownloadState({
status: 'installing',
percent: 100,
message: '安装程序已启动,请在安装向导中完成升级'
});
return {
ok: true,
message: '安装程序已启动',
filePath: targetPath,
latestVersion,
sha256: downloadResult.sha256
};
} catch (error) {
this._emitDownloadState({
status: 'failed',
message: `更新失败:${error.message}`
});
return {
ok: false,
message: `更新失败:${error.message}`
};
} finally {
this._activeDownload = null;
}
})();
return {
ok: true,
message: '已开始下载更新包',
latestVersion,
filePath: targetPath
};
}
}
export default new UpdateService();