Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53ceb85801 | ||
|
|
dbba6b3ffe | ||
|
|
03dd89add0 | ||
|
|
7fc70bc5ce | ||
|
|
6758825895 | ||
|
|
ae53d27313 | ||
|
|
86884b6ba2 |
No files matched your search
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* 服务器时间矫正 - 全局 Hook
|
||||
*
|
||||
* 保留 Date.now 原始引用,启动后通过 getServerTime 计算偏移量,
|
||||
* 直接覆盖 Date.now(),使全局所有调用自动获得矫正后的时间戳。
|
||||
*/
|
||||
|
||||
/** 原始 Date.now 引用,不受 hook 影响 */
|
||||
export const OriginalDateNow: () => number = Date.now.bind(Date);
|
||||
|
||||
/**
|
||||
* 初始化全局时间矫正,覆盖 Date.now()
|
||||
* @param getServerTimeFn 获取服务器时间的函数,返回毫秒级时间戳字符串
|
||||
* @returns 偏移量(毫秒)
|
||||
*/
|
||||
export function hookGlobalDateNow (getServerTimeFn: () => string): number {
|
||||
const localNow = OriginalDateNow();
|
||||
const serverTimeStr = getServerTimeFn();
|
||||
const serverTimeMs = parseInt(serverTimeStr, 10);
|
||||
|
||||
if (isNaN(serverTimeMs) || serverTimeMs <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const offsetMs = serverTimeMs - localNow;
|
||||
|
||||
if (Math.abs(offsetMs) > 5000) {
|
||||
Date.now = () => OriginalDateNow() + offsetMs;
|
||||
}
|
||||
|
||||
return offsetMs;
|
||||
}
|
||||
@@ -38,6 +38,7 @@ import { Napi2NativeLoader } from './packet/handler/napi2nativeLoader';
|
||||
import { container, ReceiverServiceRegistry } from './packet/handler/serviceRegister';
|
||||
import { appEvent } from './packet/handler/eventList';
|
||||
import { TypedEventEmitter } from './packet/handler/typeEvent';
|
||||
import { hookGlobalDateNow } from './helper/server-time';
|
||||
export * from './wrapper';
|
||||
export * from './types/index';
|
||||
export * from './services/index';
|
||||
@@ -50,6 +51,7 @@ export * from './helper/config';
|
||||
export * from './helper/config-base';
|
||||
export * from './helper/proxy-handler';
|
||||
export * from './helper/session-proxy';
|
||||
export * from './helper/server-time';
|
||||
|
||||
export enum NapCatCoreWorkingEnv {
|
||||
Unknown = 0,
|
||||
@@ -173,6 +175,17 @@ export class NapCatCore {
|
||||
if (!fs.existsSync(this.NapCatTempPath)) {
|
||||
fs.mkdirSync(this.NapCatTempPath, { recursive: true });
|
||||
}
|
||||
// 通过 getServerTime 全局 hook Date.now() 矫正本地时间偏差
|
||||
try {
|
||||
const offsetMs = hookGlobalDateNow(() => this.context.session.getMSFService().getServerTime());
|
||||
if (Math.abs(offsetMs) > 1000) {
|
||||
this.context.logger.logWarn(`[ServerTime] 本地时间与服务器时间偏差 ${(offsetMs / 1000).toFixed(1)}s,已自动矫正`);
|
||||
} else {
|
||||
this.context.logger.log(`[ServerTime] 时间同步完成,偏差 ${offsetMs}ms`);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('[ServerTime] 时间矫正失败', e);
|
||||
}
|
||||
// 遍历this.apis[i].initApi 如果存在该函数进行async 调用
|
||||
for (const apiKey in this.apis) {
|
||||
const api = this.apis[apiKey as keyof StableNTApiWrapper];
|
||||
|
||||
@@ -230,8 +230,8 @@ export class PacketOperationContext {
|
||||
}
|
||||
async UploadForwardMsgV2 (msg: UploadForwardMsgParams[], groupUin: number = 0) {
|
||||
//await this.SendPreprocess(msg, groupUin);
|
||||
// 遍历上传资源
|
||||
await Promise.allSettled(msg.map(async (item) => { return await this.SendPreprocess(item.actionMsg, groupUin); }));
|
||||
// 遍历上传资源(跳过已有原始数据的项)
|
||||
await Promise.allSettled(msg.filter(item => item.actionMsg).map(async (item) => { return await this.SendPreprocess(item.actionMsg!, groupUin); }));
|
||||
const req = trans.UploadForwardMsgV2.build(this.context.napcore.basicInfo.uid, msg, groupUin);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.UploadForwardMsg.parse(resp);
|
||||
@@ -312,6 +312,15 @@ export class PacketOperationContext {
|
||||
}
|
||||
}
|
||||
|
||||
async FetchForwardMsgRaw (resId: string) {
|
||||
const req = trans.DownloadForwardMsg.build(this.context.napcore.basicInfo.uid, resId);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.DownloadForwardMsg.parse(resp);
|
||||
const inflate = gunzipSync(res.result.payload);
|
||||
const result = new NapProtoMsg(LongMsgResult).decode(inflate);
|
||||
return result.action;
|
||||
}
|
||||
|
||||
async FetchForwardMsg (res_id: string): Promise<RawMessage[]> {
|
||||
const req = trans.DownloadForwardMsg.build(this.context.napcore.basicInfo.uid, res_id);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as crypto from 'node:crypto';
|
||||
import * as zlib from 'node:zlib';
|
||||
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from 'napcat-protobuf';
|
||||
import {
|
||||
@@ -665,11 +666,13 @@ export class PacketMsgMarkDownElement extends IPacketMsgElement<SendMarkdownElem
|
||||
export class PacketMultiMsgElement extends IPacketMsgElement<SendMultiForwardMsgElement> {
|
||||
resid: string;
|
||||
message: PacketMsg[];
|
||||
uuid: string;
|
||||
|
||||
constructor (rawElement: SendMultiForwardMsgElement, message?: PacketMsg[]) {
|
||||
super(rawElement);
|
||||
this.resid = rawElement.multiForwardMsgElement.resId;
|
||||
this.message = message ?? [];
|
||||
this.uuid = rawElement.multiForwardMsgElement.fileName || crypto.randomUUID();
|
||||
}
|
||||
|
||||
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
|
||||
@@ -677,7 +680,7 @@ export class PacketMultiMsgElement extends IPacketMsgElement<SendMultiForwardMsg
|
||||
lightAppElem: {
|
||||
data: Buffer.concat([
|
||||
Buffer.from([0x01]),
|
||||
zlib.deflateSync(Buffer.from(JSON.stringify(ForwardMsgBuilder.fromPacketMsg(this.resid, this.message)), 'utf-8')),
|
||||
zlib.deflateSync(Buffer.from(JSON.stringify(ForwardMsgBuilder.fromPacketMsg(this.resid, this.message, undefined, undefined, undefined, undefined, this.uuid)), 'utf-8')),
|
||||
]),
|
||||
},
|
||||
}];
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
import zlib from 'node:zlib';
|
||||
import * as proto from '@/napcat-core/packet/transformer/proto';
|
||||
import { NapProtoMsg } from 'napcat-protobuf';
|
||||
import { NapProtoEncodeStructType, NapProtoMsg } from 'napcat-protobuf';
|
||||
import { OidbPacket, PacketBufBuilder, PacketTransformer } from '@/napcat-core/packet/transformer/base';
|
||||
import { PacketMsg } from '@/napcat-core/packet/message/message';
|
||||
|
||||
export interface UploadForwardMsgParams {
|
||||
actionCommand: string;
|
||||
actionMsg: PacketMsg[];
|
||||
actionMsg?: PacketMsg[];
|
||||
actionMsgBody?: NapProtoEncodeStructType<typeof proto.PushMsgBody>[];
|
||||
}
|
||||
class UploadForwardMsgV2 extends PacketTransformer<typeof proto.SendLongMsgResp> {
|
||||
build (selfUid: string, msg: UploadForwardMsgParams[], groupUin: number = 0): OidbPacket {
|
||||
const reqdata = msg.map((item) => ({
|
||||
actionCommand: item.actionCommand,
|
||||
actionData: {
|
||||
msgBody: this.msgBuilder.buildFakeMsg(selfUid, item.actionMsg),
|
||||
msgBody: item.actionMsgBody ?? this.msgBuilder.buildFakeMsg(selfUid, item.actionMsg ?? []),
|
||||
}
|
||||
}));
|
||||
const longMsgResultData = new NapProtoMsg(proto.LongMsgResult).encode(
|
||||
|
||||
@@ -84,16 +84,27 @@ export async function NCoreInitFramework (
|
||||
|
||||
// 初始化 FFmpeg 服务
|
||||
await FFmpegService.init(pathWrapper.binaryPath, logger);
|
||||
|
||||
// 提前启动 WebUI,使其在登录前可用,支持通过 WebUI 操控登录过程
|
||||
WebUiDataRuntime.setWorkingEnv(NapCatCoreWorkingEnv.Framework);
|
||||
InitWebUi(logger, pathWrapper, logSubscription, statusHelperSubscription).then().catch(e => logger.logError(e));
|
||||
|
||||
// 直到登录成功后,执行下一步
|
||||
// const selfInfo = {
|
||||
// uid: 'u_FUSS0_x06S_9Tf4na_WpUg',
|
||||
// uin: '3684714082',
|
||||
// nick: '',
|
||||
// online: true
|
||||
// }
|
||||
const selfInfo = await new Promise<SelfInfo>((resolve) => {
|
||||
const loginContext = { isLogined: false };
|
||||
|
||||
const loginListener = new NodeIKernelLoginListener();
|
||||
|
||||
loginListener.onUserLoggedIn = (userid: string) => {
|
||||
const tips = `当前账号(${userid})已登录,无法重复登录`;
|
||||
logger.logError(tips);
|
||||
WebUiDataRuntime.setQQLoginError(tips);
|
||||
};
|
||||
|
||||
loginListener.onQRCodeLoginSucceed = async (loginResult) => {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
await new Promise<void>(resolve => {
|
||||
registerInitCallback(() => resolve());
|
||||
});
|
||||
@@ -104,6 +115,47 @@ export async function NCoreInitFramework (
|
||||
online: true,
|
||||
});
|
||||
};
|
||||
|
||||
loginListener.onQRCodeGetPicture = ({ qrcodeUrl }) => {
|
||||
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
|
||||
logger.log('[NapCat] [Framework] 二维码已更新, URL:', qrcodeUrl);
|
||||
};
|
||||
|
||||
loginListener.onQRCodeSessionFailed = (errType: number, errCode: number) => {
|
||||
if (!loginContext.isLogined) {
|
||||
logger.logError('[NapCat] [Framework] [Login] QRCode Session Failed, ErrType:', errType, 'ErrCode:', errCode);
|
||||
if (errType === 1 && errCode === 3) {
|
||||
WebUiDataRuntime.setQQLoginError('二维码已过期,请刷新');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loginListener.onLoginFailed = (...args) => {
|
||||
const errInfo = JSON.stringify(args);
|
||||
logger.logError('[NapCat] [Framework] [Login] Login Failed, ErrInfo:', errInfo);
|
||||
WebUiDataRuntime.setQQLoginError(`登录失败: ${errInfo}`);
|
||||
};
|
||||
|
||||
loginListener.onLoginConnected = () => {
|
||||
logger.log('[NapCat] [Framework] 登录服务已连接');
|
||||
// 注册 WebUI 登录操作回调
|
||||
registerWebUiLoginCallbacks(loginService, loginContext, logger);
|
||||
// 获取历史登录列表供 WebUI 使用
|
||||
loginService.getLoginList().then((res) => {
|
||||
const list = res.LocalLoginInfoList.filter((item) => item.isQuickLogin);
|
||||
WebUiDataRuntime.setQQQuickLoginList(list.map((item) => item.uin.toString()));
|
||||
WebUiDataRuntime.setQQNewLoginList(list);
|
||||
}).catch(e => logger.logError('[NapCat] [Framework] 获取登录列表失败:', e));
|
||||
};
|
||||
|
||||
loginListener.onQRCodeSessionUserScaned = () => {
|
||||
logger.log('[NapCat] [Framework] 二维码已被扫描,等待确认...');
|
||||
};
|
||||
|
||||
loginListener.onPasswordLoginFailed = (...args) => {
|
||||
logger.logError('[NapCat] [Framework] 密码登录失败:', ...args);
|
||||
};
|
||||
|
||||
loginService.addKernelLoginListener(proxiedListenerOf(loginListener, logger));
|
||||
});
|
||||
// 过早进入会导致addKernelMsgListener等Listener添加失败
|
||||
@@ -116,10 +168,8 @@ export async function NCoreInitFramework (
|
||||
}
|
||||
await loaderObject.core.initCore();
|
||||
|
||||
// 启动WebUi
|
||||
WebUiDataRuntime.setWorkingEnv(NapCatCoreWorkingEnv.Framework);
|
||||
// 登录成功后设置数据路径
|
||||
WebUiDataRuntime.setQQDataPath(loaderObject.core.dataPath);
|
||||
InitWebUi(logger, pathWrapper, logSubscription, statusHelperSubscription).then().catch(e => logger.logError(e));
|
||||
|
||||
// // 测试 DatabaseApi
|
||||
// if (dbPassphrase) {
|
||||
@@ -147,6 +197,164 @@ export async function NCoreInitFramework (
|
||||
}
|
||||
}
|
||||
|
||||
function registerWebUiLoginCallbacks (
|
||||
loginService: NodeIKernelLoginService,
|
||||
loginContext: { isLogined: boolean; },
|
||||
logger: LogWrapper
|
||||
) {
|
||||
// 刷新二维码
|
||||
WebUiDataRuntime.setRefreshQRCodeCallback(async () => {
|
||||
loginService.getQRCodePicture();
|
||||
});
|
||||
|
||||
// 快速登录
|
||||
WebUiDataRuntime.setQuickLoginCall(async (uin: string) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!uin) {
|
||||
return resolve({ result: false, message: '快速登录失败' });
|
||||
}
|
||||
logger.log('[NapCat] [Framework] 正在快速登录', uin);
|
||||
loginService.quickLoginWithUin(uin).then(res => {
|
||||
const success = res.result === '0' && !res.loginErrorInfo?.errMsg;
|
||||
if (!success) {
|
||||
const errMsg = res.loginErrorInfo?.errMsg || `快速登录失败,错误码: ${res.result}`;
|
||||
WebUiDataRuntime.setQQLoginError(errMsg);
|
||||
resolve({ result: false, message: errMsg });
|
||||
} else {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
resolve({ result: true, message: '' });
|
||||
}
|
||||
}).catch((e) => {
|
||||
logger.logError('[NapCat] [Framework] 快速登录异常:', e);
|
||||
WebUiDataRuntime.setQQLoginError('快速登录发生错误');
|
||||
resolve({ result: false, message: '快速登录发生错误' });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 密码登录
|
||||
WebUiDataRuntime.setPasswordLoginCall(async (uin: string, passwordMd5: string) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!uin || !passwordMd5) {
|
||||
return resolve({ result: false, message: '密码登录失败:参数不完整' });
|
||||
}
|
||||
logger.log('[NapCat] [Framework] 正在密码登录', uin);
|
||||
loginService.passwordLogin({
|
||||
uin,
|
||||
passwordMd5,
|
||||
step: 0,
|
||||
newDeviceLoginSig: new Uint8Array(),
|
||||
proofWaterSig: new Uint8Array(),
|
||||
proofWaterRand: new Uint8Array(),
|
||||
proofWaterSid: new Uint8Array(),
|
||||
unusualDeviceCheckSig: new Uint8Array(),
|
||||
}).then(res => {
|
||||
if (res.result === '140022008') {
|
||||
const proofWaterUrl = res.loginErrorInfo?.proofWaterUrl || '';
|
||||
resolve({ result: false, message: '需要验证码', needCaptcha: true, proofWaterUrl });
|
||||
} else if (res.result === '140022010' || res.result === '140022011') {
|
||||
const jumpUrl = res.loginErrorInfo?.jumpUrl || '';
|
||||
const newDevicePullQrCodeSig = res.loginErrorInfo?.newDevicePullQrCodeSig || '';
|
||||
resolve({ result: false, message: '新设备需要扫码验证', needNewDevice: true, jumpUrl, newDevicePullQrCodeSig });
|
||||
} else if (res.result !== '0') {
|
||||
const errMsg = res.loginErrorInfo?.errMsg || '密码登录失败';
|
||||
WebUiDataRuntime.setQQLoginError(errMsg);
|
||||
resolve({ result: false, message: errMsg });
|
||||
} else {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
resolve({ result: true, message: '' });
|
||||
}
|
||||
}).catch((e) => {
|
||||
logger.logError('[NapCat] [Framework] 密码登录异常:', e);
|
||||
WebUiDataRuntime.setQQLoginError('密码登录发生错误');
|
||||
resolve({ result: false, message: '密码登录发生错误' });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 验证码登录(密码登录需要验证码时的第二步)
|
||||
WebUiDataRuntime.setCaptchaLoginCall(async (uin: string, passwordMd5: string, ticket: string, randstr: string, sid: string) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!uin || !passwordMd5 || !ticket) {
|
||||
return resolve({ result: false, message: '验证码登录失败:参数不完整' });
|
||||
}
|
||||
logger.log('[NapCat] [Framework] 正在验证码登录', uin);
|
||||
loginService.passwordLogin({
|
||||
uin,
|
||||
passwordMd5,
|
||||
step: 1,
|
||||
newDeviceLoginSig: new Uint8Array(),
|
||||
proofWaterSig: new TextEncoder().encode(ticket),
|
||||
proofWaterRand: new TextEncoder().encode(randstr),
|
||||
proofWaterSid: new TextEncoder().encode(sid),
|
||||
unusualDeviceCheckSig: new Uint8Array(),
|
||||
}).then(res => {
|
||||
if (res.result === '140022010' || res.result === '140022011') {
|
||||
const jumpUrl = res.loginErrorInfo?.jumpUrl || '';
|
||||
const newDevicePullQrCodeSig = res.loginErrorInfo?.newDevicePullQrCodeSig || '';
|
||||
resolve({ result: false, message: '新设备需要扫码验证', needNewDevice: true, jumpUrl, newDevicePullQrCodeSig });
|
||||
} else if (res.result !== '0') {
|
||||
const errMsg = res.loginErrorInfo?.errMsg || '验证码登录失败';
|
||||
WebUiDataRuntime.setQQLoginError(errMsg);
|
||||
resolve({ result: false, message: errMsg });
|
||||
} else {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
resolve({ result: true, message: '' });
|
||||
}
|
||||
}).catch((e) => {
|
||||
logger.logError('[NapCat] [Framework] 验证码登录异常:', e);
|
||||
WebUiDataRuntime.setQQLoginError('验证码登录发生错误');
|
||||
resolve({ result: false, message: '验证码登录发生错误' });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 新设备验证登录(密码登录需要新设备验证时的第二步)
|
||||
WebUiDataRuntime.setNewDeviceLoginCall(async (uin: string, passwordMd5: string, newDevicePullQrCodeSig: string) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!uin || !passwordMd5 || !newDevicePullQrCodeSig) {
|
||||
return resolve({ result: false, message: '新设备验证登录失败:参数不完整' });
|
||||
}
|
||||
logger.log('[NapCat] [Framework] 正在新设备验证登录', uin);
|
||||
loginService.passwordLogin({
|
||||
uin,
|
||||
passwordMd5,
|
||||
step: 2,
|
||||
newDeviceLoginSig: new TextEncoder().encode(newDevicePullQrCodeSig),
|
||||
proofWaterSig: new Uint8Array(),
|
||||
proofWaterRand: new Uint8Array(),
|
||||
proofWaterSid: new Uint8Array(),
|
||||
unusualDeviceCheckSig: new Uint8Array(),
|
||||
}).then(res => {
|
||||
if (res.result === '140022011') {
|
||||
const jumpUrl = res.loginErrorInfo?.jumpUrl || '';
|
||||
const sig = res.loginErrorInfo?.newDevicePullQrCodeSig || '';
|
||||
resolve({ result: false, message: '异常设备需要验证', needNewDevice: true, jumpUrl, newDevicePullQrCodeSig: sig });
|
||||
} else if (res.result !== '0') {
|
||||
const errMsg = res.loginErrorInfo?.errMsg || '新设备验证登录失败';
|
||||
WebUiDataRuntime.setQQLoginError(errMsg);
|
||||
resolve({ result: false, message: errMsg });
|
||||
} else {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
resolve({ result: true, message: '' });
|
||||
}
|
||||
}).catch((e) => {
|
||||
logger.logError('[NapCat] [Framework] 新设备验证登录异常:', e);
|
||||
WebUiDataRuntime.setQQLoginError('新设备验证登录发生错误');
|
||||
resolve({ result: false, message: '新设备验证登录发生错误' });
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export class NapCatFramework {
|
||||
public core: NapCatCore;
|
||||
context: InstanceContext;
|
||||
|
||||
@@ -215,11 +215,11 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
|
||||
uuid?: string,
|
||||
packetMsg: PacketMsg[],
|
||||
deleteAfterSentFiles: string[],
|
||||
innerPacketMsg?: Array<{ uuid: string, packetMsg: PacketMsg[]; }>;
|
||||
innerPacketMsg?: Array<{ uuid: string, packetMsg?: PacketMsg[], actionMsgBody?: UploadForwardMsgParams['actionMsgBody']; }>;
|
||||
} | null> {
|
||||
const packetMsg: PacketMsg[] = [];
|
||||
const delFiles: string[] = [];
|
||||
const innerMsg: Array<{ uuid: string, packetMsg: PacketMsg[]; }> = new Array();
|
||||
const innerMsg: Array<{ uuid: string, packetMsg?: PacketMsg[], actionMsgBody?: UploadForwardMsgParams['actionMsgBody']; }> = new Array();
|
||||
for (const node of messageNodes) {
|
||||
if (dp >= 3) {
|
||||
this.core.context.logger.logWarn('转发消息深度超过3层,将停止解析!');
|
||||
@@ -240,7 +240,7 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
|
||||
if (uploadReturnData?.uuid) {
|
||||
innerMsg.push({ uuid: uploadReturnData.uuid, packetMsg: uploadReturnData.packetMsg });
|
||||
uploadReturnData.innerPacketMsg?.forEach(m => {
|
||||
innerMsg.push({ uuid: m.uuid, packetMsg: m.packetMsg });
|
||||
innerMsg.push(m);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -274,6 +274,37 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
|
||||
const msgCache = await this.core.apis.FileApi.downloadRawMsgMedia([msg]);
|
||||
delFiles.push(...msgCache);
|
||||
const transformedMsg = this.core.apis.PacketApi.pkt.msgConverter.rawMsgToPacketMsg(msg, msgPeer);
|
||||
// 检测嵌套合并转发消息,拉取内层protobuf数据
|
||||
for (const element of msg.elements) {
|
||||
let resId: string | undefined;
|
||||
let uuid: string | undefined;
|
||||
if (element.multiForwardMsgElement?.resId) {
|
||||
resId = element.multiForwardMsgElement.resId;
|
||||
uuid = element.multiForwardMsgElement.fileName;
|
||||
} else if (element.arkElement?.bytesData) {
|
||||
try {
|
||||
const json = JSON.parse(element.arkElement.bytesData);
|
||||
if (json.app === 'com.tencent.multimsg') {
|
||||
resId = json.meta?.detail?.resid;
|
||||
uuid = json.meta?.detail?.uniseq || json.extra?.filename;
|
||||
}
|
||||
} catch { /* not a valid json */ }
|
||||
}
|
||||
if (resId && uuid) {
|
||||
try {
|
||||
const rawActions = await this.core.apis.PacketApi.pkt.operation.FetchForwardMsgRaw(resId);
|
||||
for (const action of rawActions) {
|
||||
if (action.actionCommand === 'MultiMsg') {
|
||||
innerMsg.push({ uuid, actionMsgBody: action.actionData.msgBody });
|
||||
} else {
|
||||
innerMsg.push({ uuid: action.actionCommand, actionMsgBody: action.actionData.msgBody });
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
this.core.context.logger.logError(`获取合并转发内层消息失败: ${(e as Error)?.stack}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.core.context.logger.logDebug(`handleForwardedNodesPacket[PureRaw] 转换为 ${stringifyWithBigInt(transformedMsg)}`);
|
||||
packetMsg.push(transformedMsg);
|
||||
}
|
||||
@@ -289,10 +320,11 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
|
||||
actionCommand: 'MultiMsg',
|
||||
actionMsg: packetMsg,
|
||||
}];
|
||||
innerMsg.forEach(({ uuid, packetMsg: msg }) => {
|
||||
innerMsg.forEach(({ uuid, packetMsg: msg, actionMsgBody: raw }) => {
|
||||
uploadMsgData.push({
|
||||
actionCommand: uuid,
|
||||
actionMsg: msg,
|
||||
actionMsgBody: raw,
|
||||
});
|
||||
});
|
||||
const resid = await this.core.apis.PacketApi.pkt.operation.UploadForwardMsgV2(uploadMsgData, msgPeer.chatType === ChatType.KCHATTYPEGROUP ? +msgPeer.peerUid : 0);
|
||||
|
||||
@@ -85,7 +85,7 @@ export const lastestMessageSchema = Type.Object({
|
||||
}, { $id: 'OB11LatestMessage', description: '最后一条消息' });
|
||||
|
||||
export const OB11MessageSchema = Type.Intersect([
|
||||
lastestMessageSchema,
|
||||
Type.Omit(lastestMessageSchema, []),
|
||||
Type.Object({
|
||||
message_id: Type.Number({ description: '消息ID' }),
|
||||
message_seq: Type.Number({ description: '消息序列号' }),
|
||||
|
||||
@@ -384,6 +384,26 @@ export class OneBotMsgApi {
|
||||
this.core.context.logger.logError('所有查找方法均失败,获取不到旧客户端的引用消息', element.replayMsgSeq);
|
||||
}
|
||||
|
||||
// 协议兜底:尝试通过协议直接获取消息
|
||||
if (this.core.apis.PacketApi.packetStatus) {
|
||||
try {
|
||||
const msgSeq = +element.replayMsgSeq;
|
||||
const fetchedMsgs = msg.chatType === ChatType.KCHATTYPEGROUP
|
||||
? await this.core.apis.PacketApi.pkt.operation.FetchGroupMessage(+msg.peerUin, msgSeq, msgSeq)
|
||||
: await this.core.apis.PacketApi.pkt.operation.FetchC2CMessage(msg.peerUid, msgSeq, msgSeq);
|
||||
|
||||
const targetMsg = fetchedMsgs.find(m => (m.contentHead.sequence ?? 0) === msgSeq);
|
||||
if (targetMsg?.contentHead?.newId) {
|
||||
const msgId = String(targetMsg.contentHead.newId);
|
||||
this.core.context.logger.logWarn('通过协议兜底成功获取引用消息', msgId);
|
||||
return createReplyData(msgId);
|
||||
}
|
||||
this.core.context.logger.logWarn('协议兜底未找到匹配的引用消息');
|
||||
} catch (e) {
|
||||
this.core.context.logger.logError('协议兜底获取引用消息失败', (e as Error).stack);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
videoElement: async (element, msg, elementWrapper, { disableGetUrl }) => {
|
||||
|
||||
@@ -94,7 +94,7 @@ export const OB11MessageFileBaseSchema = Type.Object({
|
||||
export const OB11MessageImageSchema = Type.Object({
|
||||
type: Type.Literal(OB11MessageDataType.image),
|
||||
data: Type.Intersect([
|
||||
FileBaseDataSchema,
|
||||
Type.Omit(FileBaseDataSchema, []),
|
||||
Type.Object({
|
||||
summary: Type.Optional(Type.String({ description: '图片摘要' })),
|
||||
sub_type: Type.Optional(Type.Number({ description: '图片子类型' })),
|
||||
|
||||
@@ -581,6 +581,9 @@ export async function NCoreInitShell () {
|
||||
console.log('NapCat Shell App Loading...');
|
||||
const pathWrapper = new NapCatPathWrapper();
|
||||
const logger = new LogWrapper(pathWrapper.logsPath);
|
||||
if (process.env['NAPCAT_WORKER_PROCESS'] !== '1' && process.env['NAPCAT_DISABLE_MULTI_PROCESS'] !== '1') {
|
||||
logger.setFileLogEnabled(false);
|
||||
}
|
||||
handleUncaughtExceptions(logger);
|
||||
await applyPendingUpdates(pathWrapper, logger);
|
||||
|
||||
|
||||
@@ -52,6 +52,9 @@ interface WorkerMessage {
|
||||
|
||||
|
||||
const logger = new LogWrapper(pathWrapper.logsPath);
|
||||
if (!ENV.isWorkerProcess && !ENV.isMultiProcessDisabled) {
|
||||
logger.setFileLogEnabled(false);
|
||||
}
|
||||
|
||||
// 进程管理器和当前 Worker 进程引用
|
||||
let processManager: IProcessManager | null = null;
|
||||
|
||||
+1
-10
@@ -1,11 +1,2 @@
|
||||
packages:
|
||||
- packages/*
|
||||
|
||||
onlyBuiltDependencies:
|
||||
- '@heroui/shared-utils'
|
||||
- '@homebridge/node-pty-prebuilt-multiarch'
|
||||
- '@swc/core'
|
||||
- esbuild
|
||||
- sharp
|
||||
- ttf2woff2
|
||||
- unrs-resolver
|
||||
- packages/*
|
||||
Reference in new issue
Block a user