refactor: packet x1
This commit is contained in:
1 parent
af29c17814
commit
7fd94a03b7
105 files changed
+2286
-1962
No files matched your search
@@ -0,0 +1,82 @@
|
||||
import { PacketContext } from "@/core/packet/context/packetContext";
|
||||
import { IPacketClient } from "@/core/packet/client/baseClient";
|
||||
import { NativePacketClient } from "@/core/packet/client/nativeClient";
|
||||
import { wsPacketClient } from "@/core/packet/client/wsClient";
|
||||
import { OidbPacket } from "@/core/packet/transformer/base";
|
||||
|
||||
type clientPriority = {
|
||||
[key: number]: (context: PacketContext) => IPacketClient;
|
||||
}
|
||||
|
||||
const clientPriority: clientPriority = {
|
||||
10: (context: PacketContext) => new NativePacketClient(context),
|
||||
1: (context: PacketContext) => new wsPacketClient(context),
|
||||
};
|
||||
|
||||
export class PacketClientContext {
|
||||
private readonly _client: IPacketClient;
|
||||
private readonly context: PacketContext;
|
||||
|
||||
constructor(context: PacketContext) {
|
||||
this.context = context;
|
||||
this._client = this.newClient();
|
||||
}
|
||||
|
||||
get available(): boolean {
|
||||
return this._client.available;
|
||||
}
|
||||
|
||||
async init(pid: number, recv: string, send: string): Promise<void> {
|
||||
await this._client.init(pid, recv, send);
|
||||
}
|
||||
|
||||
async sendOidbPacket(pkt: OidbPacket, rsp = false): Promise<Buffer> {
|
||||
console.log("REQ", pkt.cmd, pkt.data);
|
||||
const raw = await this._client.sendOidbPacket(pkt, rsp);
|
||||
console.log("RES", raw.cmd, raw.hex_data);
|
||||
return Buffer.from(raw.hex_data, "hex");
|
||||
}
|
||||
|
||||
private newClient(): IPacketClient {
|
||||
const prefer = this.context.napcore.config.packetBackend;
|
||||
let client: IPacketClient | null;
|
||||
switch (prefer) {
|
||||
case "native":
|
||||
this.context.logger.info("使用指定的 NativePacketClient 作为后端");
|
||||
client = new NativePacketClient(this.context);
|
||||
break;
|
||||
case "frida":
|
||||
this.context.logger.info("[Core] [Packet] 使用指定的 FridaPacketClient 作为后端");
|
||||
client = new wsPacketClient(this.context);
|
||||
break;
|
||||
case "auto":
|
||||
case undefined:
|
||||
client = this.judgeClient();
|
||||
break;
|
||||
default:
|
||||
this.context.logger.error(`未知的PacketBackend ${prefer},请检查配置文件!`);
|
||||
client = null;
|
||||
}
|
||||
if (!(client && client.check())) {
|
||||
throw new Error("[Core] [Packet] 无可用的后端,NapCat.Packet将不会加载!");
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
private judgeClient(): IPacketClient {
|
||||
const sortedClients = Object.entries(clientPriority)
|
||||
.map(([priority, clientFactory]) => {
|
||||
const client = clientFactory(this.context);
|
||||
const score = +priority * +client.check();
|
||||
return { client, score };
|
||||
})
|
||||
.filter(({ score }) => score > 0)
|
||||
.sort((a, b) => b.score - a.score);
|
||||
const selectedClient = sortedClients[0]?.client;
|
||||
if (!selectedClient) {
|
||||
throw new Error("[Core] [Packet] 无可用的后端,NapCat.Packet将不会加载!");
|
||||
}
|
||||
this.context.logger.info(`自动选择 ${selectedClient.constructor.name} 作为后端`);
|
||||
return selectedClient;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { LogLevel, LogWrapper } from "@/common/log";
|
||||
import { PacketContext } from "@/core/packet/context/packetContext";
|
||||
|
||||
// TODO: check bind?
|
||||
export class PacketLogger {
|
||||
private readonly napLogger: LogWrapper;
|
||||
|
||||
constructor(context: PacketContext) {
|
||||
this.napLogger = context.napcore.logger;
|
||||
}
|
||||
|
||||
private _log(level: LogLevel, ...msg: any[]): void {
|
||||
this.napLogger._log(level, "[Core] [Packet] " + msg);
|
||||
}
|
||||
|
||||
debug(...msg: any[]): void {
|
||||
this._log(LogLevel.DEBUG, msg);
|
||||
}
|
||||
|
||||
info(...msg: any[]): void {
|
||||
this._log(LogLevel.INFO, msg);
|
||||
}
|
||||
|
||||
warn(...msg: any[]): void {
|
||||
this._log(LogLevel.WARN, msg);
|
||||
}
|
||||
|
||||
error(...msg: any[]): void {
|
||||
this._log(LogLevel.ERROR, msg);
|
||||
}
|
||||
|
||||
fatal(...msg: any[]): void {
|
||||
this._log(LogLevel.FATAL, msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { NapCatCore } from "@/core";
|
||||
|
||||
export interface NapCoreCompatBasicInfo {
|
||||
readonly uin: number;
|
||||
readonly uid: string;
|
||||
readonly uin2uid: (uin: number) => Promise<string>;
|
||||
readonly uid2uin: (uid: string) => Promise<number>;
|
||||
readonly sendSsoCmdReqByContend: (cmd: string, trace_id: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export class NapCoreContext {
|
||||
private readonly core: NapCatCore;
|
||||
|
||||
constructor(core: NapCatCore) {
|
||||
this.core = core;
|
||||
}
|
||||
|
||||
get logger() {
|
||||
return this.core.context.logger;
|
||||
}
|
||||
|
||||
get basicInfo() {
|
||||
return {
|
||||
uin: +this.core.selfInfo.uin,
|
||||
uid: this.core.selfInfo.uid,
|
||||
uin2uid: (uin: number) => this.core.apis.UserApi.getUidByUinV2(String(uin)).then(res => res ?? ''),
|
||||
uid2uin: (uid: string) => this.core.apis.UserApi.getUinByUidV2(uid).then(res => +res),
|
||||
} as NapCoreCompatBasicInfo;
|
||||
}
|
||||
|
||||
get config() {
|
||||
return this.core.configLoader.configData;
|
||||
}
|
||||
|
||||
sendSsoCmdReqByContend = (cmd: string, trace_id: string) => this.core.context.session.getMsgService().sendSsoCmdReqByContend(cmd, trace_id);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import * as crypto from 'crypto';
|
||||
import { PacketContext } from "@/core/packet/context/packetContext";
|
||||
import * as trans from "@/core/packet/transformer";
|
||||
import { PacketMsg } from "@/core/packet/message/message";
|
||||
import {
|
||||
PacketMsgFileElement,
|
||||
PacketMsgPicElement,
|
||||
PacketMsgPttElement,
|
||||
PacketMsgVideoElement
|
||||
} from "@/core/packet/message/element";
|
||||
import { ChatType } from "@/core";
|
||||
import { MiniAppRawData, MiniAppReqParams } from "@/core/packet/entities/miniApp";
|
||||
import { AIVoiceChatType } from "@/core/packet/entities/aiChat";
|
||||
import { NapProtoDecodeStructType, NapProtoEncodeStructType } from "@napneko/nap-proto-core";
|
||||
import { IndexNode, MsgInfo } from "@/core/packet/transformer/proto";
|
||||
|
||||
export class PacketOperationContext {
|
||||
private context: PacketContext;
|
||||
constructor(context: PacketContext) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
async GroupPoke(groupUin: number, uin: number) {
|
||||
const req = trans.SendPoke.build(groupUin, uin);
|
||||
await this.context.client.sendOidbPacket(req);
|
||||
}
|
||||
|
||||
async FriendPoke(uin: number) {
|
||||
const req = trans.SendPoke.build(uin);
|
||||
await this.context.client.sendOidbPacket(req);
|
||||
}
|
||||
|
||||
async FetchRkey() {
|
||||
const req = trans.FetchRkey.build();
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.FetchRkey.parse(resp);
|
||||
return res.data.rkeyList;
|
||||
}
|
||||
|
||||
async GroupSign(groupUin: number) {
|
||||
const req = trans.GroupSign.build(this.context.napcore.basicInfo.uin, groupUin);
|
||||
await this.context.client.sendOidbPacket(req);
|
||||
}
|
||||
|
||||
async GetStrangerStatus(uin: number) {
|
||||
let status = 0;
|
||||
try {
|
||||
const req = trans.GetStrangerInfo.build(uin);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.GetStrangerInfo.parse(resp);
|
||||
const extBigInt = BigInt(res.data.status.value);
|
||||
if (extBigInt <= 10n) {
|
||||
return { status: Number(extBigInt) * 10, ext_status: 0 };
|
||||
}
|
||||
status = Number((extBigInt & 0xff00n) + ((extBigInt >> 16n) & 0xffn));
|
||||
return { status: 10, ext_status: status };
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async SetGroupSpecialTitle(groupUin: number, uid: string, tittle: string) {
|
||||
const req = trans.SetSpecialTitle.build(groupUin, uid, tittle);
|
||||
await this.context.client.sendOidbPacket(req);
|
||||
}
|
||||
|
||||
async UploadResources(msg: PacketMsg[], groupUin: number = 0) {
|
||||
const reqList = [];
|
||||
for (const m of msg) {
|
||||
for (const e of m.msg) {
|
||||
if (e instanceof PacketMsgPicElement) {
|
||||
reqList.push(this.context.highway.uploadImage({
|
||||
chatType: groupUin ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
|
||||
peerUid: groupUin ? String(groupUin) : this.context.napcore.basicInfo.uid
|
||||
}, e));
|
||||
}
|
||||
if (e instanceof PacketMsgVideoElement) {
|
||||
reqList.push(this.context.highway.uploadVideo({
|
||||
chatType: groupUin ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
|
||||
peerUid: groupUin ? String(groupUin) : this.context.napcore.basicInfo.uid
|
||||
}, e));
|
||||
}
|
||||
if (e instanceof PacketMsgPttElement) {
|
||||
reqList.push(this.context.highway.uploadPtt({
|
||||
chatType: groupUin ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
|
||||
peerUid: groupUin ? String(groupUin) : this.context.napcore.basicInfo.uid
|
||||
}, e));
|
||||
}
|
||||
if (e instanceof PacketMsgFileElement) {
|
||||
reqList.push(this.context.highway.uploadFile({
|
||||
chatType: groupUin ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
|
||||
peerUid: groupUin ? String(groupUin) : this.context.napcore.basicInfo.uid
|
||||
}, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
const res = await Promise.allSettled(reqList);
|
||||
this.context.logger.info(`上传资源${res.length}个,失败${res.filter(r => r.status === 'rejected').length}个`);
|
||||
res.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
this.context.logger.error(`上传第${index + 1}个资源失败:${result.reason.stack}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async UploadForwardMsg(msg: PacketMsg[], groupUin: number = 0) {
|
||||
await this.UploadResources(msg, groupUin);
|
||||
const req = trans.UploadForwardMsg.build(this.context.napcore.basicInfo.uid, msg, groupUin);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.UploadForwardMsg.parse(resp);
|
||||
return res.result.resId;
|
||||
}
|
||||
|
||||
async GetGroupFileUrl(groupUin: number, fileUUID: string) {
|
||||
const req = trans.DownloadGroupFile.build(groupUin, fileUUID);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.DownloadGroupFile.parse(resp);
|
||||
return `https://${res.download.downloadDns}/ftn_handler/${Buffer.from(res.download.downloadUrl).toString('hex')}/?fname=`;
|
||||
}
|
||||
|
||||
// TODO: why type hint is not working here?
|
||||
async GetGroupPttUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
||||
const req = trans.DownloadGroupPtt.build(groupUin, node);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.DownloadGroupPtt.parse(resp);
|
||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
||||
}
|
||||
|
||||
async GetMiniAppAdaptShareInfo(param: MiniAppReqParams) {
|
||||
const req = trans.GetMiniAppAdaptShareInfo.build(param);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.GetMiniAppAdaptShareInfo.parse(resp);
|
||||
return JSON.parse(res.content.jsonContent) as MiniAppRawData;
|
||||
}
|
||||
|
||||
async FetchAiVoiceList(groupUin: number, chatType: AIVoiceChatType) {
|
||||
const req = trans.FetchAiVoiceList.build(groupUin, chatType);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.FetchAiVoiceList.parse(resp);
|
||||
if (!res.content) return null;
|
||||
return res.content.map((item) => {
|
||||
return {
|
||||
category: item.category,
|
||||
voices: item.voices
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async GetAiVoice(groupUin: number, voiceId: string, text: string, chatType: AIVoiceChatType): Promise<NapProtoDecodeStructType<typeof MsgInfo>> {
|
||||
let reqTime = 0;
|
||||
const reqMaxTime = 30;
|
||||
const sessionId = crypto.randomBytes(4).readUInt32BE(0);
|
||||
while (true) {
|
||||
if (reqTime >= reqMaxTime) {
|
||||
throw new Error(`sendAiVoiceChatReq failed after ${reqMaxTime} times`);
|
||||
}
|
||||
reqTime++;
|
||||
const req = trans.GetAiVoice.build(groupUin, voiceId, text, sessionId, chatType);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.GetAiVoice.parse(resp);
|
||||
if (!res.msgInfo) continue;
|
||||
return res.msgInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { PacketHighwayContext } from "@/core/packet/highway/highwayContext";
|
||||
import { NapCatCore } from "@/core";
|
||||
import { PacketLogger } from "@/core/packet/context/loggerContext";
|
||||
import { NapCoreContext } from "@/core/packet/context/napCoreContext";
|
||||
import { PacketClientContext } from "@/core/packet/context/clientContext";
|
||||
import { PacketOperationContext } from "@/core/packet/context/operationContext";
|
||||
import { PacketMsgConverter } from "@/core/packet/message/converter";
|
||||
|
||||
export class PacketContext {
|
||||
readonly napcore: NapCoreContext;
|
||||
readonly logger: PacketLogger;
|
||||
readonly client: PacketClientContext;
|
||||
readonly highway: PacketHighwayContext;
|
||||
readonly msgConverter: PacketMsgConverter;
|
||||
readonly operation: PacketOperationContext;
|
||||
|
||||
constructor(core: NapCatCore) {
|
||||
this.napcore = new NapCoreContext(core);
|
||||
this.logger = new PacketLogger(this);
|
||||
this.client = new PacketClientContext(this);
|
||||
this.highway = new PacketHighwayContext(this);
|
||||
this.msgConverter = new PacketMsgConverter();
|
||||
this.operation = new PacketOperationContext(this);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user