refactor: packet x1

This commit is contained in:
pk5ls20
2024-11-12 04:02:19 +08:00
parent af29c17814
commit 7fd94a03b7
105 changed files with 2286 additions and 1962 deletions

View File

@@ -28,7 +28,7 @@ export class GetAiCharacters extends GetPacketStatusDepends<Payload, GetAiCharac
payloadSchema = SchemaData;
async _handle(payload: Payload) {
const rawList = await this.core.apis.PacketApi.sendFetchAiVoiceListReq(+payload.group_id, +(payload.chat_type ?? 1) as AIVoiceChatType);
const rawList = await this.core.apis.PacketApi.pkt.operation.FetchAiVoiceList(+payload.group_id, +(payload.chat_type ?? 1) as AIVoiceChatType);
return rawList?.map((item) => ({
type: item.category,
characters: item.voices.map((voice) => ({

View File

@@ -1,8 +1,8 @@
import { ActionName } from '../types';
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { GetPacketStatusDepends } from "@/onebot/action/packet/GetPacketStatus";
import { MiniAppInfo, MiniAppInfoHelper } from "@/core/packet/utils/helper/miniAppHelper";
import { MiniAppData, MiniAppRawData, MiniAppReqCustomParams, MiniAppReqParams } from "@/core/packet/entities/miniApp";
import { MiniAppInfo, MiniAppInfoHelper } from "@/core/packet/helper/miniAppHelper";
const SchemaData = {
type: 'object',
@@ -77,7 +77,7 @@ export class GetMiniAppArk extends GetPacketStatusDepends<Payload, {
}
);
}
const arkData = await this.core.apis.PacketApi.sendMiniAppShareInfoReq(reqParam);
const arkData = await this.core.apis.PacketApi.pkt.operation.GetMiniAppAdaptShareInfo(reqParam);
return {
data: payload.rawArkData ? arkData : MiniAppInfoHelper.RawToSend(arkData)
};

View File

@@ -6,6 +6,6 @@ export class GetRkey extends GetPacketStatusDepends<null, Array<any>> {
actionName = ActionName.GetRkey;
async _handle() {
return await this.core.apis.PacketApi.sendRkeyPacket();
return await this.core.apis.PacketApi.pkt.operation.FetchRkey();
}
}

View File

@@ -17,6 +17,6 @@ export class GetUserStatus extends GetPacketStatusDepends<Payload, { status: num
payloadSchema = SchemaData;
async _handle(payload: Payload) {
return await this.core.apis.PacketApi.sendStatusPacket(+payload.user_id);
return await this.core.apis.PacketApi.pkt.operation.GetStrangerStatus(+payload.user_id);
}
}

View File

@@ -17,9 +17,9 @@ export class SetGroupSign extends BaseAction<Payload, any> {
payloadSchema = SchemaData;
async _handle(payload: Payload) {
return await this.core.apis.PacketApi.sendGroupSignPacket(payload.group_id.toString());
return await this.core.apis.PacketApi.pkt.operation.GroupSign(+payload.group_id);
}
}
export class SendGroupSign extends SetGroupSign {
actionName = ActionName.SendGroupSign;
}
}

View File

@@ -20,6 +20,6 @@ export class SetSpecialTittle extends GetPacketStatusDepends<Payload, any> {
async _handle(payload: Payload) {
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
if(!uid) throw new Error('User not found');
await this.core.apis.PacketApi.sendSetSpecialTittlePacket(payload.group_id.toString(), uid, payload.special_title);
await this.core.apis.PacketApi.pkt.operation.SetGroupSpecialTitle(+payload.group_id, uid, payload.special_title);
}
}

View File

@@ -26,7 +26,7 @@ export class GetGroupFileUrl extends GetPacketStatusDepends<Payload, GetGroupFil
const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);
if (contextMsgFile?.fileUUID) {
return {
url: await this.core.apis.PacketApi.sendGroupFileDownloadReq(+payload.group_id, contextMsgFile.fileUUID)
url: await this.core.apis.PacketApi.pkt.operation.GetGroupFileUrl(+payload.group_id, contextMsgFile.fileUUID)
};
}
throw new Error('real fileUUID not found!');

View File

@@ -20,7 +20,7 @@ export class GetAiRecord extends GetPacketStatusDepends<Payload, string> {
payloadSchema = SchemaData;
async _handle(payload: Payload) {
const rawRsp = await this.core.apis.PacketApi.sendAiVoiceChatReq(+payload.group_id, payload.character, payload.text, AIVoiceChatType.Sound);
return await this.core.apis.PacketApi.sendGroupPttFileDownloadReq(+payload.group_id, rawRsp.msgInfoBody[0].index);
const rawRsp = await this.core.apis.PacketApi.pkt.operation.GetAiVoice(+payload.group_id, payload.character, payload.text, AIVoiceChatType.Sound);
return await this.core.apis.PacketApi.pkt.operation.GetGroupPttUrl(+payload.group_id, rawRsp.msgInfoBody[0].index);
}
}

View File

@@ -18,6 +18,6 @@ export class GroupPoke extends GetPacketStatusDepends<Payload, any> {
payloadSchema = SchemaData;
async _handle(payload: Payload) {
await this.core.apis.PacketApi.sendPokePacket(+payload.user_id, +payload.group_id);
await this.core.apis.PacketApi.pkt.operation.GroupPoke(+payload.user_id, +payload.group_id);
}
}

View File

@@ -1,9 +1,9 @@
import { ActionName } from '../types';
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { GetPacketStatusDepends } from "@/onebot/action/packet/GetPacketStatus";
import { AIVoiceChatType } from "@/core/packet/entities/aiChat";
import { uri2local } from "@/common/file";
import { ChatType, Peer } from "@/core";
import { AIVoiceChatType } from "@/core/packet/entities/aiChat";
const SchemaData = {
type: 'object',
@@ -24,8 +24,8 @@ export class SendGroupAiRecord extends GetPacketStatusDepends<Payload, {
payloadSchema = SchemaData;
async _handle(payload: Payload) {
const rawRsp = await this.core.apis.PacketApi.sendAiVoiceChatReq(+payload.group_id, payload.character, payload.text, AIVoiceChatType.Sound);
const url = await this.core.apis.PacketApi.sendGroupPttFileDownloadReq(+payload.group_id, rawRsp.msgInfoBody[0].index);
const rawRsp = await this.core.apis.PacketApi.pkt.operation.GetAiVoice(+payload.group_id, payload.character, payload.text, AIVoiceChatType.Sound);
const url = await this.core.apis.PacketApi.pkt.operation.GetGroupPttUrl(+payload.group_id, rawRsp.msgInfoBody[0].index);
const { path, fileName, errMsg, success } = (await uri2local(this.core.NapCatTempPath, url));
if (!success) {
throw new Error(errMsg);

View File

@@ -18,11 +18,11 @@ type PlayloadType = FromSchema<typeof SchemaData>;
class MarkMsgAsRead extends BaseAction<PlayloadType, null> {
async getPeer(payload: PlayloadType): Promise<Peer> {
if (payload.message_id) {
let s_peer = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id)?.Peer;
const s_peer = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id)?.Peer;
if (s_peer) {
return s_peer;
}
let l_peer = MessageUnique.getPeerByMsgId(payload.message_id.toString())?.Peer;
const l_peer = MessageUnique.getPeerByMsgId(payload.message_id.toString())?.Peer;
if (l_peer) {
return l_peer;
}

View File

@@ -11,10 +11,10 @@ import { decodeCQCode } from '@/onebot/cqcode';
import { MessageUnique } from '@/common/message-unique';
import { ChatType, ElementType, NapCatCore, Peer, RawMessage, SendArkElement, SendMessageElement } from '@/core';
import BaseAction from '../BaseAction';
import { rawMsgWithSendMsg } from "@/core/packet/message/converter";
import { PacketMsg } from "@/core/packet/message/message";
import { ForwardMsgBuilder } from "@/common/forward-msg-builder";
import { stringifyWithBigInt } from "@/common/helper";
import { PacketMsg } from "@/core/packet/message/message";
import { rawMsgWithSendMsg } from "@/core/packet/message/converter";
export interface ReturnDataType {
message_id: number;
@@ -192,7 +192,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
msg: sendElements,
};
logger.logDebug(`handleForwardedNodesPacket[SendRaw] 开始转换 ${stringifyWithBigInt(packetMsgElements)}`);
const transformedMsg = this.core.apis.PacketApi.packetSession?.packer.packetConverter.rawMsgWithSendMsgToPacketMsg(packetMsgElements);
const transformedMsg = this.core.apis.PacketApi.pkt.msgConverter.rawMsgWithSendMsgToPacketMsg(packetMsgElements);
logger.logDebug(`handleForwardedNodesPacket[SendRaw] 转换为 ${stringifyWithBigInt(transformedMsg)}`);
packetMsg.push(transformedMsg!);
} else if (node.data.id) {
@@ -205,7 +205,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(nodeMsg.Peer, [nodeMsg.MsgId])).msgList[0];
logger.logDebug(`handleForwardedNodesPacket[PureRaw] 开始转换 ${stringifyWithBigInt(msg)}`);
await this.core.apis.FileApi.downloadRawMsgMedia([msg]);
const transformedMsg = this.core.apis.PacketApi.packetSession?.packer.packetConverter.rawMsgToPacketMsg(msg, msgPeer);
const transformedMsg = this.core.apis.PacketApi.pkt.msgConverter.rawMsgToPacketMsg(msg, msgPeer);
logger.logDebug(`handleForwardedNodesPacket[PureRaw] 转换为 ${stringifyWithBigInt(transformedMsg)}`);
packetMsg.push(transformedMsg!);
} else {
@@ -216,7 +216,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
logger.logWarn('handleForwardedNodesPacket 元素为空!');
return null;
}
const resid = await this.core.apis.PacketApi.sendUploadForwardMsg(packetMsg, msgPeer.chatType === ChatType.KCHATTYPEGROUP ? +msgPeer.peerUid : 0);
const resid = await this.core.apis.PacketApi.pkt.operation.UploadForwardMsg(packetMsg, msgPeer.chatType === ChatType.KCHATTYPEGROUP ? +msgPeer.peerUid : 0);
const forwardJson = ForwardMsgBuilder.fromPacketMsg(resid, packetMsg, source, news, summary, prompt);
return {
finallySendElements: {

View File

@@ -7,6 +7,7 @@ export abstract class GetPacketStatusDepends<PT, RT> extends BaseAction<PT, RT>
protected async check(payload: PT): Promise<BaseCheckResult>{
if (!this.core.apis.PacketApi.available) {
// TODO: add error stack?
return {
valid: false,
message: "packetBackend不可用请参照文档 https://napneko.github.io/config/advanced 和启动日志检查packetBackend状态或进行配置",

View File

@@ -17,6 +17,6 @@ export class FriendPoke extends GetPacketStatusDepends<Payload, any> {
payloadSchema = SchemaData;
async _handle(payload: Payload) {
await this.core.apis.PacketApi.sendPokePacket(+payload.user_id);
await this.core.apis.PacketApi.pkt.operation.FriendPoke(+payload.user_id);
}
}

View File

@@ -18,13 +18,7 @@ import {
SendTextElement,
} from '@/core';
import faceConfig from '@/core/external/face_config.json';
import {
NapCatOneBot11Adapter,
OB11Message,
OB11MessageData,
OB11MessageDataType,
OB11MessageFileBase,
} from '@/onebot';
import { NapCatOneBot11Adapter, OB11Message, OB11MessageData, OB11MessageDataType, OB11MessageFileBase, } from '@/onebot';
import { OB11Entities } from '@/onebot/entities';
import { EventType } from '@/onebot/event/OB11BaseEvent';
import { encodeCQCode } from '@/onebot/cqcode';
@@ -33,8 +27,9 @@ import { RequestUtil } from '@/common/request';
import fs from 'node:fs';
import fsPromise from 'node:fs/promises';
import { OB11FriendAddNoticeEvent } from '@/onebot/event/notice/OB11FriendAddNoticeEvent';
import { decodeSysMessage } from '@/core/packet/proto/old/ProfileLike';
// import { decodeSysMessage } from '@/core/packet/proto/old/ProfileLike';
import { ForwardMsgBuilder } from "@/common/forward-msg-builder";
import { decodeSysMessage } from "@/core/helper/adaptDecoder";
type RawToOb11Converters = {
[Key in keyof MessageElement as Key extends `${string}Element` ? Key : never]: (
@@ -506,13 +501,12 @@ export class OneBotMsgApi {
// File service
[OB11MessageDataType.image]: async (sendMsg, context) => {
const sendPicElement = await this.core.apis.FileApi.createValidSendPicElement(
return await this.core.apis.FileApi.createValidSendPicElement(
context,
(await this.handleOb11FileLikeMessage(sendMsg, context)).path,
sendMsg.data.summary,
sendMsg.data.sub_type,
);
return sendPicElement;
},
[OB11MessageDataType.file]: async (sendMsg, context) => {
@@ -892,6 +886,7 @@ export class OneBotMsgApi {
return { path, fileName: inputdata.name ?? fileName };
}
async parseSysMessage(msg: number[]) {
const sysMsg = decodeSysMessage(Uint8Array.from(msg));
if (sysMsg.msgSpec.length === 0) {
@@ -900,8 +895,7 @@ export class OneBotMsgApi {
const { msgType, subType, subSubType } = sysMsg.msgSpec[0];
if (msgType === 528 && subType === 39 && subSubType === 39) {
if (!sysMsg.bodyWrapper) return;
const event = await this.obContext.apis.UserApi.parseLikeEvent(sysMsg.bodyWrapper.wrappedBody);
return event;
return await this.obContext.apis.UserApi.parseLikeEvent(sysMsg.bodyWrapper.wrappedBody);
}
/*
if (msgType === 732 && subType === 16 && subSubType === 16) {

View File

@@ -1,8 +1,7 @@
import { NapCatCore } from '@/core';
import { decodeProfileLikeTip } from '@/core/packet/proto/old/ProfileLike';
import { NapCatOneBot11Adapter } from '@/onebot';
import { OB11ProfileLikeEvent } from '../event/notice/OB11ProfileLikeEvent';
import { decodeProfileLikeTip } from "@/core/helper/adaptDecoder";
export class OneBotUserApi {
obContext: NapCatOneBot11Adapter;
@@ -12,6 +11,7 @@ export class OneBotUserApi {
this.obContext = obContext;
this.core = core;
}
async parseLikeEvent(wrappedBody: Uint8Array): Promise<OB11ProfileLikeEvent | undefined> {
const likeTip = decodeProfileLikeTip(Uint8Array.from(wrappedBody));
if (likeTip?.msgType !== 0 || likeTip?.subType !== 203) return;

View File

@@ -46,7 +46,6 @@ import { OB11GroupRecallNoticeEvent } from '@/onebot/event/notice/OB11GroupRecal
import { LRUCache } from '@/common/lru-cache';
import { NodeIKernelRecentContactListener } from '@/core/listeners/NodeIKernelRecentContactListener';
import { Native } from '@/native';
import { decodeMessage, decodeRecallGroup } from '@/core/packet/proto/old/Message';
//OneBot实现类
export class NapCatOneBot11Adapter {
@@ -85,21 +84,22 @@ export class NapCatOneBot11Adapter {
if (!this.nativeCore.inited) throw new Error('Native Not Init');
this.nativeCore.registerRecallCallback(async (hex: string) => {
try {
const data = decodeMessage(Buffer.from(hex, 'hex'));
//data.MsgHead.BodyInner.MsgType SubType
const bodyInner = data.msgHead?.bodyInner;
//context.logger.log("[appNative] Parse MsgType:" + bodyInner.msgType + " / SubType:" + bodyInner.subType);
if (bodyInner && bodyInner.msgType == 732 && bodyInner.subType == 17) {
const RecallData = Buffer.from(data.msgHead.noifyData.innerData);
//跳过 4字节 群号 + 不知道的1字节 +2字节 长度
const uid = RecallData.readUint32BE();
const buffer = Buffer.from(RecallData.toString('hex').slice(14), 'hex');
const seq: number = decodeRecallGroup(buffer).recallDetails.subDetail.msgSeq;
const peer: Peer = { chatType: ChatType.KCHATTYPEGROUP, peerUid: uid.toString() };
context.logger.log("[Native] 群消息撤回 Peer: " + uid.toString() + " / MsgSeq:" + seq);
const msgs = await core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, seq.toString());
this.recallMsgCache.put(msgs.msgList[0].msgId, msgs.msgList[0]);
}
// TODO: refactor!
// const data = decodeMessage(Buffer.from(hex, 'hex'));
// //data.MsgHead.BodyInner.MsgType SubType
// const bodyInner = data.msgHead?.bodyInner;
// //context.logger.log("[appNative] Parse MsgType:" + bodyInner.msgType + " / SubType:" + bodyInner.subType);
// if (bodyInner && bodyInner.msgType == 732 && bodyInner.subType == 17) {
// const RecallData = Buffer.from(data.msgHead.noifyData.innerData);
// //跳过 4字节 群号 + 不知道的1字节 +2字节 长度
// const uid = RecallData.readUint32BE();
// const buffer = Buffer.from(RecallData.toString('hex').slice(14), 'hex');
// const seq: number = decodeRecallGroup(buffer).recallDetails.subDetail.msgSeq;
// const peer: Peer = { chatType: ChatType.KCHATTYPEGROUP, peerUid: uid.toString() };
// context.logger.log("[Native] 群消息撤回 Peer: " + uid.toString() + " / MsgSeq:" + seq);
// const msgs = await core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, seq.toString());
// this.recallMsgCache.put(msgs.msgList[0].msgId, msgs.msgList[0]);
// }
} catch (error: any) {
context.logger.logWarn("[Native] Error:", (error as Error).message, ' HEX:', hex);
}