mirror of
https://github.com/NapNeko/NapCatQQ.git
synced 2026-01-09 21:09:14 +08:00
Refactor update logging to use logger interface
Replaces all console logging in the update process with the ILogWrapper logger interface for consistent logging. Updates applyPendingUpdates to require a logger parameter and propagates this change to all relevant initialization code. Also removes duplicate and unnecessary lines in workflow YAML files.
This commit is contained in:
parent
8eb1aa2fb4
commit
68c8b984ad
1
.github/workflows/pr-build.yml
vendored
1
.github/workflows/pr-build.yml
vendored
@ -199,7 +199,6 @@ jobs:
|
||||
status: ${{ steps.build.outcome }} # 构建结果:success/failure
|
||||
error: ${{ steps.build.outputs.error }} # 错误信息(如有)
|
||||
version: ${{ steps.version.outputs.version }} # 构建版本号
|
||||
version: ${{ steps.version.outputs.version }} # 构建版本号
|
||||
steps:
|
||||
# 【安全】先从 base 分支 checkout 构建脚本
|
||||
- name: Checkout scripts from base
|
||||
|
||||
2
.github/workflows/release.yml
vendored
2
.github/workflows/release.yml
vendored
@ -6,8 +6,6 @@ on:
|
||||
tags:
|
||||
- 'v[0-9]*.[0-9]*.[0-9]*'
|
||||
- 'v[0-9]*.[0-9]*.[0-9]*-*'
|
||||
- 'v[0-9]*.[0-9]*.[0-9]*+*'
|
||||
- 'v[0-9]*.[0-9]*.[0-9]*-*+*'
|
||||
|
||||
permissions: write-all
|
||||
|
||||
|
||||
@ -34,8 +34,9 @@ export async function NCoreInitFramework (
|
||||
});
|
||||
|
||||
const pathWrapper = new NapCatPathWrapper();
|
||||
await applyPendingUpdates(pathWrapper);
|
||||
|
||||
const logger = new LogWrapper(pathWrapper.logsPath);
|
||||
await applyPendingUpdates(pathWrapper, logger);
|
||||
const basicInfoWrapper = new QQBasicInfoWrapper({ logger });
|
||||
const wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVersion());
|
||||
const nativePacketHandler = new NativePacketHandler({ logger }); // 初始化 NativePacketHandler 用于后续使用
|
||||
|
||||
@ -319,7 +319,7 @@ export async function NCoreInitShell () {
|
||||
const pathWrapper = new NapCatPathWrapper();
|
||||
const logger = new LogWrapper(pathWrapper.logsPath);
|
||||
handleUncaughtExceptions(logger);
|
||||
await applyPendingUpdates(pathWrapper);
|
||||
await applyPendingUpdates(pathWrapper, logger);
|
||||
|
||||
// 初始化 FFmpeg 服务
|
||||
await FFmpegService.init(pathWrapper.binaryPath, logger);
|
||||
|
||||
@ -42,6 +42,7 @@ export let WebUiConfig: WebUiConfigWrapper;
|
||||
export let webUiPathWrapper: NapCatPathWrapper;
|
||||
export let logSubscription: ISubscription;
|
||||
export let statusHelperSubscription: IStatusHelperSubscription;
|
||||
export let webUiLogger: ILogWrapper | null = null;
|
||||
const MAX_PORT_TRY = 100;
|
||||
|
||||
export let webUiRuntimePort = 6099;
|
||||
@ -100,6 +101,7 @@ export async function InitWebUi (logger: ILogWrapper, pathWrapper: NapCatPathWra
|
||||
webUiPathWrapper = pathWrapper;
|
||||
logSubscription = Subscription;
|
||||
statusHelperSubscription = statusSubscription;
|
||||
webUiLogger = logger;
|
||||
WebUiConfig = new WebUiConfigWrapper();
|
||||
let config = await WebUiConfig.GetWebUIConfig();
|
||||
|
||||
|
||||
@ -4,7 +4,7 @@ import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as https from 'https';
|
||||
import compressing from 'compressing';
|
||||
import { webUiPathWrapper } from '../../index';
|
||||
import { webUiPathWrapper, webUiLogger } from '../../index';
|
||||
import { NapCatPathWrapper } from '@/napcat-common/src/path';
|
||||
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
|
||||
import { NapCatCoreWorkingEnv } from '@/napcat-webui-backend/src/types';
|
||||
@ -12,6 +12,7 @@ import {
|
||||
getGitHubRelease,
|
||||
findAvailableDownloadUrl
|
||||
} from '@/napcat-common/src/mirror';
|
||||
import { ILogWrapper } from '@/napcat-common/src/log-interface';
|
||||
|
||||
// 更新请求体接口
|
||||
interface UpdateRequestBody {
|
||||
@ -78,18 +79,18 @@ function scanFilesRecursively (dirPath: string, basePath: string = dirPath): Arr
|
||||
* 下载文件(带进度和重试)
|
||||
*/
|
||||
async function downloadFile (url: string, dest: string): Promise<void> {
|
||||
console.log('Starting download from:', url);
|
||||
webUiLogger?.log('[NapCat Update] Starting download from:', url);
|
||||
const file = fs.createWriteStream(dest);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = https.get(url, {
|
||||
headers: { 'User-Agent': 'NapCat-WebUI' }
|
||||
}, (res) => {
|
||||
console.log('Response status:', res.statusCode);
|
||||
console.log('Content-Type:', res.headers['content-type']);
|
||||
webUiLogger?.log('[NapCat Update] Response status:', res.statusCode);
|
||||
webUiLogger?.log('[NapCat Update] Content-Type:', res.headers['content-type']);
|
||||
|
||||
if (res.statusCode === 302 || res.statusCode === 301) {
|
||||
console.log('Following redirect to:', res.headers.location);
|
||||
webUiLogger?.log('[NapCat Update] Following redirect to:', res.headers.location);
|
||||
file.close();
|
||||
fs.unlinkSync(dest);
|
||||
downloadFile(res.headers.location!, dest).then(resolve).catch(reject);
|
||||
@ -106,13 +107,13 @@ async function downloadFile (url: string, dest: string): Promise<void> {
|
||||
res.pipe(file);
|
||||
file.on('finish', () => {
|
||||
file.close();
|
||||
console.log('Download completed');
|
||||
webUiLogger?.log('[NapCat Update] Download completed');
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
request.on('error', (err) => {
|
||||
console.error('Download error:', err);
|
||||
webUiLogger?.logError('[NapCat Update] Download error:', err);
|
||||
file.close();
|
||||
fs.unlink(dest, () => { });
|
||||
reject(err);
|
||||
@ -131,7 +132,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
|
||||
// 确定目标版本 tag
|
||||
// 如果指定了版本,使用指定版本;否则使用 'latest'
|
||||
const targetTag = targetVersion || 'latest';
|
||||
console.log(`[NapCat Update] Target version: ${targetTag}`);
|
||||
webUiLogger?.log(`[NapCat Update] Target version: ${targetTag}`);
|
||||
|
||||
// 使用 mirror 模块获取 release 信息(不依赖 API)
|
||||
// 通过 assetNames 参数直接构建下载 URL,避免调用 GitHub API
|
||||
@ -147,7 +148,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
|
||||
|
||||
// 检查是否需要强制更新(降级警告)
|
||||
const currentVersion = WebUiDataRuntime.GetNapCatVersion();
|
||||
console.log(`[NapCat Update] Current version: ${currentVersion}, Target version: ${release.tag_name}`);
|
||||
webUiLogger?.log(`[NapCat Update] Current version: ${currentVersion}, Target version: ${release.tag_name}`);
|
||||
|
||||
if (!force && currentVersion) {
|
||||
// 简单的版本比较(可选的降级保护)
|
||||
@ -165,12 +166,12 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
|
||||
(targetMajor === currMajor && targetMinor === currMinor && targetPatch < currPatch);
|
||||
|
||||
if (isDowngrade) {
|
||||
console.log(`[NapCat Update] Downgrade from ${currentVersion} to ${release.tag_name}, force=${force}`);
|
||||
webUiLogger?.log(`[NapCat Update] Downgrade from ${currentVersion} to ${release.tag_name}, force=${force}`);
|
||||
// 不阻止降级,只是记录日志
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[NapCat Update] Updating to version: ${release.tag_name}`);
|
||||
webUiLogger?.log(`[NapCat Update] Updating to version: ${release.tag_name}`);
|
||||
|
||||
// 创建临时目录
|
||||
const tempDir = path.join(webUiPathWrapper.binaryPath, './temp');
|
||||
@ -186,20 +187,20 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
|
||||
timeout: 10000, // 10秒超时
|
||||
});
|
||||
|
||||
console.log(`[NapCat Update] Using download URL: ${downloadUrl}`);
|
||||
webUiLogger?.log(`[NapCat Update] Using download URL: ${downloadUrl}`);
|
||||
|
||||
// 下载zip
|
||||
const zipPath = path.join(tempDir, 'napcat-latest.zip');
|
||||
console.log('[NapCat Update] Saving to:', zipPath);
|
||||
webUiLogger?.log('[NapCat Update] Saving to:', zipPath);
|
||||
await downloadFile(downloadUrl, zipPath);
|
||||
|
||||
// 检查文件大小
|
||||
const stats = fs.statSync(zipPath);
|
||||
console.log('[NapCat Update] Downloaded file size:', stats.size, 'bytes');
|
||||
webUiLogger?.log('[NapCat Update] Downloaded file size:', stats.size, 'bytes');
|
||||
|
||||
// 解压到临时目录
|
||||
const extractPath = path.join(tempDir, 'napcat-extract');
|
||||
console.log('[NapCat Update] Extracting to:', extractPath);
|
||||
webUiLogger?.log('[NapCat Update] Extracting to:', extractPath);
|
||||
await compressing.zip.uncompress(zipPath, extractPath);
|
||||
|
||||
// 获取解压后的实际内容目录(NapCat.Shell.zip直接包含文件,无额外根目录)
|
||||
@ -220,7 +221,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
|
||||
|
||||
// 跳过指定的文件
|
||||
if (SKIP_UPDATE_FILES.includes(path.basename(fileInfo.relativePath))) {
|
||||
console.log(`[NapCat Update] Skipping update for ${fileInfo.relativePath}`);
|
||||
webUiLogger?.log(`[NapCat Update] Skipping update for ${fileInfo.relativePath}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -238,7 +239,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
|
||||
fs.copyFileSync(fileInfo.sourcePath, targetFilePath);
|
||||
} catch (error) {
|
||||
// 如果替换失败,添加到失败列表
|
||||
console.log(`[NapCat Update] Failed to update ${targetFilePath}, will retry on next startup:`, error);
|
||||
webUiLogger?.logError(`[NapCat Update] Failed to update ${targetFilePath}, will retry on next startup:`, error);
|
||||
failedFiles.push({
|
||||
sourcePath: fileInfo.sourcePath,
|
||||
targetPath: targetFilePath
|
||||
@ -258,7 +259,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
|
||||
// 保存更新配置文件
|
||||
const configPath = path.join(webUiPathWrapper.configPath, 'napcat-update.json');
|
||||
fs.writeFileSync(configPath, JSON.stringify(updateConfig, null, 2));
|
||||
console.log(`[NapCat Update] Update config saved for ${failedFiles.length} failed files: ${configPath}`);
|
||||
webUiLogger?.log(`[NapCat Update] Update config saved for ${failedFiles.length} failed files: ${configPath}`);
|
||||
}
|
||||
|
||||
// 发送成功响应
|
||||
@ -273,12 +274,12 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('更新失败:', error);
|
||||
webUiLogger?.logError('[NapCat Update] 更新失败:', error);
|
||||
sendError(res, '更新失败: ' + (error instanceof Error ? error.message : '未知错误'));
|
||||
}
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('更新失败:', error);
|
||||
webUiLogger?.logError('[NapCat Update] 更新失败:', error);
|
||||
sendError(res, '更新失败: ' + error.message);
|
||||
}
|
||||
};
|
||||
@ -288,16 +289,16 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => {
|
||||
/**
|
||||
* 应用待处理的更新(在应用启动时调用)
|
||||
*/
|
||||
export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper): Promise<void> {
|
||||
export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper, logger: ILogWrapper): Promise<void> {
|
||||
const configPath = path.join(webUiPathWrapper.configPath, 'napcat-update.json');
|
||||
|
||||
if (!fs.existsSync(configPath)) {
|
||||
console.log('No pending updates found');
|
||||
logger.log('[NapCat Update] No pending updates found');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('[NapCat Update] Applying pending updates...');
|
||||
logger.log('[NapCat Update] Applying pending updates...');
|
||||
const updateConfig: UpdateConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
||||
|
||||
const remainingFiles: Array<{
|
||||
@ -309,7 +310,7 @@ export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper):
|
||||
try {
|
||||
// 检查源文件是否存在
|
||||
if (!fs.existsSync(file.sourcePath)) {
|
||||
console.warn(`[NapCat Update] Source file not found: ${file.sourcePath}`);
|
||||
logger.logWarn(`[NapCat Update] Source file not found: ${file.sourcePath}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -324,10 +325,10 @@ export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper):
|
||||
fs.unlinkSync(file.targetPath); // 删除旧文件
|
||||
}
|
||||
fs.copyFileSync(file.sourcePath, file.targetPath);
|
||||
console.log(`[NapCat Update] Updated ${path.basename(file.targetPath)} on startup`);
|
||||
logger.log(`[NapCat Update] Updated ${path.basename(file.targetPath)} on startup`);
|
||||
|
||||
} catch (error) {
|
||||
console.error(`[NapCat Update] Failed to update ${file.targetPath} on startup:`, error);
|
||||
logger.logError(`[NapCat Update] Failed to update ${file.targetPath} on startup:`, error);
|
||||
// 如果仍然失败,保留在列表中
|
||||
remainingFiles.push(file);
|
||||
}
|
||||
@ -340,13 +341,13 @@ export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper):
|
||||
files: remainingFiles
|
||||
};
|
||||
fs.writeFileSync(configPath, JSON.stringify(updatedConfig, null, 2));
|
||||
console.log(`${remainingFiles.length} files still pending update`);
|
||||
logger.log(`[NapCat Update] ${remainingFiles.length} files still pending update`);
|
||||
} else {
|
||||
// 所有文件都成功更新,删除配置文件
|
||||
fs.unlinkSync(configPath);
|
||||
console.log('[NapCat Update] All pending updates applied successfully');
|
||||
logger.log('[NapCat Update] All pending updates applied successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[NapCat Update] Failed to apply pending updates:', error);
|
||||
logger.logError('[NapCat Update] Failed to apply pending updates:', error);
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user