Revert "update: normalize log"

This reverts commit d36a28fa81.
This commit is contained in:
手瓜一十雪 2024-09-04 18:05:01 +08:00
parent 043d8a1861
commit ab824fb219
16 changed files with 94 additions and 84 deletions

View File

@ -12,7 +12,7 @@ export async function encodeSilk(filePath: string, TEMP_DIR: string, logger: Log
let duration = pttFileInfo.size / 1024 / 3; // 3kb/s
duration = Math.floor(duration);
duration = Math.max(1, duration);
logger.logDebug('通过文件大小估算语音的时长:', duration);
logger.log('通过文件大小估算语音的时长:', duration);
return duration;
}
@ -20,7 +20,7 @@ export async function encodeSilk(filePath: string, TEMP_DIR: string, logger: Log
const file = await fsPromise.readFile(filePath);
const pttPath = path.join(TEMP_DIR, randomUUID());
if (!isSilk(file)) {
logger.logDebug(`语音文件${filePath}需要转换成silk`);
logger.log(`语音文件${filePath}需要转换成silk`);
const _isWav = isWav(file);
const pcmPath = pttPath + '.pcm';
let sampleRate = 0;
@ -30,7 +30,7 @@ export async function encodeSilk(filePath: string, TEMP_DIR: string, logger: Log
const ffmpegPath = process.env.FFMPEG_PATH || 'ffmpeg';
const cp = spawn(ffmpegPath, ['-y', '-i', filePath, '-ar', '24000', '-ac', '1', '-f', 's16le', pcmPath]);
cp.on('error', err => {
logger.logError('ffmpeg 处理转换出错: ', err.message);
logger.log('FFmpeg处理转换出错: ', err.message);
return reject(err);
});
cp.on('exit', (code, signal) => {
@ -38,11 +38,12 @@ export async function encodeSilk(filePath: string, TEMP_DIR: string, logger: Log
if (code == null || EXIT_CODES.includes(code)) {
sampleRate = 24000;
const data = fs.readFileSync(pcmPath);
fs.unlinkSync(pcmPath);
fs.unlink(pcmPath, (err) => {
});
return resolve(data);
}
logger.logError(`ffmpeg 处理失败: code=${code ?? 'unknown'} sig=${signal ?? 'unknown'}`);
reject(Error(`ffmpeg 处理失败: code=${code ?? 'unknown'} sig=${signal ?? 'unknown'}`));
logger.log(`FFmpeg exit: code=${code ?? 'unknown'} sig=${signal ?? 'unknown'}`);
reject(Error('FFmpeg处理转换失败'));
});
});
};
@ -60,7 +61,7 @@ export async function encodeSilk(filePath: string, TEMP_DIR: string, logger: Log
}
const silk = await encode(input, sampleRate);
fs.writeFileSync(pttPath, silk.data);
logger.logDebug(`语音文件 ${filePath} 转换成功:`, pttPath, '时长:', silk.duration);
logger.log(`语音文件${filePath}转换成功!`, pttPath, '时长:', silk.duration);
return {
converted: true,
path: pttPath,
@ -68,11 +69,11 @@ export async function encodeSilk(filePath: string, TEMP_DIR: string, logger: Log
};
} else {
const silk = file;
let duration: number;
let duration = 0;
try {
duration = getDuration(silk) / 1000;
} catch (e: any) {
logger.logWarn('获取语音文件时长失败, 使用文件大小推测时长', filePath, e.stack);
logger.log('获取语音文件时长失败, 使用文件大小推测时长', filePath, e.stack);
duration = await guessDuration(filePath);
}

View File

@ -38,9 +38,9 @@ export abstract class ConfigBase<T> {
if (!fs.existsSync(configPath)) {
try {
fs.writeFileSync(configPath, fs.readFileSync(this.getConfigPath(undefined), 'utf-8'));
logger.log(`配置文件 ${this.name} 创建成功\n`);
logger.log(`[Core] [Config] 配置文件创建成功!\n`);
} catch (e: any) {
logger.logError(`创建配置文件 ${this.name} 时发生错误:`, e.message);
logger.logError(`[Core] [Config] 创建配置文件时发生错误:`, e.message);
}
}
try {
@ -49,9 +49,9 @@ export abstract class ConfigBase<T> {
return this.configData;
} catch (e: any) {
if (e instanceof SyntaxError) {
logger.logError(`配置文件 ${this.name} 格式错误, 请检查配置文件:`, e.message);
logger.logError(`[Core] [Config] 配置文件格式错误,请检查配置文件:`, e.message);
} else {
logger.logError(`读取配置文件 ${this.name} 时发生错误:`, e);
logger.logError(`[Core] [Config] 读取配置文件时发生错误:`, e.message);
}
return {} as T;
}

View File

@ -53,23 +53,23 @@ export class QQBasicInfoWrapper {
//此方法不要直接使用
getQUAInternal() {
switch (systemPlatform) {
case 'linux':
return `V1_LNX_${this.getFullQQVesion()}_${this.getQQBuildStr()}_GW_B`;
case 'darwin':
return `V1_MAC_${this.getFullQQVesion()}_${this.getQQBuildStr()}_GW_B`;
default:
return `V1_WIN_${this.getFullQQVesion()}_${this.getQQBuildStr()}_GW_B`;
case 'linux':
return `V1_LNX_${this.getFullQQVesion()}_${this.getQQBuildStr()}_GW_B`;
case 'darwin':
return `V1_MAC_${this.getFullQQVesion()}_${this.getQQBuildStr()}_GW_B`;
default:
return `V1_WIN_${this.getFullQQVesion()}_${this.getQQBuildStr()}_GW_B`;
}
}
getAppidInternal() {
switch (systemPlatform) {
case 'linux':
return '537243600';
case 'darwin':
return '537243441';
default:
return '537243538';
case 'linux':
return '537243600';
case 'darwin':
return '537243441';
default:
return '537243538';
}
}
@ -84,8 +84,8 @@ export class QQBasicInfoWrapper {
}
// else
this.context.logger.logWarn(`获取 AppID 异常, 使用备用 AppID. 请检测 NapCat/QQNT 是否正常`);
this.context.logger.logWarn(`${fullVersion} 版本兼容性不佳, 可能会导致一些功能无法正常使用`,);
this.context.logger.log(`[QQ版本兼容性检测] 获取Appid异常 请检测NapCat/QQNT是否正常`);
this.context.logger.log(`[QQ版本兼容性检测] ${fullVersion} 版本兼容性不佳可能会导致一些功能无法正常使用`,);
return { appid: this.getAppidInternal(), qua: this.getQUAInternal() };
}
}

View File

@ -24,9 +24,9 @@ export async function getVideoInfo(filePath: string, logger: LogWrapper) {
} else {
const videoStream = metadata.streams.find((s: FfprobeStream) => s.codec_type === 'video');
if (videoStream) {
logger.logDebug(`视频尺寸: ${videoStream.width}x${videoStream.height}`);
logger.log(`视频尺寸: ${videoStream.width}x${videoStream.height}`);
} else {
return reject(new Error('未找到视频流信息.'));
return reject(new Error('未找到视频流信息'));
}
resolve({
width: videoStream.width!, height: videoStream.height!,
@ -42,16 +42,17 @@ export async function getVideoInfo(filePath: string, logger: LogWrapper) {
export function checkFfmpeg(logger: LogWrapper, newPath: string | null = null): Promise<boolean> {
return new Promise((resolve) => {
logger.logDebug('开始检查 ffmpeg', newPath);
logger.log('开始检查ffmpeg', newPath);
if (newPath) {
ffmpeg.setFfmpegPath(newPath);
}
try {
ffmpeg.getAvailableFormats((err: any) => {
if (err) {
logger.logWarn('未找到 ffmpeg', err);
logger.log('ffmpeg is not installed or not found in PATH:', err);
resolve(false);
} else {
logger.log('ffmpeg is installed.');
resolve(true);
}
});

View File

@ -148,7 +148,7 @@ export class NTQQFileApi {
try {
videoInfo = await getVideoInfo(path, logger);
} catch (e) {
logger.logWarn('获取视频信息失败,将使用默认值', e);
logger.logError('获取视频信息失败,将使用默认值', e);
}
const thumbPath = new Map();
const _thumbPath = await new Promise<string | undefined>((resolve, reject) => {

View File

@ -26,7 +26,7 @@ export class RkeyManager {
try {
await this.refreshRkey();
} catch (e) {
this.logger.logError('获取 rkey 失败', e);
this.logger.logError('获取rkey失败', e);
}
}
return this.rkeyData;

View File

@ -119,9 +119,9 @@ export class NapCatCore {
// Renamed from 'InitDataListener'
async initNapCatCoreListeners() {
const msgListener = new NodeIKernelMsgListener();
msgListener.onKickedOffLine = (info: KickedOffLineInfo) => {
msgListener.onKickedOffLine = (Info: KickedOffLineInfo) => {
// 下线通知
this.context.logger.logError(`当前账户被强制下线: ${info.tipsTitle} ${info.tipsDesc}`);
this.context.logger.logError('[KickedOffLine] [' + Info.tipsTitle + '] ' + Info.tipsDesc);
this.selfInfo.online = false;
};
msgListener.onRecvMsg = (msgs) => {

View File

@ -148,7 +148,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
//对Mgsid和OB11ID混用情况兜底
const nodeMsg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(nodeId)) || MessageUnique.getPeerByMsgId(nodeId);
if (!nodeMsg) {
logger.logError(`转发消息失败, 未找到消息 ${nodeId}`);
logger.logError('转发消息失败,未找到消息', nodeId);
continue;
}
nodeMsgIds.push(nodeMsg.MsgId);
@ -160,7 +160,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
const isNodeMsg = OB11Data.filter(e => e.type === OB11MessageDataType.node).length;//找到子转发消息
if (isNodeMsg !== 0) {
if (isNodeMsg !== OB11Data.length) {
logger.logWarn('子消息中包含非 node 消息, 跳过不合法部分');
logger.logError('子消息中包含非node消息 跳过不合法部分');
continue;
}
const nodeMsg = await this.handleForwardedNodes(selfPeer, OB11Data.filter(e => e.type === OB11MessageDataType.node));
@ -256,12 +256,12 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
}
if (sendElements.length === 0) {
logger.logWarn('需要 clone 的消息无法解析, 忽略: ', msg);
logger.logDebug('需要clone的消息无法解析将会忽略掉', msg);
}
try {
return await this.core.apis.MsgApi.sendMsg(selfPeer, sendElements, true);
} catch (e) {
logger.logError('克隆转发消息失败, 将忽略本条消息', e, msg);
logger.logError(e, '克隆转发消息失败,将忽略本条消息', msg);
}
}
}

View File

@ -234,7 +234,7 @@ export class OneBotMsgApi {
if (records.peerUin === '284840486') {
return createReplyData(records.msgId);
}
const replyMsg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeqV2(peer, element.replayMsgSeq, element.replyMsgTime, [element.senderUidStr]))
let replyMsg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeqV2(peer, element.replayMsgSeq, element.replyMsgTime, [element.senderUidStr]))
.msgList.find(msg => msg.msgRandom === records.msgRandom);
if (!replyMsg || records.msgRandom !== replyMsg.msgRandom) {
@ -591,20 +591,25 @@ export class OneBotMsgApi {
// 保留, 直到...找到更好的解决方案
if (data.type === 'custom') {
if (!data.url) {
throw '自定义音乐卡片缺少参数 url';
this.core.context.logger.logError('自定义音卡缺少参数url');
return undefined;
}
if (!data.audio) {
throw '自定义音乐卡片缺少参数 audio';
this.core.context.logger.logError('自定义音卡缺少参数audio');
return undefined;
}
if (!data.title) {
throw '自定义音乐卡片缺少参数 title';
this.core.context.logger.logError('自定义音卡缺少参数title');
return undefined;
}
} else {
if (!['qq', '163'].includes(data.type)) {
throw `不支持的 type: ${data.type}`;
this.core.context.logger.logError('音乐卡片type错误, 只支持qq、163、custom当前type:', data.type);
return undefined;
}
if (!data.id) {
throw '音乐卡片缺少参数 id';
this.core.context.logger.logError('音乐卡片缺少参数id');
return undefined;
}
}

View File

@ -87,7 +87,7 @@ export class NapCatOneBot11Adapter {
selfInfo.nick = user.nick;
this.context.logger.setLogSelfInfo(selfInfo);
}).catch(this.context.logger.logError);
this.context.logger.log(`OneBot 服务状态: ${serviceInfo}`);
this.context.logger.log(`[Notice] [OneBot11] ${serviceInfo}`);
//创建NetWork服务
if (ob11Config.http.enable) {
@ -128,7 +128,7 @@ export class NapCatOneBot11Adapter {
await WebUiDataRuntime.setOnOB11ConfigChanged(async (newConfig: OB11Config) => {
const prev = this.configLoader.configData;
this.configLoader.save(newConfig);
this.context.logger.logDebug(`OneBot11 配置更改: ${JSON.stringify(prev)} -> ${JSON.stringify(newConfig)}`);
this.context.logger.log(`OneBot11 配置更改:${JSON.stringify(prev)} -> ${JSON.stringify(newConfig)}`);
await this.reloadNetwork(prev, newConfig);
});
}
@ -150,7 +150,7 @@ export class NapCatOneBot11Adapter {
HTTP上报服务 ${now.http.enablePost ? '已启动' : '未启动'}, 上报地址: ${now.http.postUrls}
WebSocket服务 ${now.ws.enable ? '已启动' : '未启动'}, ${now.ws.host}:${now.ws.port}
WebSocket反向服务 ${now.reverseWs.enable ? '已启动' : '未启动'}, 反向地址: ${now.reverseWs.urls}`;
this.context.logger.log(`热重载 - OneBot 服务状态: ${serviceInfo}`);
this.context.logger.log(`[Notice] [OneBot11] 热重载 ${serviceInfo}`);
// check difference in passive http (Http)
if (prev.http.enable !== now.http.enable) {
@ -270,7 +270,7 @@ export class NapCatOneBot11Adapter {
msgListener.onInputStatusPush = async data => {
const uin = await this.core.apis.UserApi.getUinByUidV2(data.fromUin);
this.context.logger.log(`${uin} 输入状态更新: ${data.statusText}`);
this.context.logger.log(`[Notice] [输入状态] ${uin} ${data.statusText}`);
await this.networkManager.emitEvent(new OB11InputStatusEvent(
this.core,
parseInt(uin),

View File

@ -43,7 +43,7 @@ export class OB11ActiveHttpAdapter implements IOB11NetworkAdapter {
resJson = await res.json();
//logDebug('新消息事件HTTP上报返回快速操作: ', JSON.stringify(resJson));
} catch (e) {
this.logger.logDebug('新消息事件 HTTP 上报没有返回快速操作,不需要处理');
this.logger.logDebug('[OneBot] [Http Client] 新消息事件HTTP上报没有返回快速操作不需要处理');
return;
}
try {
@ -51,10 +51,10 @@ export class OB11ActiveHttpAdapter implements IOB11NetworkAdapter {
.handleQuickOperation(event as QuickActionEvent, resJson)
.catch(this.logger.logError);
} catch (e: any) {
this.logger.logError('新消息事件 HTTP 上报返回快速操作失败', e);
this.logger.logError('[OneBot] [Http Client] 新消息事件HTTP上报返回快速操作失败', e);
}
}).catch((e) => {
this.logger.logError('新消息事件 HTTP 上报失败', e);
this.logger.logError('[OneBot] [Http Client] 新消息事件HTTP上报失败', e);
});
}

View File

@ -85,13 +85,13 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
this.connection?.pong();
});
this.connection.on('pong', () => {
//this.logger.logDebug('收到pong');
//this.logger.logDebug('[OneBot] [WebSocket Client] 收到pong');
});
this.connection.on('open', () => {
try {
this.connectEvent(this.core);
} catch (e) {
this.logger.logError('发送连接生命周期失败', e);
this.logger.logError('[OneBot] [WebSocket Client] 发送连接生命周期失败', e);
}
});
@ -100,8 +100,8 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
});
this.connection.once('close', () => {
if (!isClosedByError) {
this.logger.logError(`反向WebSocket (${this.url}) 连接意外关闭`);
this.logger.logError(`${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
this.logger.logError(`[OneBot] [WebSocket Client] 反向WebSocket (${this.url}) 连接意外关闭`);
this.logger.logError(`[OneBot] [WebSocket Client] ${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
if (!this.isClosed) {
this.connection = null;
setTimeout(() => this.tryConnect(), this.reconnectIntervalInMillis);
@ -110,8 +110,8 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
});
this.connection.on('error', (err) => {
isClosedByError = true;
this.logger.logError(`反向WebSocket (${this.url}) 连接错误`, err);
this.logger.logError(`${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
this.logger.logError(`[OneBot] [WebSocket Client] 反向WebSocket (${this.url}) 连接错误`, err);
this.logger.logError(`[OneBot] [WebSocket Client] ${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
if (!this.isClosed) {
this.connection = null;
setTimeout(() => this.tryConnect(), this.reconnectIntervalInMillis);
@ -124,7 +124,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
try {
this.checkStateAndReply<any>(new OB11LifeCycleEvent(core, LifeCycleSubType.CONNECT));
} catch (e) {
this.logger.logError('发送生命周期失败', e);
this.logger.logError('[OneBot] [WebSocket Client] 发送生命周期失败', e);
}
}
@ -135,7 +135,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
try {
receiveData = JSON.parse(message.toString());
echo = receiveData.echo;
this.logger.logDebug('收到正向Websocket消息', receiveData);
this.logger.logDebug('[OneBot] [WebSocket Client] 收到正向Websocket消息', receiveData);
} catch (e) {
this.checkStateAndReply<any>(OB11Response.error('json解析失败,请检查数据格式', 1400, echo));
return;
@ -143,8 +143,8 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
receiveData.params = (receiveData?.params) ? receiveData.params : {};//兼容类型验证
const action = this.actions.get(receiveData.action);
if (!action) {
this.logger.logError('不支持的 api' + receiveData.action);
this.checkStateAndReply<any>(OB11Response.error('不支持的 api ' + receiveData.action, 1404, echo));
this.logger.logError('[OneBot] [WebSocket Client] 发生错误', '不支持的api ' + receiveData.action);
this.checkStateAndReply<any>(OB11Response.error('不支持的api ' + receiveData.action, 1404, echo));
return;
}
const retdata = await action.websocketHandle(receiveData.params, echo ?? '');

View File

@ -26,7 +26,7 @@ export class OB11PassiveHttpAdapter implements IOB11NetworkAdapter {
open() {
try {
if (this.isOpen) {
this.core.context.logger.logError('Http 服务已经启动');
this.core.context.logger.logError('Cannot open a closed HTTP server');
return;
}
if (!this.isOpen) {
@ -34,7 +34,7 @@ export class OB11PassiveHttpAdapter implements IOB11NetworkAdapter {
this.isOpen = true;
}
} catch (e) {
this.core.context.logger.logError('Http 服务启动失败', e);
this.core.context.logger.logError(`[OneBot] [HTTP Server Adapter] Boot Error: ${e}`);
}
}
@ -67,7 +67,7 @@ export class OB11PassiveHttpAdapter implements IOB11NetworkAdapter {
this.app.use((req, res) => this.handleRequest(req, res));
this.server.listen(this.port, () => {
this.core.context.logger.logDebug(`OneBot 11 Http 服务在 ${this.port} 上启动`);
this.core.context.logger.log(`[OneBot] [HTTP Server Adapter] Start On Port ${this.port}`);
});
}
@ -85,7 +85,7 @@ export class OB11PassiveHttpAdapter implements IOB11NetworkAdapter {
private async handleRequest(req: Request, res: Response) {
if (!this.isOpen) {
this.core.context.logger.log(`OneBot 11 Http 服务已关闭`);
this.core.context.logger.log(`[OneBot] [HTTP Server Adapter] Server is closed`);
return res.json(OB11Response.error('Server is closed', 200));
}

View File

@ -47,7 +47,7 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
//鉴权
this.authorize(token, wsClient, wsReq);
this.connectEvent(core, wsClient);
wsClient.on('error', (err) => this.logger.logError('OneBot 11 WS 客户端连接异常中断', err.message));
wsClient.on('error', (err) => this.logger.log('[OneBot] [WebSocket Server] Client Error:', err.message));
wsClient.on('message', (message) => {
this.handleMessage(wsClient, message).then().catch(this.logger.logError);
});
@ -68,14 +68,14 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
await this.wsClientsMutex.runExclusive(async () => {
this.wsClients.push(wsClient);
});
}).on('error', (err) => this.logger.logError('OneBot 11 WS 服务端错误', err.message));
}).on('error', (err) => this.logger.log('[OneBot] [WebSocket Server] Server Error:', err.message));
}
connectEvent(core: NapCatCore, wsClient: WebSocket) {
try {
this.checkStateAndReply<any>(new OB11LifeCycleEvent(core, LifeCycleSubType.CONNECT), wsClient);
} catch (e) {
this.logger.logError('WS 服务发送生命周期失败', e);
this.logger.logError('[OneBot] [WebSocket Server] 发送生命周期失败', e);
}
}
@ -89,13 +89,15 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
open() {
if (this.isOpen) {
throw 'WS 服务已经打开, 不能再次打开';
this.logger.logError('[OneBot] [WebSocket Server] Cannot open a opened WebSocket server');
return;
}
if (this.hasBeenClosed) {
throw 'WS 服务已经关闭, 不能再次打开';
this.logger.logError('[OneBot] [WebSocket Server] Cannot open a WebSocket server that has been closed');
return;
}
const addressInfo = this.wsServer.address();
this.logger.logDebug('WS 服务启动', typeof (addressInfo) === 'string' ? addressInfo : addressInfo?.address + ':' + addressInfo?.port);
this.logger.log('[OneBot] [WebSocket Server] Server Started', typeof (addressInfo) === 'string' ? addressInfo : addressInfo?.address + ':' + addressInfo?.port);
this.isOpen = true;
this.registerHeartBeat();
@ -154,7 +156,7 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
receiveData.params = (receiveData?.params) ? receiveData.params : {};//兼容类型验证
const action = this.actions.get(receiveData.action);
if (!action) {
this.logger.logError(`不支持的 api ${receiveData.action}`);
this.logger.logError('[OneBot] [WebSocket Client] 发生错误', '不支持的api ' + receiveData.action);
this.checkStateAndReply<any>(OB11Response.error('不支持的api ' + receiveData.action, 1404, echo), wsClient);
return;
}

View File

@ -39,7 +39,7 @@ export async function NCoreInitShell() {
const logger = new LogWrapper(pathWrapper.logsPath);
const basicInfoWrapper = new QQBasicInfoWrapper({ logger });
const wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVesion());
logger.log(`NapCatQQ 版本: ` + napCatVersion);
logger.log(`[NapCat] [Core] NapCat.Core Version: ` + napCatVersion);
InitWebUi(logger, pathWrapper).then().catch(logger.logError);
// from constructor
@ -125,20 +125,20 @@ export async function NCoreInitShell() {
logger.logWarn('请扫描下面的二维码然后在手Q上授权登录');
const qrcodePath = path.join(pathWrapper.cachePath, 'qrcode.png');
qrcode.generate(qrcodeUrl, { small: true }, (res) => {
logger.log([
logger.logWarn([
'\n',
res,
'二维码解码URL: ' + qrcodeUrl,
'如果控制台二维码无法扫码可以复制解码url到二维码生成网站生成二维码再扫码也可以打开下方的二维码路径图片进行扫码。',
].join('\n'));
fs.writeFile(qrcodePath, buffer, {}, () => {
logger.log(`二维码已保存到 ${qrcodePath}`);
logger.logWarn('二维码已保存到', qrcodePath);
});
});
};
loginListener.onQRCodeSessionFailed = (errType: number, errCode: number, errMsg: string) => {
//logger.logError('登录失败(onQRCodeSessionFailed)', errCode, errMsg);
logger.logError(`二维码登录失败(${errCode} - ${errType}): ${errMsg}`);
logger.logError('[Core] [Login] Login Error,ErrCode: ', errCode, ' ErrMsg:', errMsg);
if (errType == 1 && errCode == 3) {
// 二维码过期刷新
}
@ -146,7 +146,7 @@ export async function NCoreInitShell() {
};
loginListener.onLoginFailed = (args) => {
//logger.logError('登录失败(onLoginFailed)', args);
logger.logError('登录失败', args);
logger.logError('[Core] [Login] Login Error , ErrInfo: ', args);
};
loginService.addKernelLoginListener(proxiedListenerOf(loginListener, logger) as any);
@ -190,7 +190,7 @@ export async function NCoreInitShell() {
.catch();
}, 1000);
} else {
logger.logError('快速登录失败, 未找到该 QQ 历史登录记录, 将使用二维码登录方式.');
logger.logError('快速登录失败,未找到该 QQ 历史登录记录,将使用二维码登录方式');
loginService.getQRCodePicture();
}
} else {
@ -199,7 +199,7 @@ export async function NCoreInitShell() {
logger.log(`可用于快速登录的 QQ\n${historyLoginList
.map((u, index) => `${index + 1}. ${u.uin} ${u.nickName}`)
.join('\n')
}`);
}`);
}
loginService.getQRCodePicture();
}

View File

@ -18,9 +18,10 @@ export let webUiPathWrapper: NapCatPathWrapper;
export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapper) {
webUiPathWrapper = pathWrapper;
WebUiConfig = new WebUiConfigWrapper();
const log = logger.log.bind(logger);
const config = await WebUiConfig.GetWebUIConfig();
if (config.port == 0) {
logger.log('[NapCat] [WebUi] Current WebUi is not run.');
log('[NapCat] [WebUi] Current WebUi is not run.');
return;
}
app.use(express.json());
@ -36,8 +37,8 @@ export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapp
//挂载API接口
app.use(config.prefix + '/api', ALLRouter);
app.listen(config.port, config.host, async () => {
logger.log(`[NapCat] [WebUi] Current WebUi is running at http://${config.host}:${config.port}${config.prefix}`);
logger.log(`[NapCat] [WebUi] Login URL is http://${config.host}:${config.port}${config.prefix}/webui`);
logger.log(`[NapCat] [WebUi] Login Token is ${config.token}`);
log(`[NapCat] [WebUi] Current WebUi is running at http://${config.host}:${config.port}${config.prefix}`);
log(`[NapCat] [WebUi] Login URL is http://${config.host}:${config.port}${config.prefix}/webui`);
log(`[NapCat] [WebUi] Login Token is ${config.token}`);
});
}