refactor: 整体重构 (#1381)

* feat: pnpm new

* Refactor build and release workflows, update dependencies

Switch build scripts and workflows from npm to pnpm, update build and artifact paths, and simplify release workflow by removing version detection and changelog steps. Add new dependencies (silk-wasm, express, ws, node-pty-prebuilt-multiarch), update exports in package.json files, and add vite config for napcat-framework. Also, rename manifest.json for framework package and fix static asset copying in shell build config.
This commit is contained in:
手瓜一十雪 authored and GitHub committed 2025-11-13 15:39:42 +08:00
1 parent c3d1892545
commit ed19c52f25
778 files changed
+2356 -26391

No files matched your search

@@ -0,0 +1,108 @@
import path, { dirname } from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import { constants } from 'node:os';
import { LogStack } from '@/napcat-core/packet/context/clientContext';
import { NapCoreContext } from '@/napcat-core/packet/context/napCoreContext';
import { PacketLogger } from '@/napcat-core/packet/context/loggerContext';
import { OidbPacket, PacketBuf } from '@/napcat-core/packet/transformer/base';
export interface RecvPacket {
type: string, // 仅recv
data: RecvPacketData;
}
export interface RecvPacketData {
seq: number;
cmd: string;
data: Buffer;
}
// 0 send 1 recv
export interface NativePacketExportType {
initHook?: (send: string, recv: string) => boolean;
}
export class NativePacketClient {
protected readonly napcore: NapCoreContext;
protected readonly logger: PacketLogger;
protected readonly cb = new Map<string, (json: RecvPacketData) => Promise<any> | any>(); // hash-type callback
logStack: LogStack;
available: boolean = false;
private readonly supportedPlatforms = ['win32.x64', 'linux.x64', 'linux.arm64', 'darwin.x64', 'darwin.arm64'];
private readonly MoeHooExport: { exports: NativePacketExportType; } = { exports: {} };
constructor (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) {
this.napcore = napCore;
this.logger = logger;
this.logStack = logStack;
}
check (): boolean {
const platform = process.platform + '.' + process.arch;
if (!this.supportedPlatforms.includes(platform)) {
this.logStack.pushLogWarn(`NativePacketClient: 不支持的平台: ${platform}`);
return false;
}
const moehoo_path = path.join(dirname(fileURLToPath(import.meta.url)), './native/napi2native/napi2native.' + platform + '.node');
if (!fs.existsSync(moehoo_path)) {
this.logStack.pushLogWarn(`NativePacketClient: 缺失运行时文件: ${moehoo_path}`);
return false;
}
return true;
}
async init (_pid: number, recv: string, send: string): Promise<void> {
const platform = process.platform + '.' + process.arch;
const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40824');
if (isNewQQ) {
const moehoo_path = path.join(dirname(fileURLToPath(import.meta.url)), './native/napi2native/napi2native.' + platform + '.node');
process.dlopen(this.MoeHooExport, moehoo_path, constants.dlopen.RTLD_LAZY);
this.MoeHooExport?.exports.initHook?.(send, recv);
this.available = true;
}
}
async sendPacket (
cmd: string,
data: PacketBuf,
rsp = false,
timeout = 5000
): Promise<RecvPacketData> {
if (!rsp) {
this.napcore
.sendSsoCmdReqByContend(cmd, data)
.catch((err: any) =>
this.logger.error(
`[PacketClient] sendPacket 无响应命令发送失败 cmd=${cmd} err=${err}`
)
);
return { seq: 0, cmd, data: Buffer.alloc(0) };
}
const sendPromise = this.napcore
.sendSsoCmdReqByContend(cmd, data)
.then(ret => ({
seq: 0,
cmd,
data: (ret as { rspbuffer: Buffer; }).rspbuffer,
}));
const timeoutPromise = new Promise<RecvPacketData>((_resolve, reject) => {
setTimeout(
() =>
reject(
new Error(
`[PacketClient] sendPacket 超时 cmd=${cmd} timeout=${timeout}ms`
)
),
timeout
);
});
return Promise.race([sendPromise, timeoutPromise]);
}
async sendOidbPacket (pkt: OidbPacket, rsp = false, timeout = 5000): Promise<RecvPacketData> {
return await this.sendPacket(pkt.cmd, pkt.data, rsp, timeout);
}
}
@@ -0,0 +1,31 @@
import { PacketContext } from '@/napcat-core/packet/context/packetContext';
import { NapCatCore } from '@/napcat-core/index';
export class PacketClientSession {
private readonly context: PacketContext;
constructor (core: NapCatCore) {
this.context = new PacketContext(core);
}
init (pid: number, recv: string, send: string): Promise<void> {
return this.context.client.init(pid, recv, send);
}
get clientLogStack () {
return this.context.client.clientLogStack;
}
get available () {
return this.context.client.available;
}
get operation () {
return this.context.operation;
}
// TODO: global message element adapter (?
get msgConverter () {
return this.context.msgConverter;
}
}
@@ -0,0 +1,80 @@
import { NativePacketClient } from '@/napcat-core/packet/client/nativeClient';
import { OidbPacket } from '@/napcat-core/packet/transformer/base';
import { PacketLogger } from '@/napcat-core/packet/context/loggerContext';
import { NapCoreContext } from '@/napcat-core/packet/context/napCoreContext';
export class LogStack {
private stack: string[] = [];
private readonly logger: PacketLogger;
constructor (logger: PacketLogger) {
this.logger = logger;
}
push (msg: string) {
this.stack.push(msg);
}
pushLogInfo (msg: string) {
this.logger.info(msg);
this.stack.push(`${new Date().toISOString()} [INFO] ${msg}`);
}
pushLogWarn (msg: string) {
this.logger.warn(msg);
this.stack.push(`${new Date().toISOString()} [WARN] ${msg}`);
}
pushLogError (msg: string) {
this.logger.error(msg);
this.stack.push(`${new Date().toISOString()} [ERROR] ${msg}`);
}
clear () {
this.stack = [];
}
content () {
return this.stack.join('\n');
}
}
export class PacketClientContext {
private readonly napCore: NapCoreContext;
private readonly logger: PacketLogger;
private readonly logStack: LogStack;
private readonly _client: NativePacketClient;
constructor (napCore: NapCoreContext, logger: PacketLogger) {
this.napCore = napCore;
this.logger = logger;
this.logStack = new LogStack(logger);
this._client = this.newClient();
}
get available (): boolean {
return this._client.available;
}
get clientLogStack (): string {
return this._client.logStack.content();
}
async init (pid: number, recv: string, send: string): Promise<void> {
await this._client.init(pid, recv, send);
}
async sendOidbPacket<T extends boolean = false>(pkt: OidbPacket, rsp?: T, timeout?: number): Promise<T extends true ? Buffer : void> {
const raw = await this._client.sendOidbPacket(pkt, rsp, timeout);
return raw.data as T extends true ? Buffer : void;
}
private newClient (): NativePacketClient {
this.logger.info('使用 NativePacketClient 作为后端');
const client = new NativePacketClient(this.napCore, this.logger, this.logStack);
if (!client.check()) {
throw new Error('[Core] [Packet] NativePacketClient 不可用,NapCat.Packet将不会加载!');
}
return client;
}
}
@@ -0,0 +1,35 @@
import { LogLevel, LogWrapper } from 'napcat-common/src/log';
import { NapCoreContext } from '@/napcat-core/packet/context/napCoreContext';
// TODO: check bind?
export class PacketLogger {
private readonly napLogger: LogWrapper;
constructor (napcore: NapCoreContext) {
this.napLogger = 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,38 @@
import { NapCatCore } from '@/napcat-core/index';
export interface NapCoreCompatBasicInfo {
readonly requireMinNTQQBuild: (buildVer: string) => boolean;
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 {
requireMinNTQQBuild: (buildVer: string) => this.core.context.basicInfoWrapper.requireMinNTQQBuild(buildVer),
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, data: Buffer) => this.core.context.session.getMsgService().sendSsoCmdReqByContend(cmd, data);
}
@@ -0,0 +1,373 @@
import * as crypto from 'crypto';
import { PacketContext } from '@/napcat-core/packet/context/packetContext';
import * as trans from '@/napcat-core/packet/transformer';
import { PacketMsg } from '@/napcat-core/packet/message/message';
import {
PacketMsgFileElement,
PacketMsgPicElement,
PacketMsgPttElement,
PacketMsgReplyElement,
PacketMsgVideoElement,
} from '@/napcat-core/packet/message/element';
import { ChatType, MsgSourceType, NTMsgType, RawMessage } from '@/napcat-core';
import { MiniAppRawData, MiniAppReqParams } from '@/napcat-core/packet/entities/miniApp';
import { AIVoiceChatType } from '@/napcat-core/packet/entities/aiChat';
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
import { IndexNode, LongMsgResult, MsgInfo, PushMsgBody } from '@/napcat-core/packet/transformer/proto';
import { OidbPacket } from '@/napcat-core/packet/transformer/base';
import { ImageOcrResult } from '@/napcat-core/packet/entities/ocrResult';
import { gunzipSync } from 'zlib';
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
export class PacketOperationContext {
private readonly context: PacketContext;
constructor (context: PacketContext) {
this.context = context;
}
async sendPacket<T extends boolean = false>(pkt: OidbPacket, rsp?: T): Promise<T extends true ? Buffer : void> {
return await this.context.client.sendOidbPacket(pkt, rsp);
}
async SendPoke (is_group: boolean, peer: number, target?: number) {
const req = trans.SendPoke.build(is_group, peer, target ?? peer);
await this.context.client.sendOidbPacket(req);
}
async SetGroupTodo (groupUin: number, msgSeq: string) {
const req = trans.SetGroupTodo.build(groupUin, msgSeq);
await this.context.client.sendOidbPacket(req, true);
}
async FetchRkey (timeout: number = 10000) {
const req = trans.FetchRkey.build();
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
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 {
return undefined;
}
}
async SetGroupSpecialTitle (groupUin: number, uid: string, title: string) {
const req = trans.SetSpecialTitle.build(groupUin, uid, title);
await this.context.client.sendOidbPacket(req);
}
async UploadResources (msg: PacketMsg[], groupUin: number = 0) {
const chatType = groupUin ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C;
const peerUid = groupUin ? String(groupUin) : this.context.napcore.basicInfo.uid;
const reqList = msg.flatMap((m) =>
m.msg
.map((e) => {
if (e instanceof PacketMsgPicElement) {
return this.context.highway.uploadImage({ chatType, peerUid }, e);
} else if (e instanceof PacketMsgVideoElement) {
return this.context.highway.uploadVideo({ chatType, peerUid }, e);
} else if (e instanceof PacketMsgPttElement) {
return this.context.highway.uploadPtt({ chatType, peerUid }, e);
} else if (e instanceof PacketMsgFileElement) {
return this.context.highway.uploadFile({ chatType, peerUid }, e);
}
return null;
})
.filter(Boolean)
);
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 UploadImage (img: PacketMsgPicElement) {
await this.context.highway.uploadImage(
{
chatType: ChatType.KCHATTYPEC2C,
peerUid: this.context.napcore.basicInfo.uid,
},
img
);
const index = img.msgInfo?.msgInfoBody?.at(0)?.index;
if (!index) {
throw new Error('img.msgInfo?.msgInfoBody![0].index! is undefined');
}
return await this.GetImageUrl(this.context.napcore.basicInfo.uid, index);
}
async GetImageUrl (selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>) {
const req = trans.DownloadImage.build(selfUid, node);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.DownloadImage.parse(resp);
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
}
async GetPttUrl (selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>, timeout?: number) {
const req = trans.DownloadPtt.build(selfUid, node);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadPtt.parse(resp);
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
}
async GetVideoUrl (selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>, timeout?: number) {
const req = trans.DownloadVideo.build(selfUid, node);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadVideo.parse(resp);
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
}
async GetGroupImageUrl (groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>, timeout?: number) {
const req = trans.DownloadGroupImage.build(groupUin, node);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadImage.parse(resp);
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
}
async GetGroupPttUrl (groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>, timeout?: number) {
const req = trans.DownloadGroupPtt.build(groupUin, node);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadImage.parse(resp);
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
}
async GetGroupVideoUrl (groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>, timeout: number = 20000) {
const req = trans.DownloadGroupVideo.build(groupUin, node);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadImage.parse(resp);
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
}
async ImageOCR (imgUrl: string) {
const req = trans.ImageOCR.build(imgUrl);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.ImageOCR.parse(resp);
return {
texts: res.ocrRspBody.textDetections.map((item) => {
return {
text: item.detectedText,
confidence: item.confidence,
coordinates: item.polygon.coordinates.map((c) => {
return {
x: c.x,
y: c.y,
};
}),
};
}),
language: res.ocrRspBody.language,
} as ImageOcrResult;
}
private async SendPreprocess (msg: PacketMsg[], groupUin: number = 0) {
const ps = msg.map((m) => {
return m.msg.map(async (e) => {
if (e instanceof PacketMsgReplyElement && !e.targetElems) {
this.context.logger.debug('Cannot find reply element\'s targetElems, prepare to fetch it...');
if (!e.targetPeer?.peerUid) {
this.context.logger.error('targetPeer is undefined!');
}
let targetMsg: NapProtoEncodeStructType<typeof PushMsgBody>[] | undefined;
if (e.isGroupReply) {
targetMsg = await this.FetchGroupMessage(+(e.targetPeer?.peerUid ?? 0), e.targetMessageSeq, e.targetMessageSeq);
} else {
targetMsg = await this.FetchC2CMessage(await this.context.napcore.basicInfo.uin2uid(e.targetUin), e.targetMessageSeq, e.targetMessageSeq);
}
e.targetElems = targetMsg.at(0)?.body?.richText?.elems;
e.targetSourceMsg = targetMsg.at(0);
}
});
}).flat();
await Promise.all(ps);
await this.UploadResources(msg, groupUin);
}
async FetchGroupMessage (groupUin: number, startSeq: number, endSeq: number): Promise<NapProtoDecodeStructType<typeof PushMsgBody>[]> {
const req = trans.FetchGroupMessage.build(groupUin, startSeq, endSeq);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.FetchGroupMessage.parse(resp);
return res.body.messages;
}
async FetchC2CMessage (targetUid: string, startSeq: number, endSeq: number): Promise<NapProtoDecodeStructType<typeof PushMsgBody>[]> {
const req = trans.FetchC2CMessage.build(targetUid, startSeq, endSeq);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.FetchC2CMessage.parse(resp);
return res.messages;
}
async UploadForwardMsg (msg: PacketMsg[], groupUin: number = 0) {
await this.SendPreprocess(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 MoveGroupFile (
groupUin: number,
fileUUID: string,
currentParentDirectory: string,
targetParentDirectory: string
) {
const req = trans.MoveGroupFile.build(groupUin, fileUUID, currentParentDirectory, targetParentDirectory);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.MoveGroupFile.parse(resp);
return res.move.retCode;
}
async RenameGroupFile (groupUin: number, fileUUID: string, currentParentDirectory: string, newName: string) {
const req = trans.RenameGroupFile.build(groupUin, fileUUID, currentParentDirectory, newName);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.RenameGroupFile.parse(resp);
return res.rename.retCode;
}
async GetGroupFileUrl (groupUin: number, fileUUID: string, timeout?: number) {
const req = trans.DownloadGroupFile.build(groupUin, fileUUID);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadGroupFile.parse(resp);
return `https://${res.download.downloadDns}/ftn_handler/${Buffer.from(res.download.downloadUrl).toString('hex')}/?fname=`;
}
async GetPrivateFileUrl (self_id: string, fileUUID: string, md5: string, timeout?: number) {
const req = trans.DownloadPrivateFile.build(self_id, fileUUID, md5);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadPrivateFile.parse(resp);
return `http://${res.body?.result?.server}:${res.body?.result?.port}${res.body?.result?.url?.slice(8)}&isthumb=0`;
}
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;
}
}
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);
const res = trans.DownloadForwardMsg.parse(resp);
const inflate = gunzipSync(res.result.payload);
const result = new NapProtoMsg(LongMsgResult).decode(inflate);
const main = result.action.find((r) => r.actionCommand === 'MultiMsg');
if (!main?.actionData.msgBody) {
throw new Error('msgBody is empty');
}
this.context.logger.debug('rawChains ', inflate.toString('hex'));
const messagesPromises = main.actionData.msgBody.map(async (msg) => {
if (!msg?.body?.richText?.elems) {
throw new Error('msg.body.richText.elems is empty');
}
const rawChains = new PacketMsgConverter().packetMsgToRaw(msg?.body?.richText?.elems);
const elements = await Promise.all(
rawChains.map(async ([element, rawElem]) => {
if (element.picElement && rawElem?.commonElem?.pbElem) {
const extra = new NapProtoMsg(MsgInfo).decode(rawElem.commonElem.pbElem);
const index = extra?.msgInfoBody[0]?.index;
if (msg?.responseHead.grp !== undefined) {
const groupUin = msg?.responseHead.grp?.groupUin ?? 0;
element.picElement = {
...element.picElement,
originImageUrl: await this.GetGroupImageUrl(groupUin, index!),
};
} else {
element.picElement = {
...element.picElement,
originImageUrl: await this.GetImageUrl(this.context.napcore.basicInfo.uid, index!),
};
}
return element;
}
return element;
})
);
return {
chatType: ChatType.KCHATTYPEGROUP,
elements,
guildId: '',
isOnlineMsg: false,
msgId: '7467703692092974645', // TODO: no necessary
msgRandom: '0',
msgSeq: String(msg.contentHead.sequence ?? 0),
msgTime: String(msg.contentHead.timeStamp ?? 0),
msgType: NTMsgType.KMSGTYPEMIX,
parentMsgIdList: [],
parentMsgPeer: {
chatType: ChatType.KCHATTYPEGROUP,
peerUid: String(msg?.responseHead.grp?.groupUin ?? 0),
},
peerName: '',
peerUid: '1094950020',
peerUin: '1094950020',
recallTime: '0',
records: [],
sendNickName: msg?.responseHead.grp?.memberName ?? '',
sendRemarkName: msg?.responseHead.grp?.memberName ?? '',
senderUid: '',
senderUin: '1094950020',
sourceType: MsgSourceType.K_DOWN_SOURCETYPE_UNKNOWN,
subMsgType: 1,
};
});
return await Promise.all(messagesPromises);
}
}
@@ -0,0 +1,25 @@
import { PacketHighwayContext } from '@/napcat-core/packet/highway/highwayContext';
import { NapCatCore } from '@/napcat-core';
import { PacketLogger } from '@/napcat-core/packet/context/loggerContext';
import { NapCoreContext } from '@/napcat-core/packet/context/napCoreContext';
import { PacketClientContext } from '@/napcat-core/packet/context/clientContext';
import { PacketOperationContext } from '@/napcat-core/packet/context/operationContext';
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
export class PacketContext {
readonly msgConverter: PacketMsgConverter;
readonly napcore: NapCoreContext;
readonly logger: PacketLogger;
readonly client: PacketClientContext;
readonly highway: PacketHighwayContext;
readonly operation: PacketOperationContext;
constructor (core: NapCatCore) {
this.msgConverter = new PacketMsgConverter();
this.napcore = new NapCoreContext(core);
this.logger = new PacketLogger(this.napcore);
this.client = new PacketClientContext(this.napcore, this.logger);
this.highway = new PacketHighwayContext(this.napcore, this.logger, this.client);
this.operation = new PacketOperationContext(this);
}
}
@@ -0,0 +1,16 @@
export enum AIVoiceChatType {
Unknown = 0,
Sound = 1,
Sing = 2,
}
export interface AIVoiceItem {
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
}
export interface AIVoiceItemList {
category: string;
voices: AIVoiceItem[];
}
@@ -0,0 +1,80 @@
export interface MiniAppReqCustomParams {
title: string;
desc: string;
picUrl: string;
jumpUrl: string;
webUrl?: string;
}
export interface MiniAppReqTemplateParams {
sdkId: string;
appId: string;
scene: number;
iconUrl: string;
templateType: number;
businessType: number;
verType: number;
shareType: number;
versionId: string;
withShareTicket: number;
}
export interface MiniAppReqParams extends MiniAppReqCustomParams, MiniAppReqTemplateParams {}
export interface MiniAppData {
ver: string;
prompt: string;
config: Config;
app: string;
view: string;
meta: MetaData;
miniappShareOrigin: number;
miniappOpenRefer: string;
}
export interface MiniAppRawData {
appName: string;
appView: string;
ver: string;
desc: string;
prompt: string;
metaData: MetaData;
config: Config;
}
interface Config {
type: string;
width: number;
height: number;
forward: number;
autoSize: number;
ctime: number;
token: string;
}
interface Host {
uin: number;
nick: string;
}
interface Detail {
appid: string;
appType: number;
title: string;
desc: string;
icon: string;
preview: string;
url: string;
scene: number;
host: Host;
shareTemplateId: string;
shareTemplateData: Record<string, unknown>;
showLittleTail: string;
gamePoints: string;
gamePointsUrl: string;
shareOrigin: number;
}
interface MetaData {
detail_1: Detail;
}
@@ -0,0 +1,15 @@
export interface ImageOcrResult {
texts: TextDetection[];
language: string;
}
export interface TextDetection {
text: string;
confidence: number;
coordinates: Coordinate[];
}
export interface Coordinate {
x: number;
y: number;
}
@@ -0,0 +1,227 @@
import path, { dirname } from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import { constants } from 'node:os';
import { LogWrapper } from 'napcat-common/src/log';
import offset from '@/napcat-core/external/packet.json';
interface OffsetType {
[key: string]: {
recv: string;
send: string;
};
}
const typedOffset: OffsetType = offset;
// 0 send 1 recv
export interface NativePacketExportType {
initHook?: (send: string, recv: string, callback: (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => void, o3_hook: boolean) => boolean;
}
export type PacketType = 0 | 1; // 0: send, 1: recv
export type PacketCallback = (data: { type: PacketType, uin: string, cmd: string, seq: number, hex_data: string; }) => void;
interface ListenerEntry {
callback: PacketCallback;
once: boolean;
}
export class NativePacketHandler {
private readonly supportedPlatforms = ['win32.x64', 'linux.x64', 'linux.arm64', 'darwin.x64', 'darwin.arm64'];
private readonly MoeHooExport: { exports: NativePacketExportType; } = { exports: {} };
protected readonly logger: LogWrapper;
private loaded: boolean = false;
// 统一的监听器存储 - key: 'all' | 'type:0' | 'type:1' | 'cmd:xxx' | 'exact:type:cmd'
private readonly listeners: Map<string, Set<ListenerEntry>> = new Map();
constructor ({ logger }: { logger: LogWrapper; }) {
this.logger = logger;
try {
const platform = process.platform + '.' + process.arch;
const moehoo_path = path.join(dirname(fileURLToPath(import.meta.url)), './native/packet/MoeHoo.' + platform + '.node');
if (!fs.existsSync(moehoo_path)) {
this.logger.logWarn(`NativePacketClient: 缺失运行时文件: ${moehoo_path}`);
this.loaded = false;
}
process.dlopen(this.MoeHooExport, moehoo_path, constants.dlopen.RTLD_LAZY);
this.loaded = true;
this.logger.log('[PacketHandler] 加载成功');
} catch (error) {
this.logger.logError('NativePacketClient 加载出错:', error);
this.loaded = false;
}
}
/**
* 添加监听器的通用方法
*/
private addListener (key: string, callback: PacketCallback, once: boolean = false): () => void {
if (!this.listeners.has(key)) {
this.listeners.set(key, new Set());
}
const entry: ListenerEntry = { callback, once };
this.listeners.get(key)!.add(entry);
return () => this.removeListener(key, callback);
}
/**
* 移除监听器的通用方法
*/
private removeListener (key: string, callback: PacketCallback): boolean {
const entries = this.listeners.get(key);
if (!entries) return false;
for (const entry of entries) {
if (entry.callback === callback) {
return entries.delete(entry);
}
}
return false;
}
// ===== 永久监听器 =====
/** 监听所有数据包 */
onAll (callback: PacketCallback): () => void {
return this.addListener('all', callback);
}
/** 监听特定类型的数据包 (0: send, 1: recv) */
onType (type: PacketType, callback: PacketCallback): () => void {
return this.addListener(`type:${type}`, callback);
}
/** 监听所有发送的数据包 */
onSend (callback: PacketCallback): () => void {
return this.onType(0, callback);
}
/** 监听所有接收的数据包 */
onRecv (callback: PacketCallback): () => void {
return this.onType(1, callback);
}
/** 监听特定cmd的数据包(不限type) */
onCmd (cmd: string, callback: PacketCallback): () => void {
return this.addListener(`cmd:${cmd}`, callback);
}
/** 监听特定type和cmd的数据包(精确匹配) */
onExact (type: PacketType, cmd: string, callback: PacketCallback): () => void {
return this.addListener(`exact:${type}:${cmd}`, callback);
}
// ===== 一次性监听器 =====
/** 一次性监听所有数据包 */
onceAll (callback: PacketCallback): () => void {
return this.addListener('all', callback, true);
}
/** 一次性监听特定类型的数据包 */
onceType (type: PacketType, callback: PacketCallback): () => void {
return this.addListener(`type:${type}`, callback, true);
}
/** 一次性监听所有发送的数据包 */
onceSend (callback: PacketCallback): () => void {
return this.onceType(0, callback);
}
/** 一次性监听所有接收的数据包 */
onceRecv (callback: PacketCallback): () => void {
return this.onceType(1, callback);
}
/** 一次性监听特定cmd的数据包 */
onceCmd (cmd: string, callback: PacketCallback): () => void {
return this.addListener(`cmd:${cmd}`, callback, true);
}
/** 一次性监听特定type和cmd的数据包 */
onceExact (type: PacketType, cmd: string, callback: PacketCallback): () => void {
return this.addListener(`exact:${type}:${cmd}`, callback, true);
}
// ===== 移除监听器 =====
/** 移除特定的全局监听器 */
off (key: string, callback: PacketCallback): boolean {
return this.removeListener(key, callback);
}
/** 移除特定key下的所有监听器 */
offAll (key: string): void {
this.listeners.delete(key);
}
/** 移除所有监听器 */
removeAllListeners (): void {
this.listeners.clear();
}
/**
* 触发监听器 - 按优先级触发: 精确匹配 > cmd匹配 > type匹配 > 全局
*/
private emitPacket (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string): void {
const keys = [
`exact:${type}:${cmd}`, // 精确匹配
`cmd:${cmd}`, // cmd匹配
`type:${type}`, // type匹配
'all', // 全局
];
for (const key of keys) {
const entries = this.listeners.get(key);
if (!entries) continue;
const toRemove: ListenerEntry[] = [];
for (const entry of entries) {
try {
entry.callback({ type, uin, cmd, seq, hex_data });
if (entry.once) {
toRemove.push(entry);
}
} catch (error) {
this.logger.logError('监听器回调执行出错:', error);
}
}
// 移除一次性监听器
for (const entry of toRemove) {
entries.delete(entry);
}
}
}
async init (version: string): Promise<boolean> {
const version_arch = version + '-' + process.arch;
try {
if (!this.loaded) {
this.logger.logWarn('NativePacketClient 未成功加载,无法初始化');
return false;
}
const send = typedOffset[version_arch]?.send;
const recv = typedOffset[version_arch]?.recv;
if (!send || !recv) {
this.logger.logWarn(`NativePacketClient: 未找到对应版本的偏移数据: ${version_arch}`);
return false;
}
const platform = process.platform + '.' + process.arch;
if (!this.supportedPlatforms.includes(platform)) {
this.logger.logWarn(`NativePacketClient: 不支持的平台: ${platform}`);
return false;
}
this.MoeHooExport.exports.initHook?.(send, recv, (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => {
this.emitPacket(type, uin, cmd, seq, hex_data);
}, true);
this.logger.log('[PacketHandler] 初始化成功');
return true;
} catch (error) {
this.logger.logError('NativePacketClient 初始化出错:', error);
return false;
}
}
}
@@ -0,0 +1,73 @@
import * as stream from 'node:stream';
import { ReadStream } from 'node:fs';
import { HighwayTcpUploader } from '@/napcat-core/packet/highway/uploader/highwayTcpUploader';
import { HighwayHttpUploader } from '@/napcat-core/packet/highway/uploader/highwayHttpUploader';
import { PacketHighwaySig } from '@/napcat-core/packet/highway/highwayContext';
import { PacketLogger } from '@/napcat-core/packet/context/loggerContext';
export interface PacketHighwayTrans {
uin: string;
cmd: number;
command: string;
data: stream.Readable;
sum: Uint8Array;
size: number;
ticket: Uint8Array;
loginSig?: Uint8Array;
ext: Uint8Array;
encrypt: boolean;
timeout?: number;
server: string;
port: number;
}
export class PacketHighwayClient {
sig: PacketHighwaySig;
server: string = 'htdata3.qq.com';
port: number = 80;
logger: PacketLogger;
constructor (sig: PacketHighwaySig, logger: PacketLogger, _server: string = 'htdata3.qq.com', _port: number = 80) {
this.sig = sig;
this.logger = logger;
}
changeServer (server: string, port: number) {
this.server = server;
this.port = port;
}
private buildDataUpTrans (cmd: number, data: ReadStream, fileSize: number, md5: Uint8Array, extendInfo: Uint8Array, timeout: number = 1200): PacketHighwayTrans {
return {
uin: this.sig.uin,
cmd,
command: 'PicUp.DataUp',
data,
sum: md5,
size: fileSize,
ticket: this.sig.sigSession!,
ext: extendInfo,
encrypt: false,
timeout,
server: this.server,
port: this.port,
} as PacketHighwayTrans;
}
async upload (cmd: number, data: ReadStream, fileSize: number, md5: Uint8Array, extendInfo: Uint8Array): Promise<void> {
const trans = this.buildDataUpTrans(cmd, data, fileSize, md5, extendInfo);
try {
const tcpUploader = new HighwayTcpUploader(trans, this.logger);
await tcpUploader.upload();
} catch (e) {
this.logger.error(`[Highway] upload failed: ${e}, fallback to http upload`);
try {
const httpUploader = new HighwayHttpUploader(trans, this.logger);
await httpUploader.upload();
} catch (e) {
this.logger.error(`[Highway] http upload failed: ${e}`);
throw e;
}
}
}
}
@@ -0,0 +1,23 @@
import assert from 'node:assert';
export class Frame {
static pack (head: Buffer, body: Buffer): Buffer {
const totalLength = 9 + head.length + body.length + 1;
const buffer = Buffer.allocUnsafe(totalLength);
buffer[0] = 0x28;
buffer.writeUInt32BE(head.length, 1);
buffer.writeUInt32BE(body.length, 5);
head.copy(buffer, 9);
body.copy(buffer, 9 + head.length);
buffer[totalLength - 1] = 0x29;
return buffer;
}
static unpack (frame: Buffer): [Buffer, Buffer] {
assert(frame[0] === 0x28 && frame[frame.length - 1] === 0x29, 'Invalid frame!');
const headLen = frame.readUInt32BE(1);
const bodyLen = frame.readUInt32BE(5);
// assert(frame.length === 9 + headLen + bodyLen + 1, `Frame ${frame.toString('hex')} length does not match head and body lengths!`);
return [frame.subarray(9, 9 + headLen), frame.subarray(9 + headLen, 9 + headLen + bodyLen)];
}
}
@@ -0,0 +1,542 @@
import { PacketHighwayClient } from '@/napcat-core/packet/highway/client';
import { PacketLogger } from '@/napcat-core/packet/context/loggerContext';
import FetchSessionKey from '@/napcat-core/packet/transformer/highway/FetchSessionKey';
import { int32ip2str, oidbIpv4s2HighwayIpv4s } from '@/napcat-core/packet/highway/utils';
import {
PacketMsgFileElement,
PacketMsgPicElement,
PacketMsgPttElement,
PacketMsgVideoElement,
} from '@/napcat-core/packet/message/element';
import { ChatType, Peer } from '@/napcat-core/index';
import { calculateSha1, calculateSha1StreamBytes, computeMd5AndLengthWithLimit } from '@/napcat-core/packet/utils/crypto/hash';
import UploadGroupImage from '@/napcat-core/packet/transformer/highway/UploadGroupImage';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import * as proto from '@/napcat-core/packet/transformer/proto';
import * as trans from '@/napcat-core/packet/transformer';
import fs from 'fs';
import { NapCoreContext } from '@/napcat-core/packet/context/napCoreContext';
import { PacketClientContext } from '@/napcat-core/packet/context/clientContext';
export const BlockSize = 1024 * 1024;
interface HighwayServerAddr {
ip: string;
port: number;
}
export interface PacketHighwaySig {
uin: string;
uid: string;
sigSession: Uint8Array | null;
sessionKey: Uint8Array | null;
serverAddr: HighwayServerAddr[];
}
export class PacketHighwayContext {
private readonly napcore: NapCoreContext;
private readonly client: PacketClientContext;
protected sig: PacketHighwaySig;
protected logger: PacketLogger;
protected hwClient: PacketHighwayClient;
private cachedPrepareReq: Promise<void> | null = null;
constructor (napcore: NapCoreContext, logger: PacketLogger, client: PacketClientContext) {
this.napcore = napcore;
this.client = client;
this.sig = {
uin: String(this.napcore.basicInfo.uin),
uid: this.napcore.basicInfo.uid,
sigSession: null,
sessionKey: null,
serverAddr: [],
};
this.logger = logger;
this.hwClient = new PacketHighwayClient(this.sig, this.logger);
}
private async checkAvailable () {
if (this.sig.sigSession === null || this.sig.sessionKey === null) {
if (this.cachedPrepareReq === null) {
this.cachedPrepareReq = this.prepareUpload().finally(() => {
this.cachedPrepareReq = null;
});
}
await this.cachedPrepareReq;
}
}
private async prepareUpload (): Promise<void> {
this.logger.debug('[Highway] on prepareUpload!');
const packet = FetchSessionKey.build();
const req = await this.client.sendOidbPacket(packet, true);
const rsp = FetchSessionKey.parse(req);
this.sig.sigSession = rsp.httpConn.sigSession;
this.sig.sessionKey = rsp.httpConn.sessionKey;
for (const info of rsp.httpConn.serverInfos) {
if (info.serviceType !== 1) continue;
for (const addr of info.serverAddrs) {
this.logger.debug(`[Highway PrepareUpload] server addr add: ${int32ip2str(addr.ip)}:${addr.port}`);
this.sig.serverAddr.push({
ip: int32ip2str(addr.ip),
port: addr.port,
});
this.hwClient.changeServer(int32ip2str(addr.ip), addr.port);
}
}
if (this.sig.serverAddr.length === 0) {
this.logger.warn('[Highway PrepareUpload] server addr is empty!');
}
}
async uploadImage (peer: Peer, img: PacketMsgPicElement): Promise<void> {
await this.checkAvailable();
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
await this.uploadGroupImage(+peer.peerUid, img);
} else if (peer.chatType === ChatType.KCHATTYPEC2C) {
await this.uploadC2CImage(peer.peerUid, img);
} else {
throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
}
}
async uploadVideo (peer: Peer, video: PacketMsgVideoElement): Promise<void> {
await this.checkAvailable();
if (+(video.fileSize ?? 0) > 1024 * 1024 * 100) {
throw new Error(`[Highway] 视频文件过大: ${(+(video.fileSize ?? 0) / (1024 * 1024)).toFixed(2)} MB > 100 MB,请使用文件上传!`);
}
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
await this.uploadGroupVideo(+peer.peerUid, video);
} else if (peer.chatType === ChatType.KCHATTYPEC2C) {
await this.uploadC2CVideo(peer.peerUid, video);
} else {
throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
}
}
async uploadPtt (peer: Peer, ptt: PacketMsgPttElement): Promise<void> {
await this.checkAvailable();
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
await this.uploadGroupPtt(+peer.peerUid, ptt);
} else if (peer.chatType === ChatType.KCHATTYPEC2C) {
await this.uploadC2CPtt(peer.peerUid, ptt);
} else {
throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
}
}
async uploadFile (peer: Peer, file: PacketMsgFileElement): Promise<void> {
await this.checkAvailable();
if (peer.chatType === ChatType.KCHATTYPEGROUP) {
await this.uploadGroupFile(+peer.peerUid, file);
} else if (peer.chatType === ChatType.KCHATTYPEC2C) {
await this.uploadC2CFile(peer.peerUid, file);
} else {
throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
}
}
private async uploadGroupImage (groupUin: number, img: PacketMsgPicElement): Promise<void> {
img.sha1 = Buffer.from(await calculateSha1(img.path)).toString('hex');
const req = UploadGroupImage.build(groupUin, img);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = UploadGroupImage.parse(resp);
const ukey = preRespData.upload.uKey;
if (ukey && ukey !== '') {
this.logger.debug(`[Highway] uploadGroupImageReq get upload ukey: ${ukey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
const md5 = Buffer.from(index.info.fileHash, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
hash: {
fileSha1: [sha1],
},
});
await this.hwClient.upload(
1004,
fs.createReadStream(img.path, { highWaterMark: BlockSize }),
img.size,
md5,
extend
);
} else {
this.logger.debug(`[Highway] uploadGroupImageReq get upload invalid ukey ${ukey}, don't need upload!`);
}
img.msgInfo = preRespData.upload.msgInfo;
// img.groupPicExt = new NapProtoMsg(CustomFace).decode(preRespData.tcpUpload.compatQMsg)
}
private async uploadC2CImage (peerUid: string, img: PacketMsgPicElement): Promise<void> {
img.sha1 = Buffer.from(await calculateSha1(img.path)).toString('hex');
const req = trans.UploadPrivateImage.build(peerUid, img);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadPrivateImage.parse(resp);
const ukey = preRespData.upload.uKey;
if (ukey && ukey !== '') {
this.logger.debug(`[Highway] uploadC2CImageReq get upload ukey: ${ukey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
const md5 = Buffer.from(index.info.fileHash, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
hash: {
fileSha1: [sha1],
},
});
await this.hwClient.upload(
1003,
fs.createReadStream(img.path, { highWaterMark: BlockSize }),
img.size,
md5,
extend
);
} else {
this.logger.debug(`[Highway] uploadC2CImageReq get upload invalid ukey ${ukey}, don't need upload!`);
}
img.msgInfo = preRespData.upload.msgInfo;
}
private async uploadGroupVideo (groupUin: number, video: PacketMsgVideoElement): Promise<void> {
if (!video.filePath || !video.thumbPath) throw new Error('video.filePath or video.thumbPath is empty');
video.fileSha1 = Buffer.from(await calculateSha1(video.filePath)).toString('hex');
video.thumbSha1 = Buffer.from(await calculateSha1(video.thumbPath)).toString('hex');
const req = trans.UploadGroupVideo.build(groupUin, video);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadGroupVideo.parse(resp);
const ukey = preRespData.upload.uKey;
if (ukey && ukey !== '') {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video ukey: ${ukey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
hash: {
fileSha1: await calculateSha1StreamBytes(video.filePath),
},
});
await this.hwClient.upload(
1005,
fs.createReadStream(video.filePath, { highWaterMark: BlockSize }),
+video.fileSize!,
md5,
extend
);
} else {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
}
const subFile = preRespData.upload.subFileInfos[0];
if (subFile!.uKey && subFile!.uKey !== '') {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
uKey: subFile!.uKey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
hash: {
fileSha1: [sha1],
},
});
await this.hwClient.upload(
1006,
fs.createReadStream(video.thumbPath, { highWaterMark: BlockSize }),
+video.thumbSize!,
md5,
extend
);
} else {
this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
}
video.msgInfo = preRespData.upload.msgInfo;
}
private async uploadC2CVideo (peerUid: string, video: PacketMsgVideoElement): Promise<void> {
if (!video.filePath || !video.thumbPath) throw new Error('video.filePath or video.thumbPath is empty');
video.fileSha1 = Buffer.from(await calculateSha1(video.filePath)).toString('hex');
video.thumbSha1 = Buffer.from(await calculateSha1(video.thumbPath)).toString('hex');
const req = trans.UploadPrivateVideo.build(peerUid, video);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadPrivateVideo.parse(resp);
const ukey = preRespData.upload.uKey;
if (ukey && ukey !== '') {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video ukey: ${ukey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
hash: {
fileSha1: await calculateSha1StreamBytes(video.filePath),
},
});
await this.hwClient.upload(
1001,
fs.createReadStream(video.filePath, { highWaterMark: BlockSize }),
+video.fileSize!,
md5,
extend
);
} else {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
}
const subFile = preRespData.upload.subFileInfos[0];
if (subFile!.uKey && subFile!.uKey !== '') {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile!.uKey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[1]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
uKey: subFile!.uKey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(subFile!.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
hash: {
fileSha1: [sha1],
},
});
await this.hwClient.upload(
1002,
fs.createReadStream(video.thumbPath, { highWaterMark: BlockSize }),
+video.thumbSize!,
md5,
extend
);
} else {
this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile!.uKey}, don't need upload!`);
}
video.msgInfo = preRespData.upload.msgInfo;
}
private async uploadGroupPtt (groupUin: number, ptt: PacketMsgPttElement): Promise<void> {
ptt.fileSha1 = Buffer.from(await calculateSha1(ptt.filePath)).toString('hex');
const req = trans.UploadGroupPtt.build(groupUin, ptt);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadGroupPtt.parse(resp);
const ukey = preRespData.upload.uKey;
if (ukey && ukey !== '') {
this.logger.debug(`[Highway] uploadGroupPttReq get upload ptt ukey: ${ukey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
hash: {
fileSha1: [sha1],
},
});
await this.hwClient.upload(
1008,
fs.createReadStream(ptt.filePath, { highWaterMark: BlockSize }),
ptt.fileSize,
md5,
extend
);
} else {
this.logger.debug(`[Highway] uploadGroupPttReq get upload invalid ukey ${ukey}, don't need upload!`);
}
ptt.msgInfo = preRespData.upload.msgInfo;
}
private async uploadC2CPtt (peerUid: string, ptt: PacketMsgPttElement): Promise<void> {
ptt.fileSha1 = Buffer.from(await calculateSha1(ptt.filePath)).toString('hex');
const req = trans.UploadPrivatePtt.build(peerUid, ptt);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadPrivatePtt.parse(resp);
const ukey = preRespData.upload.uKey;
if (ukey && ukey !== '') {
this.logger.debug(`[Highway] uploadC2CPttReq get upload ptt ukey: ${ukey}, need upload!`);
const index = preRespData.upload.msgInfo.msgInfoBody[0]!.index;
const md5 = Buffer.from(index.info.fileHash, 'hex');
const sha1 = Buffer.from(index.info.fileSha1, 'hex');
const extend = new NapProtoMsg(proto.NTV2RichMediaHighwayExt).encode({
fileUuid: index.fileUuid,
uKey: ukey,
network: {
ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S),
},
msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
blockSize: BlockSize,
hash: {
fileSha1: [sha1],
},
});
await this.hwClient.upload(
1007,
fs.createReadStream(ptt.filePath, { highWaterMark: BlockSize }),
ptt.fileSize,
md5,
extend
);
} else {
this.logger.debug(`[Highway] uploadC2CPttReq get upload invalid ukey ${ukey}, don't need upload!`);
}
ptt.msgInfo = preRespData.upload.msgInfo;
}
private async uploadGroupFile (groupUin: number, file: PacketMsgFileElement): Promise<void> {
file.isGroupFile = true;
file.fileMd5 = await computeMd5AndLengthWithLimit(file.filePath);
file.fileSha1 = await calculateSha1(file.filePath);
const req = trans.UploadGroupFile.build(groupUin, file);
const resp = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadGroupFile.parse(resp);
if (!preRespData?.upload?.boolFileExist) {
this.logger.debug('[Highway] uploadGroupFileReq file not exist, need upload!');
const ext = new NapProtoMsg(proto.FileUploadExt).encode({
unknown1: 100,
unknown2: 1,
entry: {
busiBuff: {
senderUin: BigInt(this.sig.uin),
receiverUin: BigInt(groupUin),
groupCode: BigInt(groupUin),
},
fileEntry: {
fileSize: BigInt(file.fileSize),
md5: file.fileMd5,
md5S2: file.fileMd5,
checkKey: preRespData.upload.checkKey,
fileId: preRespData.upload.fileId,
uploadKey: preRespData.upload.fileKey,
},
clientInfo: {
clientType: 3,
appId: '100',
terminalType: 3,
clientVer: '1.1.1',
unknown: 4,
},
fileNameInfo: {
fileName: file.fileName,
},
host: {
hosts: [
{
url: {
host: preRespData.upload.uploadIp,
unknown: 1,
},
port: preRespData.upload.uploadPort,
},
],
},
},
unknown200: 0,
});
await this.hwClient.upload(
71,
fs.createReadStream(file.filePath, { highWaterMark: BlockSize }),
file.fileSize,
file.fileMd5,
ext
);
} else {
this.logger.debug('[Highway] uploadGroupFileReq file exist, don\'t need upload!');
}
file.fileUuid = preRespData.upload.fileId;
}
private async uploadC2CFile (peerUid: string, file: PacketMsgFileElement): Promise<void> {
file.isGroupFile = false;
file.fileMd5 = await computeMd5AndLengthWithLimit(file.filePath);
file.fileSha1 = await calculateSha1(file.filePath);
const req = await trans.UploadPrivateFile.build(this.sig.uid, peerUid, file);
const res = await this.client.sendOidbPacket(req, true);
const preRespData = trans.UploadPrivateFile.parse(res);
if (!preRespData.upload?.boolFileExist) {
this.logger.debug('[Highway] uploadC2CFileReq file not exist, need upload!');
const ext = new NapProtoMsg(proto.FileUploadExt).encode({
unknown1: 100,
unknown2: 1,
entry: {
busiBuff: {
senderUin: BigInt(this.sig.uin),
},
fileEntry: {
fileSize: BigInt(file.fileSize),
md5: file.fileMd5,
md5S2: file.fileMd5,
checkKey: file.fileSha1,
fileId: preRespData.upload?.uuid,
uploadKey: preRespData.upload?.mediaPlatformUploadKey,
},
clientInfo: {
clientType: 3,
appId: '100',
terminalType: 3,
clientVer: '1.1.1',
unknown: 4,
},
fileNameInfo: {
fileName: file.fileName,
},
host: {
hosts: [
{
url: {
host: preRespData.upload?.uploadIp,
unknown: 1,
},
port: preRespData.upload?.uploadPort,
},
],
},
},
unknown200: 1,
unknown3: 0,
});
await this.hwClient.upload(
95,
fs.createReadStream(file.filePath, { highWaterMark: BlockSize }),
file.fileSize,
file.fileMd5,
ext
);
}
file.fileUuid = preRespData.upload?.uuid;
file.fileHash = preRespData.upload?.fileAddon;
const fileExistReq = trans.DownloadOfflineFile.build(file.fileUuid!, file.fileHash!, this.sig.uid, peerUid);
const fileExistRes = await this.client.sendOidbPacket(fileExistReq, true);
file._e37_800_rsp = trans.DownloadOfflineFile.parse(fileExistRes);
file._private_send_uid = this.sig.uid;
file._private_recv_uid = peerUid;
}
}
@@ -0,0 +1,75 @@
import crypto from 'node:crypto';
import http from 'node:http';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { IHighwayUploader } from '@/napcat-core/packet/highway/uploader/highwayUploader';
import { Frame } from '@/napcat-core/packet/highway/frame';
import * as proto from '@/napcat-core/packet/transformer/proto';
export class HighwayHttpUploader extends IHighwayUploader {
async upload (): Promise<void> {
const controller = new AbortController();
const { signal } = controller;
const upload = (async () => {
let offset = 0;
for await (const chunk of this.trans.data) {
if (signal.aborted) {
throw new Error('Upload aborted due to timeout');
}
const block = chunk as Buffer;
try {
await this.uploadBlock(block, offset);
} catch (err) {
throw new Error(`[Highway] httpUpload Error uploading block at offset ${offset}: ${err}`);
}
offset += block.length;
}
})();
const timeout = this.timeout().catch((err) => {
controller.abort();
throw new Error(err.message);
});
await Promise.race([upload, timeout]);
}
private async uploadBlock (block: Buffer, offset: number): Promise<void> {
const chunkMD5 = crypto.createHash('md5').update(block).digest();
const payload = this.buildPicUpHead(offset, block.length, chunkMD5);
const frame = Frame.pack(Buffer.from(payload), block);
const resp = await this.httpPostHighwayContent(frame, `http://${this.trans.server}:${this.trans.port}/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${this.trans.uin}`);
const [head, body] = Frame.unpack(resp);
const headData = new NapProtoMsg(proto.RespDataHighwayHead).decode(head);
this.logger.debug(`[Highway] httpUploadBlock: ${headData.errorCode} | ${headData.msgSegHead?.retCode} | ${headData.bytesRspExtendInfo} | ${head.toString('hex')} | ${body.toString('hex')}`);
if (headData.errorCode !== 0) throw new Error(`[Highway] httpUploadBlock failed (code=${headData.errorCode})`);
}
private async httpPostHighwayContent (frame: Buffer, serverURL: string): Promise<Buffer> {
return new Promise((resolve, reject) => {
try {
const options: http.RequestOptions = {
method: 'POST',
headers: {
Connection: 'keep-alive',
'Accept-Encoding': 'identity',
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)',
'Content-Length': frame.length.toString(),
},
};
const req = http.request(serverURL, options, (res) => {
const data: Buffer[] = [];
res.on('data', (chunk) => {
data.push(chunk);
});
res.on('end', () => {
resolve(Buffer.concat(data));
});
});
req.write(frame);
req.on('error', (error: Error) => {
reject(error);
});
} catch (error: unknown) {
reject(new Error((error as Error).message));
}
});
}
}
@@ -0,0 +1,86 @@
import net from 'node:net';
import stream from 'node:stream';
import crypto from 'node:crypto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { BlockSize } from '@/napcat-core/packet/highway/highwayContext';
import { Frame } from '@/napcat-core/packet/highway/frame';
import { IHighwayUploader } from '@/napcat-core/packet/highway/uploader/highwayUploader';
import * as proto from '@/napcat-core/packet/transformer/proto';
class HighwayTcpUploaderTransform extends stream.Transform {
uploader: HighwayTcpUploader;
offset: number;
constructor (uploader: HighwayTcpUploader) {
super();
this.uploader = uploader;
this.offset = 0;
}
override _transform (data: Buffer, _: BufferEncoding, callback: stream.TransformCallback) {
let chunkOffset = 0;
while (chunkOffset < data.length) {
const chunkSize = Math.min(BlockSize, data.length - chunkOffset);
const chunk = data.subarray(chunkOffset, chunkOffset + chunkSize);
const chunkMd5 = crypto.createHash('md5').update(chunk).digest();
const head = this.uploader.buildPicUpHead(this.offset, chunk.length, chunkMd5);
chunkOffset += chunk.length;
this.offset += chunk.length;
this.push(Frame.pack(Buffer.from(head), chunk));
}
callback(null);
}
}
export class HighwayTcpUploader extends IHighwayUploader {
async upload (): Promise<void> {
const controller = new AbortController();
const { signal } = controller;
const upload = new Promise<void>((resolve, reject) => {
const highwayTransForm = new HighwayTcpUploaderTransform(this);
const socket = net.connect(this.trans.port, this.trans.server, () => {
this.trans.data.pipe(highwayTransForm).pipe(socket, { end: false });
});
const handleRspHeader = (header: Buffer) => {
const rsp = new NapProtoMsg(proto.RespDataHighwayHead).decode(header);
if (rsp.errorCode !== 0) {
socket.end();
reject(new Error(`[Highway] tcpUpload failed (code=${rsp.errorCode})`));
}
const percent = ((Number(rsp.msgSegHead?.dataOffset) + Number(rsp.msgSegHead?.dataLength)) / Number(rsp.msgSegHead?.filesize)).toFixed(2);
this.logger.debug(`[Highway] tcpUpload ${rsp.errorCode} | ${percent} | ${Buffer.from(header).toString('hex')}`);
if (Number(rsp.msgSegHead?.dataOffset) + Number(rsp.msgSegHead?.dataLength) >= Number(rsp.msgSegHead?.filesize)) {
this.logger.debug('[Highway] tcpUpload finished.');
socket.end();
resolve();
}
};
socket.on('data', (chunk: Buffer) => {
if (signal.aborted) {
socket.end();
reject(new Error('Upload aborted due to timeout'));
}
const [head, _] = Frame.unpack(chunk);
handleRspHeader(head);
});
socket.on('close', () => {
this.logger.debug('[Highway] tcpUpload socket closed.');
resolve();
});
socket.on('error', (err) => {
socket.end();
reject(new Error(`[Highway] tcpUpload socket.on error: ${err}`));
});
this.trans.data.on('error', (err) => {
socket.end();
reject(new Error(`[Highway] tcpUpload readable error: ${err}`));
});
});
const timeout = this.timeout().catch((err) => {
controller.abort();
throw new Error(err.message);
});
await Promise.race([upload, timeout]);
}
}
@@ -0,0 +1,64 @@
// import * as tea from '@/napcat-core/packet/utils/crypto/tea';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { PacketHighwayTrans } from '@/napcat-core/packet/highway/client';
import { PacketLogger } from '@/napcat-core/packet/context/loggerContext';
import * as proto from '@/napcat-core/packet/transformer/proto';
export abstract class IHighwayUploader {
readonly trans: PacketHighwayTrans;
readonly logger: PacketLogger;
constructor (trans: PacketHighwayTrans, logger: PacketLogger) {
this.trans = trans;
this.logger = logger;
}
// TODO: 没用到的加密方法先注释掉
// private encryptTransExt (key: Uint8Array) {
// if (!this.trans.encrypt) return;
// this.trans.ext = tea.encrypt(Buffer.from(this.trans.ext), Buffer.from(key));
// }
protected timeout (): Promise<void> {
return new Promise<void>((_resolve, reject) => {
setTimeout(() => {
reject(new Error(`[Highway] timeout after ${this.trans.timeout}s`));
}, (this.trans.timeout ?? Infinity) * 1000
);
});
}
buildPicUpHead (offset: number, bodyLength: number, bodyMd5: Uint8Array): Uint8Array {
return new NapProtoMsg(proto.ReqDataHighwayHead).encode({
msgBaseHead: {
version: 1,
uin: this.trans.uin,
command: 'PicUp.DataUp',
seq: 0,
retryTimes: 0,
appId: 1600001604,
dataFlag: 16,
commandId: this.trans.cmd,
},
msgSegHead: {
serviceId: 0,
filesize: BigInt(this.trans.size),
dataOffset: BigInt(offset),
dataLength: bodyLength,
serviceTicket: this.trans.ticket,
md5: bodyMd5,
fileMd5: this.trans.sum,
cacheAddr: 0,
cachePort: 0,
},
bytesReqExtendInfo: this.trans.ext,
timestamp: BigInt(0),
msgLoginSigHead: {
uint32LoginSigType: 8,
appId: 1600001604,
},
});
}
abstract upload (): Promise<void>;
}
@@ -0,0 +1,19 @@
import { NapProtoEncodeStructType } from '@napneko/nap-proto-core';
import * as proto from '@/napcat-core/packet/transformer/proto';
export const int32ip2str = (ip: number) => {
ip = ip & 0xffffffff;
return [ip & 0xff, (ip & 0xff00) >> 8, (ip & 0xff0000) >> 16, ((ip & 0xff000000) >> 24) & 0xff].join('.');
};
export const oidbIpv4s2HighwayIpv4s = (ipv4s: NapProtoEncodeStructType<typeof proto.IPv4>[]): NapProtoEncodeStructType<typeof proto.NTHighwayIPv4>[] => {
return ipv4s.map((ip) => {
return {
domain: {
isEnable: true,
ip: int32ip2str(ip.outIP ?? 0),
},
port: ip.outPort!,
} as NapProtoEncodeStructType<typeof proto.NTHighwayIPv4>;
});
};
@@ -0,0 +1,70 @@
import * as crypto from 'crypto';
import { PushMsgBody } from '@/napcat-core/packet/transformer/proto';
import { NapProtoEncodeStructType } from '@napneko/nap-proto-core';
import { PacketMsg, PacketSendMsgElement } from '@/napcat-core/packet/message/message';
import { IPacketMsgElement, PacketMsgTextElement } from '@/napcat-core/packet/message/element';
import { SendTextElement } from '@/napcat-core/index';
export class PacketMsgBuilder {
protected static failBackText = new PacketMsgTextElement(
{
textElement: { content: '[该消息类型暂不支持查看]' },
} as SendTextElement
);
buildFakeMsg (selfUid: string, element: PacketMsg[]): NapProtoEncodeStructType<typeof PushMsgBody>[] {
return element.map((node): NapProtoEncodeStructType<typeof PushMsgBody> => {
const avatar = `https://q.qlogo.cn/headimg_dl?dst_uin=${node.senderUin}&spec=640&img_type=jpg`;
const msgContent = node.msg.reduceRight((acc: undefined | Uint8Array, msg: IPacketMsgElement<PacketSendMsgElement>) => {
return acc ?? msg.buildContent();
}, undefined);
const msgElement = node.msg.flatMap(msg => msg.buildElement() ?? []);
if (!msgContent && !msgElement.length) {
msgElement.push(PacketMsgBuilder.failBackText.buildElement());
}
return {
responseHead: {
fromUin: node.senderUin,
type: 0,
sigMap: 0,
toUin: 0,
fromUid: '',
forward: node.groupId
? undefined
: {
friendName: node.senderName,
},
toUid: node.groupId ? undefined : selfUid,
grp: node.groupId
? {
groupUin: node.groupId,
memberName: node.senderName,
unknown5: 2,
}
: undefined,
},
contentHead: {
type: node.groupId ? 82 : 9,
subType: node.groupId ? undefined : 4,
divSeq: node.groupId ? undefined : 4,
autoReply: 0,
sequence: crypto.randomBytes(4).readUInt32LE(0),
timeStamp: +node.time.toString().substring(0, 10),
forward: {
field1: 0,
field2: 0,
field3: node.groupId ? 1 : 2,
unknownBase64: avatar,
avatar,
},
},
body: {
richText: {
elems: msgElement,
},
msgContent,
},
};
});
}
}
@@ -0,0 +1,171 @@
import {
ChatType,
ElementType,
MessageElement,
Peer,
RawMessage,
SendArkElement,
SendFaceElement,
SendFileElement,
SendMarkdownElement,
SendMarketFaceElement,
SendMultiForwardMsgElement,
SendPicElement,
SendPttElement,
SendReplyElement,
SendTextElement,
SendVideoElement,
} from '@/napcat-core/index';
import {
IPacketMsgElement,
PacketMsgAtElement,
PacketMsgFaceElement,
PacketMsgFileElement,
PacketMsgLightAppElement,
PacketMsgMarkDownElement,
PacketMsgMarkFaceElement,
PacketMsgPicElement,
PacketMsgPttElement,
PacketMsgReplyElement,
PacketMsgTextElement,
PacketMsgVideoElement,
PacketMultiMsgElement,
} from '@/napcat-core/packet/message/element';
import { PacketMsg, PacketSendMsgElement } from '@/napcat-core/packet/message/message';
import { NapProtoDecodeStructType } from '@napneko/nap-proto-core';
import { Elem } from '@/napcat-core/packet/transformer/proto';
const SupportedElementTypes = [
ElementType.TEXT,
ElementType.PIC,
ElementType.REPLY,
ElementType.FACE,
ElementType.MFACE,
ElementType.VIDEO,
ElementType.FILE,
ElementType.PTT,
ElementType.ARK,
ElementType.MARKDOWN,
ElementType.MULTIFORWARD,
];
type SendMessageTypeElementMap = {
[ElementType.TEXT]: SendTextElement,
[ElementType.PIC]: SendPicElement,
[ElementType.FILE]: SendFileElement,
[ElementType.PTT]: SendPttElement,
[ElementType.VIDEO]: SendVideoElement,
[ElementType.FACE]: SendFaceElement,
[ElementType.REPLY]: SendReplyElement,
[ElementType.ARK]: SendArkElement,
[ElementType.MFACE]: SendMarketFaceElement,
[ElementType.MULTIFORWARD]: SendMultiForwardMsgElement,
[ElementType.MARKDOWN]: SendMarkdownElement,
};
type ElementToPacketMsgConverters = {
[K in keyof SendMessageTypeElementMap]: (
sendElement: MessageElement
) => IPacketMsgElement<SendMessageTypeElementMap[K]>;
};
export type rawMsgWithSendMsg = {
senderUin: number;
senderUid?: string;
senderName: string;
groupId?: number;
time: number;
msg: PacketSendMsgElement[]
};
// TODO: make it become adapter?
export class PacketMsgConverter {
private isValidElementType (type: ElementType): type is keyof ElementToPacketMsgConverters {
return SupportedElementTypes.includes(type);
}
private readonly rawToPacketMsgConverters: ElementToPacketMsgConverters = {
[ElementType.TEXT]: (element) => {
if (element.textElement?.atType) {
return new PacketMsgAtElement(element as SendTextElement);
}
return new PacketMsgTextElement(element as SendTextElement);
},
[ElementType.PIC]: (element) => {
return new PacketMsgPicElement(element as SendPicElement);
},
[ElementType.REPLY]: (element) => {
return new PacketMsgReplyElement(element as SendReplyElement);
},
[ElementType.FACE]: (element) => {
return new PacketMsgFaceElement(element as SendFaceElement);
},
[ElementType.MFACE]: (element) => {
return new PacketMsgMarkFaceElement(element as SendMarketFaceElement);
},
[ElementType.VIDEO]: (element) => {
return new PacketMsgVideoElement(element as SendVideoElement);
},
[ElementType.FILE]: (element) => {
return new PacketMsgFileElement(element as SendFileElement);
},
[ElementType.PTT]: (element) => {
return new PacketMsgPttElement(element as SendPttElement);
},
[ElementType.ARK]: (element) => {
return new PacketMsgLightAppElement(element as SendArkElement);
},
[ElementType.MARKDOWN]: (element) => {
return new PacketMsgMarkDownElement(element as SendMarkdownElement);
},
[ElementType.MULTIFORWARD]: (element) => {
return new PacketMultiMsgElement(element as SendMultiForwardMsgElement);
},
};
rawMsgWithSendMsgToPacketMsg (msg: rawMsgWithSendMsg): PacketMsg {
return {
senderUid: msg.senderUid ?? '',
senderUin: msg.senderUin,
senderName: msg.senderName,
groupId: msg.groupId,
time: msg.time,
msg: msg.msg.map((element) => {
if (!this.isValidElementType(element.elementType)) return null;
// @ts-ignore
return this.rawToPacketMsgConverters[element.elementType](element as MessageElement);
}).filter((e) => e !== null),
};
}
rawMsgToPacketMsg (msg: RawMessage, ctxPeer: Peer): PacketMsg {
return {
seq: +msg.msgSeq,
groupId: ctxPeer.chatType === ChatType.KCHATTYPEGROUP ? +msg.peerUid : undefined,
senderUid: msg.senderUid,
senderUin: +msg.senderUin,
senderName: msg.sendMemberName && msg.sendMemberName !== ''
? msg.sendMemberName
: msg.sendNickName && msg.sendNickName !== ''
? msg.sendNickName
: 'QQ用户',
time: +msg.msgTime,
msg: msg.elements.map((element) => {
if (!this.isValidElementType(element.elementType)) return null;
return this.rawToPacketMsgConverters[element.elementType](element);
}).filter((e) => e !== null),
};
}
packetMsgToRaw (msg: NapProtoDecodeStructType<typeof Elem>[]): [MessageElement, NapProtoDecodeStructType<typeof Elem> | null][] {
const converters = [PacketMsgTextElement.parseElement,
PacketMsgAtElement.parseElement, PacketMsgReplyElement.parseElement, PacketMsgPicElement.parseElement];
return msg.map((element) => {
for (const converter of converters) {
const result = converter(element);
if (result) return result;
}
return null;
}).filter((e) => e !== null);
}
}
@@ -0,0 +1,689 @@
import * as zlib from 'node:zlib';
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
import {
CustomFace,
Elem,
FileExtra,
GroupFileExtra,
MarkdownData,
MentionExtra,
MsgInfo,
NotOnlineImage,
OidbSvcTrpcTcp0XE37_800Response,
PushMsgBody,
QBigFaceExtra,
QSmallFaceExtra,
} from '@/napcat-core/packet/transformer/proto';
import {
ElementType,
FaceType,
MessageElement,
NTMsgAtType,
PicType,
SendArkElement,
SendFaceElement,
SendFileElement,
SendMarkdownElement,
SendMarketFaceElement,
SendPicElement,
SendPttElement,
SendReplyElement,
SendMultiForwardMsgElement,
SendTextElement,
SendVideoElement,
Peer,
} from '@/napcat-core';
import { ForwardMsgBuilder } from 'napcat-common/src/forward-msg-builder';
import { PacketMsg, PacketSendMsgElement } from '@/napcat-core/packet/message/message';
export type ParseElementFnR = [MessageElement, NapProtoDecodeStructType<typeof Elem> | null] | undefined;
type ParseElementFn = (elem: NapProtoDecodeStructType<typeof Elem>) => ParseElementFnR;
// raw <-> packet
// TODO: SendStructLongMsgElement
export abstract class IPacketMsgElement<T extends PacketSendMsgElement> {
protected constructor (_rawElement: T) {
}
get valid (): boolean {
return true;
}
buildContent (): Uint8Array | undefined {
return undefined;
}
buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
return [];
}
static parseElement: ParseElementFn;
toPreview (): string {
return '[暂不支持该消息类型喵~]';
}
}
export class PacketMsgTextElement extends IPacketMsgElement<SendTextElement> {
text: string;
constructor (element: SendTextElement) {
super(element);
this.text = element.textElement.content;
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
return [{
text: {
str: this.text,
},
}];
}
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
if (elem.text?.str && (elem.text?.attr6Buf === undefined || elem.text?.attr6Buf?.length === 0)) {
return [{
textElement: {
content: elem.text?.str,
atType: NTMsgAtType.ATTYPEUNKNOWN,
atUid: '',
atTinyId: '',
atNtUid: '',
},
elementType: ElementType.UNKNOWN,
elementId: '',
}, null];
}
return undefined;
};
override toPreview (): string {
return this.text;
}
}
export class PacketMsgAtElement extends PacketMsgTextElement {
targetUid: string;
atAll: boolean;
constructor (element: SendTextElement) {
super(element);
this.targetUid = element.textElement.atNtUid;
this.atAll = element.textElement.atType === NTMsgAtType.ATTYPEALL;
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
return [{
text: {
str: this.text,
pbReserve: new NapProtoMsg(MentionExtra).encode({
type: this.atAll ? 1 : 2,
uin: 0,
field5: 0,
uid: this.targetUid,
}
),
},
}];
}
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
if (elem.text?.str && (elem.text?.attr6Buf?.length ?? 100) >= 11) {
return [{
textElement: {
content: elem.text?.str,
atType: NTMsgAtType.ATTYPEONE,
atUid: String(Buffer.from(elem.text!.attr6Buf!).readUInt32BE(7)), // FIXME: hack
atTinyId: '',
atNtUid: '',
},
elementType: ElementType.UNKNOWN,
elementId: '',
}, null];
}
return undefined;
};
}
export class PacketMsgReplyElement extends IPacketMsgElement<SendReplyElement> {
time: number;
targetMessageId: bigint;
targetMessageSeq: number;
targetMessageClientSeq: number;
targetUin: number;
targetUid: string;
targetElems?: NapProtoEncodeStructType<typeof Elem>[];
targetSourceMsg?: NapProtoEncodeStructType<typeof PushMsgBody>;
targetPeer?: Peer;
constructor (element: SendReplyElement) {
super(element);
this.time = +(element.replyElement.replyMsgTime ?? Math.floor(Date.now() / 1000));
this.targetMessageId = BigInt(element.replyElement.replayMsgId ?? 0);
this.targetMessageSeq = +(element.replyElement.replayMsgSeq ?? 0);
this.targetMessageClientSeq = +(element.replyElement.replyMsgClientSeq ?? 0);
this.targetUin = +(element.replyElement.senderUin ?? 0);
this.targetUid = element.replyElement.senderUidStr ?? '';
this.targetPeer = element.replyElement._replyMsgPeer;
}
get isGroupReply (): boolean {
return this.targetMessageClientSeq === 0;
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
return [{
srcMsg: {
origSeqs: [this.isGroupReply ? this.targetMessageSeq : this.targetMessageClientSeq],
senderUin: BigInt(this.targetUin),
time: this.time,
elems: this.targetElems ?? [],
sourceMsg: new NapProtoMsg(PushMsgBody).encode(this.targetSourceMsg ?? {}),
toUin: BigInt(0),
},
}];
}
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
if (elem.srcMsg && elem.srcMsg.pbReserve) {
const reserve = elem.srcMsg.pbReserve;
return [{
replyElement: {
replayMsgSeq: String(reserve.friendSeq ?? elem.srcMsg?.origSeqs?.[0] ?? 0),
replayMsgId: String(reserve.messageId ?? 0),
senderUin: String(elem?.srcMsg ?? 0),
},
elementType: ElementType.UNKNOWN,
elementId: '',
}, null];
}
return undefined;
};
override toPreview (): string {
return '[回复消息]';
}
}
export class PacketMsgFaceElement extends IPacketMsgElement<SendFaceElement> {
faceId: number;
isLargeFace: boolean;
resultId?: string;
constructor (element: SendFaceElement) {
super(element);
this.faceId = element.faceElement.faceIndex;
this.resultId = element.faceElement.resultId;
this.isLargeFace = element.faceElement.faceType === FaceType.AniSticke;
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
if (this.isLargeFace) {
return [{
commonElem: {
serviceType: 37,
pbElem: new NapProtoMsg(QBigFaceExtra).encode({
aniStickerPackId: '1',
aniStickerId: '8',
faceId: this.faceId,
sourceType: 1,
resultId: this.resultId,
preview: '',
randomType: 1,
}),
businessType: 1,
},
}];
} else if (this.faceId < 260) {
return [{
face: {
index: this.faceId,
},
}];
} else {
return [{
commonElem: {
serviceType: 33,
pbElem: new NapProtoMsg(QSmallFaceExtra).encode({
faceId: this.faceId,
preview: '',
preview2: '',
}),
businessType: 1,
},
}];
}
}
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
if (elem.face?.index) {
return [{
faceElement: {
faceIndex: elem.face.index,
faceType: FaceType.Normal,
},
elementType: ElementType.UNKNOWN,
elementId: '',
}, null];
}
if (elem?.commonElem?.serviceType === 37 && elem?.commonElem?.pbElem) {
const qface = new NapProtoMsg(QBigFaceExtra).decode(elem?.commonElem?.pbElem);
if (qface?.faceId) {
return [{
faceElement: {
faceIndex: qface.faceId,
faceType: FaceType.Normal,
},
elementType: ElementType.UNKNOWN,
elementId: '',
}, null];
}
}
if (elem?.commonElem?.serviceType === 33 && elem?.commonElem?.pbElem) {
const qface = new NapProtoMsg(QSmallFaceExtra).decode(elem?.commonElem?.pbElem);
if (qface?.faceId) {
return [{
faceElement: {
faceIndex: qface.faceId,
faceType: FaceType.Normal,
},
elementType: ElementType.UNKNOWN,
elementId: '',
}, null];
}
}
return undefined;
};
override toPreview (): string {
return '[表情]';
}
}
export class PacketMsgMarkFaceElement extends IPacketMsgElement<SendMarketFaceElement> {
emojiName: string;
emojiId: string;
emojiPackageId: number;
emojiKey: string;
constructor (element: SendMarketFaceElement) {
super(element);
this.emojiName = element.marketFaceElement.faceName;
this.emojiId = element.marketFaceElement.emojiId;
this.emojiPackageId = element.marketFaceElement.emojiPackageId;
this.emojiKey = element.marketFaceElement.key;
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
return [{
marketFace: {
faceName: this.emojiName,
itemType: 6,
faceInfo: 1,
faceId: Buffer.from(this.emojiId, 'hex'),
tabId: this.emojiPackageId,
subType: 3,
key: this.emojiKey,
imageWidth: 300,
imageHeight: 300,
pbReserve: {
field8: 1,
},
},
}];
}
override toPreview (): string {
return `${this.emojiName}`;
}
}
export class PacketMsgPicElement extends IPacketMsgElement<SendPicElement> {
path: string;
name: string;
size: number;
md5: string;
width: number;
height: number;
picType: PicType;
picSubType: number;
summary: string;
sha1: string | null = null;
msgInfo: NapProtoEncodeStructType<typeof MsgInfo> | null = null;
groupPicExt: NapProtoEncodeStructType<typeof CustomFace> | null = null;
c2cPicExt: NapProtoEncodeStructType<typeof NotOnlineImage> | null = null;
constructor (element: SendPicElement) {
super(element);
this.path = element.picElement.sourcePath;
this.name = element.picElement.fileName;
this.size = +element.picElement.fileSize;
this.md5 = element.picElement.md5HexStr ?? '';
this.width = element.picElement.picWidth;
this.height = element.picElement.picHeight;
this.picType = element.picElement.picType;
this.picSubType = element.picElement.picSubType ?? 0;
this.summary = element.picElement.summary === ''
? (
element.picElement.picSubType === 0 ? '[图片]' : '[动画表情]'
)
: element.picElement.summary;
}
override get valid (): boolean {
return !!this.msgInfo;
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
if (!this.msgInfo) return [];
return [{
commonElem: {
serviceType: 48,
pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
businessType: 10,
},
}];
}
static override parseElement = (elem: NapProtoDecodeStructType<typeof Elem>): ParseElementFnR => {
if (elem?.commonElem?.serviceType === 48 || [10, 20].includes(elem?.commonElem?.businessType ?? 0)) {
const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem!.pbElem!);
const msgInfoBody = extra.msgInfoBody[0];
const index = msgInfoBody?.index;
return [{
picElement: {
fileSize: index?.info.fileSize ?? 0,
picWidth: index?.info?.width ?? 0,
picHeight: index?.info?.height ?? 0,
fileName: index?.info?.fileHash ?? '',
sourcePath: '',
original: false,
picType: PicType.NEWPIC_APNG,
fileUuid: '',
fileSubId: '',
thumbFileSize: 0,
summary: '[图片]',
thumbPath: new Map(),
},
elementType: ElementType.UNKNOWN,
elementId: '',
}, elem];
}
if (elem?.notOnlineImage) {
const img = elem?.notOnlineImage; // url in originImageUrl
const preImg: MessageElement = {
picElement: {
fileSize: img.fileLen ?? 0,
picWidth: img.picWidth ?? 0,
picHeight: img.picHeight ?? 0,
fileName: Buffer.from(img.picMd5!).toString('hex') ?? '',
sourcePath: '',
original: false,
picType: PicType.NEWPIC_APNG,
fileUuid: '',
fileSubId: '',
thumbFileSize: 0,
summary: '[图片]',
thumbPath: new Map(),
},
elementType: ElementType.UNKNOWN,
elementId: '',
};
if (img.origUrl?.includes('&fileid=')) {
preImg.picElement!.originImageUrl = `https://multimedia.nt.qq.com.cn${img.origUrl}`;
} else {
preImg.picElement!.originImageUrl = `https://gchat.qpic.cn${img.origUrl}`;
}
return [preImg, elem];
}
return undefined;
};
override toPreview (): string {
return this.summary;
}
}
export class PacketMsgVideoElement extends IPacketMsgElement<SendVideoElement> {
fileSize?: string;
filePath?: string;
thumbSize?: number;
thumbPath?: string;
fileMd5?: string;
fileSha1?: string;
thumbMd5?: string;
thumbSha1?: string;
thumbWidth?: number;
thumbHeight?: number;
msgInfo: NapProtoEncodeStructType<typeof MsgInfo> | null = null;
constructor (element: SendVideoElement) {
super(element);
this.fileSize = element.videoElement.fileSize;
this.filePath = element.videoElement.filePath;
this.thumbSize = element.videoElement.thumbSize;
this.thumbPath = element.videoElement.thumbPath?.get(0) as string | undefined;
this.fileMd5 = element.videoElement.videoMd5;
this.thumbMd5 = element.videoElement.thumbMd5;
this.thumbWidth = element.videoElement.thumbWidth;
this.thumbHeight = element.videoElement.thumbHeight;
}
override get valid (): boolean {
return !!this.msgInfo;
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
if (!this.msgInfo) return [];
return [{
commonElem: {
serviceType: 48,
pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
businessType: 21,
},
}];
}
override toPreview (): string {
return '[视频]';
}
}
export class PacketMsgPttElement extends IPacketMsgElement<SendPttElement> {
filePath: string;
fileSize: number;
fileMd5: string;
fileSha1?: string;
fileDuration: number;
msgInfo: NapProtoEncodeStructType<typeof MsgInfo> | null = null;
constructor (element: SendPttElement) {
super(element);
this.filePath = element.pttElement.filePath;
this.fileSize = +element.pttElement.fileSize; // TODO: cc
this.fileMd5 = element.pttElement.md5HexStr;
this.fileDuration = Math.round(element.pttElement.duration); // TODO: cc
}
override get valid (): boolean {
return false;
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
return [];
// if (!this.msgInfo) return [];
// return [{
// commonElem: {
// serviceType: 48,
// pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
// businessType: 22,
// }
// }];
}
override toPreview (): string {
return '[语音]';
}
}
export class PacketMsgFileElement extends IPacketMsgElement<SendFileElement> {
fileName: string;
filePath: string;
fileSize: number;
fileSha1?: Uint8Array;
fileMd5?: Uint8Array;
fileUuid?: string;
fileHash?: string;
isGroupFile?: boolean;
_private_send_uid?: string;
_private_recv_uid?: string;
_e37_800_rsp?: NapProtoEncodeStructType<typeof OidbSvcTrpcTcp0XE37_800Response>;
constructor (element: SendFileElement) {
super(element);
this.fileName = element.fileElement.fileName;
this.filePath = element.fileElement.filePath;
this.fileSize = +element.fileElement.fileSize;
}
override get valid (): boolean {
return this.isGroupFile || Boolean(this._e37_800_rsp);
}
override buildContent (): Uint8Array | undefined {
if (this.isGroupFile || !this._e37_800_rsp) return undefined;
return new NapProtoMsg(FileExtra).encode({
file: {
fileType: 0,
fileUuid: this.fileUuid,
fileMd5: this.fileMd5,
fileName: this.fileName,
fileSize: BigInt(this.fileSize),
subcmd: 1,
dangerEvel: 0,
expireTime: Math.floor(Date.now() / 1000) + 7 * 24 * 60 * 60,
fileHash: this.fileHash,
},
field6: {
field2: {
field1: this._e37_800_rsp?.body?.field30?.field110,
fileUuid: this.fileUuid,
fileName: this.fileName,
field6: this._e37_800_rsp?.body?.field30?.field3,
field7: this._e37_800_rsp?.body?.field30?.field101,
field8: this._e37_800_rsp?.body?.field30?.field100,
timestamp1: this._e37_800_rsp?.body?.field30?.timestamp1,
fileHash: this.fileHash,
selfUid: this._private_send_uid,
destUid: this._private_recv_uid,
},
},
});
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
if (!this.isGroupFile) return [];
const lb = Buffer.alloc(2);
const transElemVal = new NapProtoMsg(GroupFileExtra).encode({
field1: 6,
fileName: this.fileName,
inner: {
info: {
busId: 102,
fileId: this.fileUuid,
fileSize: BigInt(this.fileSize),
fileName: this.fileName,
fileSha: this.fileSha1,
extInfoString: '',
fileMd5: this.fileMd5,
},
},
});
lb.writeUInt16BE(transElemVal.length);
return [{
transElem: {
elemType: 24,
elemValue: Buffer.concat([Buffer.from([0x01]), lb, transElemVal]), // TLV
},
}];
}
override toPreview (): string {
return `[文件]${this.fileName}`;
}
}
export class PacketMsgLightAppElement extends IPacketMsgElement<SendArkElement> {
payload: string;
constructor (element: SendArkElement) {
super(element);
this.payload = element.arkElement.bytesData;
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
return [{
lightAppElem: {
data: Buffer.concat([
Buffer.from([0x01]),
zlib.deflateSync(Buffer.from(this.payload, 'utf-8')),
]),
},
}];
}
override toPreview (): string {
return '[卡片消息]';
}
}
export class PacketMsgMarkDownElement extends IPacketMsgElement<SendMarkdownElement> {
content: string;
constructor (element: SendMarkdownElement) {
super(element);
this.content = element.markdownElement.content;
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
return [{
commonElem: {
serviceType: 45,
pbElem: new NapProtoMsg(MarkdownData).encode({
content: this.content,
}),
businessType: 1,
},
}];
}
override toPreview (): string {
return `[Markdown消息 ${this.content}]`;
}
}
export class PacketMultiMsgElement extends IPacketMsgElement<SendMultiForwardMsgElement> {
resid: string;
message: PacketMsg[];
constructor (rawElement: SendMultiForwardMsgElement, message?: PacketMsg[]) {
super(rawElement);
this.resid = rawElement.multiForwardMsgElement.resId;
this.message = message ?? [];
}
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
return [{
lightAppElem: {
data: Buffer.concat([
Buffer.from([0x01]),
zlib.deflateSync(Buffer.from(JSON.stringify(ForwardMsgBuilder.fromPacketMsg(this.resid, this.message)), 'utf-8')),
]),
},
}];
}
override toPreview (): string {
return '[聊天记录]';
}
}
@@ -0,0 +1,15 @@
import { IPacketMsgElement } from '@/napcat-core/packet/message/element';
import { SendMessageElement, SendMultiForwardMsgElement } from '@/napcat-core';
export type PacketSendMsgElement = SendMessageElement | SendMultiForwardMsgElement;
export interface PacketMsg {
seq?: number;
clientSeq?: number;
groupId?: number;
senderUid: string;
senderUin: number;
senderName: string;
time: number;
msg: IPacketMsgElement<PacketSendMsgElement>[]
}
@@ -0,0 +1,22 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import { AIVoiceChatType } from '@/napcat-core/packet/entities/aiChat';
class FetchAiVoiceList extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0X929D_0Resp> {
build (groupUin: number, chatType: AIVoiceChatType): OidbPacket {
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0X929D_0).encode({
groupUin,
chatType,
});
return OidbBase.build(0x929D, 0, data);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.OidbSvcTrpcTcp0X929D_0Resp).decode(oidbBody);
}
}
export default new FetchAiVoiceList();
@@ -0,0 +1,27 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import { AIVoiceChatType } from '@/napcat-core/packet/entities/aiChat';
class GetAiVoice extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0X929B_0Resp> {
build (groupUin: number, voiceId: string, text: string, sessionId: number, chatType: AIVoiceChatType): OidbPacket {
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0X929B_0).encode({
groupUin,
voiceId,
text,
chatType,
session: {
sessionId,
},
});
return OidbBase.build(0x929B, 0, data);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.OidbSvcTrpcTcp0X929B_0Resp).decode(oidbBody);
}
}
export default new GetAiVoice();
@@ -0,0 +1,49 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketBufBuilder, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import { MiniAppReqParams } from '@/napcat-core/packet/entities/miniApp';
class GetMiniAppAdaptShareInfo extends PacketTransformer<typeof proto.MiniAppAdaptShareInfoResp> {
build (req: MiniAppReqParams): OidbPacket {
const data = new NapProtoMsg(proto.MiniAppAdaptShareInfoReq).encode({
appId: req.sdkId,
body: {
extInfo: {
field2: Buffer.alloc(0),
},
appid: req.appId,
title: req.title,
desc: req.desc,
time: BigInt(Date.now()),
scene: req.scene,
templateType: req.templateType,
businessType: req.businessType,
picUrl: req.picUrl,
vidUrl: '',
jumpUrl: req.jumpUrl,
iconUrl: req.iconUrl,
verType: req.verType,
shareType: req.shareType,
versionId: req.versionId,
withShareTicket: req.withShareTicket,
webURL: req.webUrl ?? '',
appidRich: Buffer.alloc(0),
template: {
templateId: '',
templateData: '',
},
field20: '',
},
});
return {
cmd: 'LightAppSvc.mini_app_share.AdaptShareInfo',
data: PacketBufBuilder(data),
};
}
parse (data: Buffer) {
return new NapProtoMsg(proto.MiniAppAdaptShareInfoResp).decode(data);
}
}
export default new GetMiniAppAdaptShareInfo();
@@ -0,0 +1,21 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class GetStrangerInfo extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0XFE1_2RSP> {
build (uin: number): OidbPacket {
const body = new NapProtoMsg(proto.OidbSvcTrpcTcp0XFE1_2).encode({
uin,
key: [{ key: 27372 }],
});
return OidbBase.build(0XFE1, 2, body);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.OidbSvcTrpcTcp0XFE1_2RSP).decode(oidbBody);
}
}
export default new GetStrangerInfo();
@@ -0,0 +1,25 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class GroupSign extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
build (uin: number, groupCode: number): OidbPacket {
const body = new NapProtoMsg(proto.OidbSvcTrpcTcp0XEB7).encode(
{
body: {
uin: String(uin),
groupUin: String(groupCode),
version: '9.0.90',
},
}
);
return OidbBase.build(0XEB7, 1, body, false, false);
}
parse (data: Buffer) {
return OidbBase.parse(data);
}
}
export default new GroupSign();
@@ -0,0 +1,33 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class ImageOCR extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0xE07_0_Response> {
build (url: string): OidbPacket {
const body = new NapProtoMsg(proto.OidbSvcTrpcTcp0xE07_0).encode(
{
version: 1,
client: 0,
entrance: 1,
ocrReqBody: {
imageUrl: url,
originMd5: '',
afterCompressMd5: '',
afterCompressFileSize: '',
afterCompressWeight: '',
afterCompressHeight: '',
isCut: false,
},
}
);
return OidbBase.build(0XEB7, 1, body, false, false);
}
parse (data: Buffer) {
const base = OidbBase.parse(data);
return new NapProtoMsg(proto.OidbSvcTrpcTcp0xE07_0_Response).decode(base.body);
}
}
export default new ImageOCR();
@@ -0,0 +1,31 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class MoveGroupFile extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0x6D6Response> {
build (groupUin: number, fileUUID: string, currentParentDirectory: string, targetParentDirectory: string): OidbPacket {
const body = new NapProtoMsg(proto.OidbSvcTrpcTcp0x6D6).encode({
move: {
groupUin,
appId: 5,
busId: 102,
fileId: fileUUID,
parentDirectory: currentParentDirectory,
targetDirectory: targetParentDirectory,
},
});
return OidbBase.build(0x6D6, 5, body, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
const res = new NapProtoMsg(proto.OidbSvcTrpcTcp0x6D6Response).decode(oidbBody);
if (res.move.retCode !== 0) {
throw new Error(`sendGroupFileMoveReq error: ${res.move.clientWording} (code=${res.move.retCode})`);
}
return res;
}
}
export default new MoveGroupFile();
@@ -0,0 +1,30 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class RenameGroupFile extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0x6D6Response> {
build (groupUin: number, fileUUID: string, currentParentDirectory: string, newName: string): OidbPacket {
const body = new NapProtoMsg(proto.OidbSvcTrpcTcp0x6D6).encode({
rename: {
groupUin,
busId: 102,
fileId: fileUUID,
parentFolder: currentParentDirectory,
newFileName: newName,
},
});
return OidbBase.build(0x6D6, 4, body, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
const res = new NapProtoMsg(proto.OidbSvcTrpcTcp0x6D6Response).decode(oidbBody);
if (res.rename.retCode !== 0) {
throw new Error(`sendGroupFileRenameReq error: ${res.rename.clientWording} (code=${res.rename.retCode})`);
}
return res;
}
}
export default new RenameGroupFile();
@@ -0,0 +1,22 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class SendPoke extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
build (is_group: boolean, peer: number, target: number): OidbPacket {
const payload = {
uin: target,
ext: 0,
...(is_group ? { groupUin: peer } : { friendUin: peer }),
};
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XED3_1).encode(payload);
return OidbBase.build(0xED3, 1, data);
}
parse (data: Buffer) {
return OidbBase.parse(data);
}
}
export default new SendPoke();
@@ -0,0 +1,20 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class SetGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
build (peer: number, msgSeq: string): OidbPacket {
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90_1).encode({
groupUin: peer,
msgSeq: BigInt(msgSeq),
});
return OidbBase.build(0xF90, 1, data);
}
parse (data: Buffer) {
return OidbBase.parse(data);
}
}
export default new SetGroupTodo();
@@ -0,0 +1,25 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class SetSpecialTitle extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
build (groupCode: number, uid: string, title: string): OidbPacket {
const oidb_0x8FC_2 = new NapProtoMsg(proto.OidbSvcTrpcTcp0X8FC_2).encode({
groupUin: +groupCode,
body: {
targetUid: uid,
specialTitle: title,
expiredTime: -1,
uinName: title,
},
});
return OidbBase.build(0x8FC, 2, oidb_0x8FC_2, false, false);
}
parse (data: Buffer) {
return OidbBase.parse(data);
}
}
export default new SetSpecialTitle();
@@ -0,0 +1,11 @@
export { default as FetchAiVoiceList } from './FetchAiVoiceList';
export { default as GetAiVoice } from './GetAiVoice';
export { default as GetMiniAppAdaptShareInfo } from './GetMiniAppAdaptShareInfo';
export { default as GroupSign } from './GroupSign';
export { default as GetStrangerInfo } from './GetStrangerInfo';
export { default as SendPoke } from './SendPoke';
export { default as SetSpecialTitle } from './SetSpecialTitle';
export { default as ImageOCR } from './ImageOCR';
export { default as MoveGroupFile } from './MoveGroupFile';
export { default as RenameGroupFile } from './RenameGroupFile';
export { default as SetGroupTodo } from './SetGroupTodo';
@@ -0,0 +1,25 @@
import { NapProtoDecodeStructType } from '@napneko/nap-proto-core';
import { PacketMsgBuilder } from '@/napcat-core/packet/message/builder';
export type PacketBuf = Buffer & { readonly hexNya: unique symbol; };
export const PacketBufBuilder = (str: Uint8Array): PacketBuf => {
return Buffer.from(str) as PacketBuf;
};
export interface OidbPacket {
cmd: string;
data: PacketBuf;
}
export abstract class PacketTransformer<T> {
protected msgBuilder: PacketMsgBuilder;
constructor () {
this.msgBuilder = new PacketMsgBuilder();
}
abstract build (...args: any[]): OidbPacket | Promise<OidbPacket>;
abstract parse (data: Buffer): NapProtoDecodeStructType<T>;
}
@@ -0,0 +1,29 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class DownloadGroupFile extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0x6D6Response> {
build (groupUin: number, fileUUID: string): OidbPacket {
const body = new NapProtoMsg(proto.OidbSvcTrpcTcp0x6D6).encode({
download: {
groupUin,
appId: 7,
busId: 102,
fileId: fileUUID,
},
});
return OidbBase.build(0x6D6, 2, body, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
const res = new NapProtoMsg(proto.OidbSvcTrpcTcp0x6D6Response).decode(oidbBody);
if (res.download.retCode !== 0) {
throw new Error(`sendGroupFileDownloadReq error: ${res.download.clientWording} (code=${res.download.retCode})`);
}
return res;
}
}
export default new DownloadGroupFile();
@@ -0,0 +1,46 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import { IndexNode } from '@/napcat-core/packet/transformer/proto';
class DownloadGroupImage extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
build (group_uin: number, node: NapProtoEncodeStructType<typeof IndexNode>): OidbPacket {
const body = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
reqHead: {
common: {
requestId: 1,
command: 200,
},
scene: {
requestType: 2,
businessType: 1,
sceneType: 2,
group: {
groupUin: group_uin,
},
},
client: {
agentType: 2,
},
},
download: {
node,
download: {
video: {
busiType: 0,
sceneType: 0,
},
},
},
});
return OidbBase.build(0x11C4, 200, body, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
}
}
export default new DownloadGroupImage();
@@ -0,0 +1,45 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class DownloadGroupPtt extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
build (groupUin: number, node: NapProtoEncodeStructType<typeof proto.IndexNode>): OidbPacket {
const body = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
reqHead: {
common: {
requestId: 4,
command: 200,
},
scene: {
requestType: 1,
businessType: 3,
sceneType: 2,
group: {
groupUin,
},
},
client: {
agentType: 2,
},
},
download: {
node,
download: {
video: {
busiType: 0,
sceneType: 0,
},
},
},
});
return OidbBase.build(0x126E, 200, body, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
}
}
export default new DownloadGroupPtt();
@@ -0,0 +1,46 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import { IndexNode } from '@/napcat-core/packet/transformer/proto';
class DownloadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
build (groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>): OidbPacket {
const body = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
reqHead: {
common: {
requestId: 1,
command: 200,
},
scene: {
requestType: 2,
businessType: 2,
sceneType: 2,
group: {
groupUin,
},
},
client: {
agentType: 2,
},
},
download: {
node,
download: {
video: {
busiType: 0,
sceneType: 0,
},
},
},
});
return OidbBase.build(0x11EA, 200, body, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
}
}
export default new DownloadGroupVideo();
@@ -0,0 +1,47 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import { IndexNode } from '@/napcat-core/packet/transformer/proto';
class DownloadImage extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
build (selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>): OidbPacket {
const body = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
reqHead: {
common: {
requestId: 1,
command: 200,
},
scene: {
requestType: 2,
businessType: 1,
sceneType: 1,
c2C: {
accountType: 2,
targetUid: selfUid,
},
},
client: {
agentType: 2,
},
},
download: {
node,
download: {
video: {
busiType: 0,
sceneType: 0,
},
},
},
});
return OidbBase.build(0x11C5, 200, body, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
}
}
export default new DownloadImage();
@@ -0,0 +1,31 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class DownloadOfflineFile extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0XE37Response> {
build (fileUUID: string, fileHash: string, senderUid: string, receiverUid: string): OidbPacket {
const body = new NapProtoMsg(proto.OidbSvcTrpcTcp0XE37_800).encode({
subCommand: 800,
field2: 0,
body: {
senderUid,
receiverUid,
fileUuid: fileUUID,
fileHash,
},
field101: 3,
field102: 1,
field200: 1,
});
return OidbBase.build(0xE37, 800, body, false, false);
}
// TODO:check
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.OidbSvcTrpcTcp0XE37Response).decode(oidbBody);
}
}
export default new DownloadOfflineFile();
@@ -0,0 +1,32 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class DownloadPrivateFile extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0XE37_1200Response> {
build (selfUid: string, fileUUID: string, fileHash: string): OidbPacket {
const body = new NapProtoMsg(proto.OidbSvcTrpcTcp0XE37_1200).encode({
subCommand: 1200,
field2: 1,
body: {
receiverUid: selfUid,
fileUuid: fileUUID,
type: 2,
fileHash,
t2: 0,
},
field101: 3,
field102: 103,
field200: 1,
field99999: Buffer.from([0xc0, 0x85, 0x2c, 0x01]),
});
return OidbBase.build(0xE37, 1200, body, false, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.OidbSvcTrpcTcp0XE37_1200Response).decode(oidbBody);
}
}
export default new DownloadPrivateFile();
@@ -0,0 +1,47 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import { IndexNode } from '@/napcat-core/packet/transformer/proto';
class DownloadPtt extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
build (selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>): OidbPacket {
const body = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
reqHead: {
common: {
requestId: 1,
command: 200,
},
scene: {
requestType: 1,
businessType: 3,
sceneType: 1,
c2C: {
accountType: 2,
targetUid: selfUid,
},
},
client: {
agentType: 2,
},
},
download: {
node,
download: {
video: {
busiType: 0,
sceneType: 0,
},
},
},
});
return OidbBase.build(0x126D, 200, body, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
}
}
export default new DownloadPtt();
@@ -0,0 +1,47 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import { IndexNode } from '@/napcat-core/packet/transformer/proto';
class DownloadVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
build (selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>): OidbPacket {
const body = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
reqHead: {
common: {
requestId: 1,
command: 200,
},
scene: {
requestType: 2,
businessType: 2,
sceneType: 1,
c2C: {
accountType: 2,
targetUid: selfUid,
},
},
client: {
agentType: 2,
},
},
download: {
node,
download: {
video: {
busiType: 0,
sceneType: 0,
},
},
},
});
return OidbBase.build(0x11E9, 200, body, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
}
}
export default new DownloadVideo();
@@ -0,0 +1,33 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketBufBuilder, PacketTransformer } from '@/napcat-core/packet/transformer/base';
class FetchSessionKey extends PacketTransformer<typeof proto.HttpConn0x6ff_501Response> {
build (): OidbPacket {
const req = new NapProtoMsg(proto.HttpConn0x6ff_501).encode({
httpConn: {
field1: 0,
field2: 0,
field3: 16,
field4: 1,
field6: 3,
serviceTypes: [1, 5, 10, 21],
// tgt: "", // TODO: do we really need tgt? seems not
field9: 2,
field10: 9,
field11: 8,
ver: '1.0.1',
},
});
return {
cmd: 'HttpConn.0x6ff_501',
data: PacketBufBuilder(req),
};
}
parse (data: Buffer) {
return new NapProtoMsg(proto.HttpConn0x6ff_501Response).decode(data);
}
}
export default new FetchSessionKey();
@@ -0,0 +1,34 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import { PacketMsgFileElement } from '@/napcat-core/packet/message/element';
class UploadGroupFile extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0x6D6Response> {
build (groupUin: number, file: PacketMsgFileElement): OidbPacket {
const body = new NapProtoMsg(proto.OidbSvcTrpcTcp0x6D6).encode({
file: {
groupUin,
appId: 4,
busId: 102,
entrance: 6,
targetDirectory: '/', // TODO:
fileName: file.fileName,
localDirectory: `/${file.fileName}`,
fileSize: BigInt(file.fileSize),
fileMd5: file.fileMd5,
fileSha1: file.fileSha1,
fileSha3: Buffer.alloc(0),
field15: true,
},
});
return OidbBase.build(0x6D6, 0, body, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.OidbSvcTrpcTcp0x6D6Response).decode(oidbBody);
}
}
export default new UploadGroupFile();
@@ -0,0 +1,86 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import crypto from 'node:crypto';
import { PacketMsgPicElement } from '@/napcat-core/packet/message/element';
class UploadGroupImage extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
build (groupUin: number, img: PacketMsgPicElement): OidbPacket {
const data = new NapProtoMsg(proto.NTV2RichMediaReq).encode(
{
reqHead: {
common: {
requestId: 1,
command: 100,
},
scene: {
requestType: 2,
businessType: 1,
sceneType: 2,
group: {
groupUin,
},
},
client: {
agentType: 2,
},
},
upload: {
uploadInfo: [
{
fileInfo: {
fileSize: +img.size,
fileHash: img.md5,
fileSha1: img.sha1!,
fileName: img.name,
type: {
type: 1,
picFormat: img.picType, // TODO: extend NapCat imgType /cc @MliKiowa
videoFormat: 0,
voiceFormat: 0,
},
width: img.width,
height: img.height,
time: 0,
original: 1,
},
subFileType: 0,
},
],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: crypto.randomBytes(8).readBigUInt64BE() & BigInt('0x7FFFFFFFFFFFFFFF'),
compatQMsgSceneType: 2,
extBizInfo: {
pic: {
bizType: img.picSubType,
bytesPbReserveTroop: {
subType: img.picSubType,
},
textSummary: img.summary,
},
video: {
bytesPbReserve: Buffer.alloc(0),
},
ptt: {
bytesPbReserve: Buffer.alloc(0),
bytesReserve: Buffer.alloc(0),
bytesGeneralFlags: Buffer.alloc(0),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
}
);
return OidbBase.build(0x11C4, 100, data, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
}
}
export default new UploadGroupImage();
@@ -0,0 +1,82 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import crypto from 'node:crypto';
import { PacketMsgPttElement } from '@/napcat-core/packet/message/element';
class UploadGroupPtt extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
build (groupUin: number, ptt: PacketMsgPttElement): OidbPacket {
const data = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
reqHead: {
common: {
requestId: 1,
command: 100,
},
scene: {
requestType: 2,
businessType: 3,
sceneType: 2,
group: {
groupUin,
},
},
client: {
agentType: 2,
},
},
upload: {
uploadInfo: [
{
fileInfo: {
fileSize: ptt.fileSize,
fileHash: ptt.fileMd5,
fileSha1: ptt.fileSha1,
fileName: `${ptt.fileMd5}.amr`,
type: {
type: 3,
picFormat: 0,
videoFormat: 0,
voiceFormat: 1,
},
height: 0,
width: 0,
time: ptt.fileDuration,
original: 0,
},
subFileType: 0,
},
],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: crypto.randomBytes(8).readBigUInt64BE() & BigInt('0x7FFFFFFFFFFFFFFF'),
compatQMsgSceneType: 2,
extBizInfo: {
pic: {
textSummary: 'Nya~',
},
video: {
bytesPbReserve: Buffer.alloc(0),
},
ptt: {
bytesPbReserve: Buffer.alloc(0),
bytesReserve: Buffer.from([0x08, 0x00, 0x38, 0x00]),
bytesGeneralFlags: Buffer.from([0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00]),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
});
return OidbBase.build(0x126E, 100, data, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
}
}
const instance = new UploadGroupPtt();
export default instance;
@@ -0,0 +1,100 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import crypto from 'node:crypto';
import { PacketMsgVideoElement } from '@/napcat-core/packet/message/element';
class UploadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
build (groupUin: number, video: PacketMsgVideoElement): OidbPacket {
if (!video.fileSize || !video.thumbSize) throw new Error('video.fileSize or video.thumbSize is empty');
const data = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
reqHead: {
common: {
requestId: 3,
command: 100,
},
scene: {
requestType: 2,
businessType: 2,
sceneType: 2,
group: {
groupUin,
},
},
client: {
agentType: 2,
},
},
upload: {
uploadInfo: [
{
fileInfo: {
fileSize: +video.fileSize,
fileHash: video.fileMd5,
fileSha1: video.fileSha1,
fileName: 'nya.mp4',
type: {
type: 2,
picFormat: 0,
videoFormat: 0,
voiceFormat: 0,
},
height: 0,
width: 0,
time: 0,
original: 0,
},
subFileType: 0,
}, {
fileInfo: {
fileSize: +video.thumbSize,
fileHash: video.thumbMd5,
fileSha1: video.thumbSha1,
fileName: 'nya.jpg',
type: {
type: 1,
picFormat: 0,
videoFormat: 0,
voiceFormat: 0,
},
height: video.thumbHeight,
width: video.thumbWidth,
time: 0,
original: 0,
},
subFileType: 100,
},
],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: crypto.randomBytes(8).readBigUInt64BE() & BigInt('0x7FFFFFFFFFFFFFFF'),
compatQMsgSceneType: 2,
extBizInfo: {
pic: {
bizType: 0,
textSummary: 'Nya~',
},
video: {
bytesPbReserve: Buffer.from([0x80, 0x01, 0x00]),
},
ptt: {
bytesPbReserve: Buffer.alloc(0),
bytesReserve: Buffer.alloc(0),
bytesGeneralFlags: Buffer.alloc(0),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
});
return OidbBase.build(0x11EA, 100, data, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
}
}
export default new UploadGroupVideo();
@@ -0,0 +1,37 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import { PacketMsgFileElement } from '@/napcat-core/packet/message/element';
import { computeMd5AndLengthWithLimit } from '@/napcat-core/packet/utils/crypto/hash';
class UploadPrivateFile extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0XE37Response> {
async build (selfUid: string, peerUid: string, file: PacketMsgFileElement): Promise<OidbPacket> {
const body = new NapProtoMsg(proto.OidbSvcTrpcTcp0XE37_1700).encode({
command: 1700,
seq: 0,
upload: {
senderUid: selfUid,
receiverUid: peerUid,
fileSize: file.fileSize,
fileName: file.fileName,
md510MCheckSum: await computeMd5AndLengthWithLimit(file.filePath, 10 * 1024 * 1024),
sha1CheckSum: file.fileSha1,
localPath: '/',
md5CheckSum: file.fileMd5,
sha3CheckSum: Buffer.alloc(0),
},
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
});
return OidbBase.build(0xE37, 1700, body, false, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.OidbSvcTrpcTcp0XE37Response).decode(oidbBody);
}
}
export default new UploadPrivateFile();
@@ -0,0 +1,86 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import crypto from 'node:crypto';
import { PacketMsgPicElement } from '@/napcat-core/packet/message/element';
class UploadPrivateImage extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
build (peerUin: string, img: PacketMsgPicElement): OidbPacket {
const data = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
reqHead: {
common: {
requestId: 1,
command: 100,
},
scene: {
requestType: 2,
businessType: 1,
sceneType: 1,
c2C: {
accountType: 2,
targetUid: peerUin,
},
},
client: {
agentType: 2,
},
},
upload: {
uploadInfo: [
{
fileInfo: {
fileSize: +img.size,
fileHash: img.md5,
fileSha1: img.sha1!,
fileName: img.name,
type: {
type: 1,
picFormat: img.picType, // TODO: extend NapCat imgType /cc @MliKiowa
videoFormat: 0,
voiceFormat: 0,
},
width: img.width,
height: img.height,
time: 0,
original: 1,
},
subFileType: 0,
},
],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: crypto.randomBytes(8).readBigUInt64BE() & BigInt('0x7FFFFFFFFFFFFFFF'),
compatQMsgSceneType: 1,
extBizInfo: {
pic: {
bizType: img.picSubType,
bytesPbReserveC2C: {
subType: img.picSubType,
},
textSummary: img.summary,
},
video: {
bytesPbReserve: Buffer.alloc(0),
},
ptt: {
bytesPbReserve: Buffer.alloc(0),
bytesReserve: Buffer.alloc(0),
bytesGeneralFlags: Buffer.alloc(0),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
}
);
return OidbBase.build(0x11C5, 100, data, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
}
}
export default new UploadPrivateImage();
@@ -0,0 +1,77 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import crypto from 'node:crypto';
import { PacketMsgPttElement } from '@/napcat-core/packet/message/element';
class UploadPrivatePtt extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
build (peerUin: string, ptt: PacketMsgPttElement): OidbPacket {
const data = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
reqHead: {
common: {
requestId: 4,
command: 100,
},
scene: {
requestType: 2,
businessType: 3,
sceneType: 1,
c2C: {
accountType: 2,
targetUid: peerUin,
},
},
client: {
agentType: 2,
},
},
upload: {
uploadInfo: [
{
fileInfo: {
fileSize: ptt.fileSize,
fileHash: ptt.fileMd5,
fileSha1: ptt.fileSha1,
fileName: `${ptt.fileMd5}.amr`,
type: {
type: 3,
picFormat: 0,
videoFormat: 0,
voiceFormat: 1,
},
height: 0,
width: 0,
time: ptt.fileDuration,
original: 0,
},
subFileType: 0,
},
],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: crypto.randomBytes(8).readBigUInt64BE() & BigInt('0x7FFFFFFFFFFFFFFF'),
compatQMsgSceneType: 1,
extBizInfo: {
pic: {
textSummary: 'Nya~',
},
ptt: {
bytesReserve: Buffer.from([0x08, 0x00, 0x38, 0x00]),
bytesGeneralFlags: Buffer.from([0x9a, 0x01, 0x0b, 0xaa, 0x03, 0x08, 0x08, 0x04, 0x12, 0x04, 0x00, 0x00, 0x00, 0x00]),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
});
return OidbBase.build(0x126D, 100, data, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
}
}
export default new UploadPrivatePtt();
@@ -0,0 +1,101 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
import crypto from 'node:crypto';
import { PacketMsgVideoElement } from '@/napcat-core/packet/message/element';
class UploadPrivateVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
build (peerUin: string, video: PacketMsgVideoElement): OidbPacket {
if (!video.fileSize || !video.thumbSize) throw new Error('video.fileSize or video.thumbSize is empty');
const data = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
reqHead: {
common: {
requestId: 3,
command: 100,
},
scene: {
requestType: 2,
businessType: 2,
sceneType: 1,
c2C: {
accountType: 2,
targetUid: peerUin,
},
},
client: {
agentType: 2,
},
},
upload: {
uploadInfo: [
{
fileInfo: {
fileSize: +video.fileSize,
fileHash: video.fileMd5,
fileSha1: video.fileSha1,
fileName: 'nya.mp4',
type: {
type: 2,
picFormat: 0,
videoFormat: 0,
voiceFormat: 0,
},
height: 0,
width: 0,
time: 0,
original: 0,
},
subFileType: 0,
}, {
fileInfo: {
fileSize: +video.thumbSize,
fileHash: video.thumbMd5,
fileSha1: video.thumbSha1,
fileName: 'nya.jpg',
type: {
type: 1,
picFormat: 0,
videoFormat: 0,
voiceFormat: 0,
},
height: video.thumbHeight,
width: video.thumbWidth,
time: 0,
original: 0,
},
subFileType: 100,
},
],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: crypto.randomBytes(8).readBigUInt64BE() & BigInt('0x7FFFFFFFFFFFFFFF'),
compatQMsgSceneType: 2,
extBizInfo: {
pic: {
bizType: 0,
textSummary: 'Nya~',
},
video: {
bytesPbReserve: Buffer.from([0x80, 0x01, 0x00]),
},
ptt: {
bytesPbReserve: Buffer.alloc(0),
bytesReserve: Buffer.alloc(0),
bytesGeneralFlags: Buffer.alloc(0),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
});
return OidbBase.build(0x11E9, 100, data, true, false);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
}
}
export default new UploadPrivateVideo();
@@ -0,0 +1,18 @@
export { default as DownloadGroupFile } from './DownloadGroupFile';
export { default as DownloadGroupPtt } from './DownloadGroupPtt';
export { default as DownloadOfflineFile } from './DownloadOfflineFile';
export { default as DownloadPrivateFile } from './DownloadPrivateFile';
export { default as FetchSessionKey } from './FetchSessionKey';
export { default as UploadGroupFile } from './UploadGroupFile';
export { default as UploadGroupImage } from './UploadGroupImage';
export { default as UploadGroupPtt } from './UploadGroupPtt';
export { default as UploadGroupVideo } from './UploadGroupVideo';
export { default as UploadPrivateFile } from './UploadPrivateFile';
export { default as UploadPrivateImage } from './UploadPrivateImage';
export { default as UploadPrivatePtt } from './UploadPrivatePtt';
export { default as UploadPrivateVideo } from './UploadPrivateVideo';
export { default as DownloadImage } from './DownloadImage';
export { default as DownloadGroupImage } from './DownloadGroupImage';
export { default as DownloadVideo } from './DownloadVideo';
export { default as DownloadGroupVideo } from './DownloadGroupVideo';
export { default as DownloadPtt } from './DownloadPtt';
@@ -0,0 +1,4 @@
export * from './action';
export * from './highway';
export * from './message';
export * from './system';
@@ -0,0 +1,33 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketBufBuilder, PacketTransformer } from '@/napcat-core/packet/transformer/base';
class DownloadForwardMsg extends PacketTransformer<typeof proto.RecvLongMsgResp> {
build (uid: string, resId: string): OidbPacket {
const req = new NapProtoMsg(proto.RecvLongMsgReq).encode({
info: {
uid: {
uid,
},
resId,
acquire: true,
},
settings: {
field1: 2,
field2: 0,
field3: 0,
field4: 0,
},
});
return {
cmd: 'trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg',
data: PacketBufBuilder(req),
};
}
parse (data: Buffer) {
return new NapProtoMsg(proto.RecvLongMsgResp).decode(data);
}
}
export default new DownloadForwardMsg();
@@ -0,0 +1,23 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketBufBuilder, PacketTransformer } from '@/napcat-core/packet/transformer/base';
class FetchC2CMessage extends PacketTransformer<typeof proto.SsoGetC2cMsgResponse> {
build (targetUid: string, startSeq: number, endSeq: number): OidbPacket {
const req = new NapProtoMsg(proto.SsoGetC2cMsg).encode({
friendUid: targetUid,
startSequence: startSeq,
endSequence: endSeq,
});
return {
cmd: 'trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg',
data: PacketBufBuilder(req),
};
}
parse (data: Buffer) {
return new NapProtoMsg(proto.SsoGetC2cMsgResponse).decode(data);
}
}
export default new FetchC2CMessage();
@@ -0,0 +1,26 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketBufBuilder, PacketTransformer } from '@/napcat-core/packet/transformer/base';
class FetchGroupMessage extends PacketTransformer<typeof proto.SsoGetGroupMsgResponse> {
build (groupUin: number, startSeq: number, endSeq: number): OidbPacket {
const req = new NapProtoMsg(proto.SsoGetGroupMsg).encode({
info: {
groupUin,
startSequence: startSeq,
endSequence: endSeq,
},
direction: true,
});
return {
cmd: 'trpc.msg.register_proxy.RegisterProxy.SsoGetGroupMsg',
data: PacketBufBuilder(req),
};
}
parse (data: Buffer) {
return new NapProtoMsg(proto.SsoGetGroupMsgResponse).decode(data);
}
}
export default new FetchGroupMessage();
@@ -0,0 +1,47 @@
import zlib from 'node:zlib';
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketBufBuilder, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import { PacketMsg } from '@/napcat-core/packet/message/message';
class UploadForwardMsg extends PacketTransformer<typeof proto.SendLongMsgResp> {
build (selfUid: string, msg: PacketMsg[], groupUin: number = 0): OidbPacket {
const msgBody = this.msgBuilder.buildFakeMsg(selfUid, msg);
const longMsgResultData = new NapProtoMsg(proto.LongMsgResult).encode(
{
action: [{
actionCommand: 'MultiMsg',
actionData: {
msgBody,
},
}],
}
);
const payload = zlib.gzipSync(Buffer.from(longMsgResultData));
const req = new NapProtoMsg(proto.SendLongMsgReq).encode(
{
info: {
type: groupUin === 0 ? 1 : 3,
uid: {
uid: groupUin === 0 ? selfUid : groupUin.toString(),
},
groupUin,
payload,
},
settings: {
field1: 4, field2: 1, field3: 7, field4: 0,
},
}
);
return {
cmd: 'trpc.group.long_msg_interface.MsgService.SsoSendLongMsg',
data: PacketBufBuilder(req),
};
}
parse (data: Buffer) {
return new NapProtoMsg(proto.SendLongMsgResp).decode(data);
}
}
export default new UploadForwardMsg();
@@ -0,0 +1,4 @@
export { default as UploadForwardMsg } from './UploadForwardMsg';
export { default as FetchGroupMessage } from './FetchGroupMessage';
export { default as FetchC2CMessage } from './FetchC2CMessage';
export { default as DownloadForwardMsg } from './DownloadForwardMsg';
@@ -0,0 +1,28 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketBufBuilder, PacketTransformer } from '@/napcat-core/packet/transformer/base';
class OidbBase extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
build (cmd: number, subCmd: number, body: Uint8Array, isUid: boolean = true, _isLafter: boolean = false): OidbPacket {
const data = new NapProtoMsg(proto.OidbSvcTrpcTcpBase).encode({
command: cmd,
subCommand: subCmd,
body,
isReserved: isUid ? 1 : 0,
});
return {
cmd: `OidbSvcTrpcTcp.0x${cmd.toString(16).toUpperCase()}_${subCmd}`,
data: PacketBufBuilder(data),
};
}
parse (data: Buffer) {
const res = new NapProtoMsg(proto.OidbSvcTrpcTcpBase).decode(data);
if (res.errorCode !== 0) {
throw new Error(`OidbSvcTrpcTcpBase parse error: ${res.errorMsg} (code=${res.errorCode})`);
}
return res;
}
}
export default new OidbBase();
@@ -0,0 +1,114 @@
import { ScalarType } from '@protobuf-ts/runtime';
import { ProtoField } from '@napneko/nap-proto-core';
import { ContentHead, MessageBody, MessageControl, RoutingHead } from '@/napcat-core/packet/transformer/proto';
export const FaceRoamRequest = {
comm: ProtoField(1, () => PlatInfo, true),
selfUin: ProtoField(2, ScalarType.UINT32),
subCmd: ProtoField(3, ScalarType.UINT32),
field6: ProtoField(6, ScalarType.UINT32),
};
export const PlatInfo = {
imPlat: ProtoField(1, ScalarType.UINT32),
osVersion: ProtoField(2, ScalarType.STRING, true),
qVersion: ProtoField(3, ScalarType.STRING, true),
};
export const FaceRoamResponse = {
retCode: ProtoField(1, ScalarType.UINT32),
errMsg: ProtoField(2, ScalarType.STRING),
subCmd: ProtoField(3, ScalarType.UINT32),
userInfo: ProtoField(6, () => FaceRoamUserInfo),
};
export const FaceRoamUserInfo = {
fileName: ProtoField(1, ScalarType.STRING, false, true),
deleteFile: ProtoField(2, ScalarType.STRING, false, true),
bid: ProtoField(3, ScalarType.STRING),
maxRoamSize: ProtoField(4, ScalarType.UINT32),
emojiType: ProtoField(5, ScalarType.UINT32, false, true),
};
export const SendMessageRequest = {
state: ProtoField(1, ScalarType.INT32),
sizeCache: ProtoField(2, ScalarType.INT32),
unknownFields: ProtoField(3, ScalarType.BYTES),
routingHead: ProtoField(4, () => RoutingHead),
contentHead: ProtoField(5, () => ContentHead),
messageBody: ProtoField(6, () => MessageBody),
msgSeq: ProtoField(7, ScalarType.INT32),
msgRand: ProtoField(8, ScalarType.INT32),
syncCookie: ProtoField(9, ScalarType.BYTES),
msgVia: ProtoField(10, ScalarType.INT32),
dataStatist: ProtoField(11, ScalarType.INT32),
messageControl: ProtoField(12, () => MessageControl),
multiSendSeq: ProtoField(13, ScalarType.INT32),
};
export const SendMessageResponse = {
result: ProtoField(1, ScalarType.INT32),
errMsg: ProtoField(2, ScalarType.STRING, true),
timestamp1: ProtoField(3, ScalarType.UINT32),
field10: ProtoField(10, ScalarType.UINT32),
groupSequence: ProtoField(11, ScalarType.UINT32, true),
timestamp2: ProtoField(12, ScalarType.UINT32),
privateSequence: ProtoField(14, ScalarType.UINT32),
};
export const SetStatus = {
status: ProtoField(1, ScalarType.UINT32),
extStatus: ProtoField(2, ScalarType.UINT32),
batteryStatus: ProtoField(3, ScalarType.UINT32),
customExt: ProtoField(4, () => SetStatusCustomExt, true),
};
export const SetStatusCustomExt = {
faceId: ProtoField(1, ScalarType.UINT32),
text: ProtoField(2, ScalarType.STRING, true),
field3: ProtoField(3, ScalarType.UINT32),
};
export const SetStatusResponse = {
message: ProtoField(2, ScalarType.STRING),
};
export const HttpConn = {
field1: ProtoField(1, ScalarType.INT32),
field2: ProtoField(2, ScalarType.INT32),
field3: ProtoField(3, ScalarType.INT32),
field4: ProtoField(4, ScalarType.INT32),
tgt: ProtoField(5, ScalarType.STRING),
field6: ProtoField(6, ScalarType.INT32),
serviceTypes: ProtoField(7, ScalarType.INT32, false, true),
field9: ProtoField(9, ScalarType.INT32),
field10: ProtoField(10, ScalarType.INT32),
field11: ProtoField(11, ScalarType.INT32),
ver: ProtoField(15, ScalarType.STRING),
};
export const HttpConn0x6ff_501 = {
httpConn: ProtoField(0x501, () => HttpConn),
};
export const HttpConn0x6ff_501Response = {
httpConn: ProtoField(0x501, () => HttpConnResponse),
};
export const HttpConnResponse = {
sigSession: ProtoField(1, ScalarType.BYTES),
sessionKey: ProtoField(2, ScalarType.BYTES),
serverInfos: ProtoField(3, () => ServerInfo, false, true),
};
export const ServerAddr = {
type: ProtoField(1, ScalarType.UINT32),
ip: ProtoField(2, ScalarType.FIXED32),
port: ProtoField(3, ScalarType.UINT32),
area: ProtoField(4, ScalarType.UINT32),
};
export const ServerInfo = {
serviceType: ProtoField(1, ScalarType.UINT32),
serverAddrs: ProtoField(2, () => ServerAddr, false, true),
};
@@ -0,0 +1,48 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const MiniAppAdaptShareInfoReq = {
appId: ProtoField(2, ScalarType.STRING),
body: ProtoField(4, () => MiniAppAdaptShareInfoReqBody),
};
export const MiniAppAdaptShareInfoReqBody = {
extInfo: ProtoField(1, () => ExtInfo),
appid: ProtoField(2, ScalarType.STRING),
title: ProtoField(3, ScalarType.STRING),
desc: ProtoField(4, ScalarType.STRING),
time: ProtoField(5, ScalarType.UINT64),
scene: ProtoField(6, ScalarType.UINT32),
templateType: ProtoField(7, ScalarType.UINT32),
businessType: ProtoField(8, ScalarType.UINT32),
picUrl: ProtoField(9, ScalarType.STRING),
vidUrl: ProtoField(10, ScalarType.STRING),
jumpUrl: ProtoField(11, ScalarType.STRING),
iconUrl: ProtoField(12, ScalarType.STRING),
verType: ProtoField(13, ScalarType.UINT32),
shareType: ProtoField(14, ScalarType.UINT32),
versionId: ProtoField(15, ScalarType.STRING),
withShareTicket: ProtoField(16, ScalarType.UINT32),
webURL: ProtoField(17, ScalarType.STRING),
appidRich: ProtoField(18, ScalarType.BYTES),
template: ProtoField(19, () => Template),
field20: ProtoField(20, ScalarType.STRING),
};
export const ExtInfo = {
field2: ProtoField(2, ScalarType.BYTES),
};
export const Template = {
templateId: ProtoField(1, ScalarType.STRING),
templateData: ProtoField(2, ScalarType.STRING),
};
export const MiniAppAdaptShareInfoResp = {
field2: ProtoField(2, ScalarType.UINT32),
field3: ProtoField(3, ScalarType.STRING),
content: ProtoField(4, () => MiniAppAdaptShareInfoRespContent),
};
export const MiniAppAdaptShareInfoRespContent = {
jsonContent: ProtoField(2, ScalarType.STRING),
};
@@ -0,0 +1,154 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
import { MsgInfoBody } from '@/napcat-core/packet/transformer/proto';
export const DataHighwayHead = {
version: ProtoField(1, ScalarType.UINT32),
uin: ProtoField(2, ScalarType.STRING, true),
command: ProtoField(3, ScalarType.STRING, true),
seq: ProtoField(4, ScalarType.UINT32, true),
retryTimes: ProtoField(5, ScalarType.UINT32, true),
appId: ProtoField(6, ScalarType.UINT32),
dataFlag: ProtoField(7, ScalarType.UINT32),
commandId: ProtoField(8, ScalarType.UINT32),
buildVer: ProtoField(9, ScalarType.BYTES, true),
};
export const FileUploadExt = {
unknown1: ProtoField(1, ScalarType.INT32),
unknown2: ProtoField(2, ScalarType.INT32),
unknown3: ProtoField(3, ScalarType.INT32),
entry: ProtoField(100, () => FileUploadEntry),
unknown200: ProtoField(200, ScalarType.INT32),
};
export const FileUploadEntry = {
busiBuff: ProtoField(100, () => ExcitingBusiInfo),
fileEntry: ProtoField(200, () => ExcitingFileEntry),
clientInfo: ProtoField(300, () => ExcitingClientInfo),
fileNameInfo: ProtoField(400, () => ExcitingFileNameInfo),
host: ProtoField(500, () => ExcitingHostConfig),
};
export const ExcitingBusiInfo = {
busId: ProtoField(1, ScalarType.INT32),
senderUin: ProtoField(100, ScalarType.UINT64),
receiverUin: ProtoField(200, ScalarType.UINT64),
groupCode: ProtoField(400, ScalarType.UINT64),
};
export const ExcitingFileEntry = {
fileSize: ProtoField(100, ScalarType.UINT64),
md5: ProtoField(200, ScalarType.BYTES),
checkKey: ProtoField(300, ScalarType.BYTES),
md5S2: ProtoField(400, ScalarType.BYTES),
fileId: ProtoField(600, ScalarType.STRING),
uploadKey: ProtoField(700, ScalarType.BYTES),
};
export const ExcitingClientInfo = {
clientType: ProtoField(100, ScalarType.INT32),
appId: ProtoField(200, ScalarType.STRING),
terminalType: ProtoField(300, ScalarType.INT32),
clientVer: ProtoField(400, ScalarType.STRING),
unknown: ProtoField(600, ScalarType.INT32),
};
export const ExcitingFileNameInfo = {
fileName: ProtoField(100, ScalarType.STRING),
};
export const ExcitingHostConfig = {
hosts: ProtoField(200, () => ExcitingHostInfo, false, true),
};
export const ExcitingHostInfo = {
url: ProtoField(1, () => ExcitingUrlInfo),
port: ProtoField(2, ScalarType.UINT32),
};
export const ExcitingUrlInfo = {
unknown: ProtoField(1, ScalarType.INT32),
host: ProtoField(2, ScalarType.STRING),
};
export const LoginSigHead = {
uint32LoginSigType: ProtoField(1, ScalarType.UINT32),
bytesLoginSig: ProtoField(2, ScalarType.BYTES),
appId: ProtoField(3, ScalarType.UINT32),
};
export const NTV2RichMediaHighwayExt = {
fileUuid: ProtoField(1, ScalarType.STRING),
uKey: ProtoField(2, ScalarType.STRING),
network: ProtoField(5, () => NTHighwayNetwork),
msgInfoBody: ProtoField(6, () => MsgInfoBody, false, true),
blockSize: ProtoField(10, ScalarType.UINT32),
hash: ProtoField(11, () => NTHighwayHash),
};
export const NTHighwayHash = {
fileSha1: ProtoField(1, ScalarType.BYTES, false, true),
};
export const NTHighwayNetwork = {
ipv4s: ProtoField(1, () => NTHighwayIPv4, false, true),
};
export const NTHighwayIPv4 = {
domain: ProtoField(1, () => NTHighwayDomain),
port: ProtoField(2, ScalarType.UINT32),
};
export const NTHighwayDomain = {
isEnable: ProtoField(1, ScalarType.BOOL),
ip: ProtoField(2, ScalarType.STRING),
};
export const ReqDataHighwayHead = {
msgBaseHead: ProtoField(1, () => DataHighwayHead, true),
msgSegHead: ProtoField(2, () => SegHead, true),
bytesReqExtendInfo: ProtoField(3, ScalarType.BYTES, true),
timestamp: ProtoField(4, ScalarType.UINT64),
msgLoginSigHead: ProtoField(5, () => LoginSigHead, true),
};
export const RespDataHighwayHead = {
msgBaseHead: ProtoField(1, () => DataHighwayHead, true),
msgSegHead: ProtoField(2, () => SegHead, true),
errorCode: ProtoField(3, ScalarType.UINT32),
allowRetry: ProtoField(4, ScalarType.UINT32),
cacheCost: ProtoField(5, ScalarType.UINT32),
htCost: ProtoField(6, ScalarType.UINT32),
bytesRspExtendInfo: ProtoField(7, ScalarType.BYTES, true),
timestamp: ProtoField(8, ScalarType.UINT64),
range: ProtoField(9, ScalarType.UINT64),
isReset: ProtoField(10, ScalarType.UINT32),
};
export const SegHead = {
serviceId: ProtoField(1, ScalarType.UINT32, true),
filesize: ProtoField(2, ScalarType.UINT64),
dataOffset: ProtoField(3, ScalarType.UINT64, true),
dataLength: ProtoField(4, ScalarType.UINT32),
retCode: ProtoField(5, ScalarType.UINT32, true),
serviceTicket: ProtoField(6, ScalarType.BYTES),
flag: ProtoField(7, ScalarType.UINT32, true),
md5: ProtoField(8, ScalarType.BYTES),
fileMd5: ProtoField(9, ScalarType.BYTES),
cacheAddr: ProtoField(10, ScalarType.UINT32, true),
queryTimes: ProtoField(11, ScalarType.UINT32),
updateCacheIp: ProtoField(12, ScalarType.UINT32),
cachePort: ProtoField(13, ScalarType.UINT32, true),
};
export const GroupAvatarExtra = {
type: ProtoField(1, ScalarType.UINT32),
groupUin: ProtoField(2, ScalarType.UINT32),
field3: ProtoField(3, () => GroupAvatarExtraField3),
field5: ProtoField(5, ScalarType.UINT32),
field6: ProtoField(6, ScalarType.UINT32),
};
export const GroupAvatarExtraField3 = {
field1: ProtoField(1, ScalarType.UINT32),
};
@@ -0,0 +1,33 @@
// action folder
export * from './action/action';
export * from './action/miniAppAdaptShareInfo';
// highway folder
export * from './highway/highway';
// message folder
export * from './message/action';
export * from './message/c2c';
export * from './message/component';
export * from './message/element';
export * from './message/group';
export * from './message/message';
export * from './message/notify';
export * from './message/routing';
// oidb folder
export * from './oidb/common/Ntv2.RichMediaReq';
export * from './oidb/common/Ntv2.RichMediaResp';
export * from './oidb/Oidb.0x6D6';
export * from './oidb/Oidb.0x8FC_2';
export * from './oidb/Oidb.0x9067_202';
export * from './oidb/Oidb.0x929';
export * from './oidb/Oidb.0xE37_1200';
export * from './oidb/Oidb.0xE37_1700';
export * from './oidb/Oidb.0XE37_800';
export * from './oidb/Oidb.0xEB7';
export * from './oidb/Oidb.0xED3_1';
export * from './oidb/Oidb.0XFE1_2';
export * from './oidb/OidbBase';
export * from './oidb/Oidb.0xE07';
export * from './oidb/Oidb.0xf90_1';
@@ -0,0 +1,116 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
import { PushMsgBody } from '@/napcat-core/packet/transformer/proto';
export const LongMsgResult = {
action: ProtoField(2, () => LongMsgAction, false, true),
};
export const LongMsgAction = {
actionCommand: ProtoField(1, ScalarType.STRING),
actionData: ProtoField(2, () => LongMsgContent),
};
export const LongMsgContent = {
msgBody: ProtoField(1, () => PushMsgBody, false, true),
};
export const RecvLongMsgReq = {
info: ProtoField(1, () => RecvLongMsgInfo, true),
settings: ProtoField(15, () => LongMsgSettings, true),
};
export const RecvLongMsgInfo = {
uid: ProtoField(1, () => LongMsgUid, true),
resId: ProtoField(2, ScalarType.STRING, true),
acquire: ProtoField(3, ScalarType.BOOL),
};
export const LongMsgUid = {
uid: ProtoField(2, ScalarType.STRING, true),
};
export const LongMsgSettings = {
field1: ProtoField(1, ScalarType.UINT32),
field2: ProtoField(2, ScalarType.UINT32),
field3: ProtoField(3, ScalarType.UINT32),
field4: ProtoField(4, ScalarType.UINT32),
};
export const RecvLongMsgResp = {
result: ProtoField(1, () => RecvLongMsgResult),
settings: ProtoField(15, () => LongMsgSettings),
};
export const RecvLongMsgResult = {
resId: ProtoField(3, ScalarType.STRING),
payload: ProtoField(4, ScalarType.BYTES),
};
export const SendLongMsgReq = {
info: ProtoField(2, () => SendLongMsgInfo),
settings: ProtoField(15, () => LongMsgSettings),
};
export const SendLongMsgInfo = {
type: ProtoField(1, ScalarType.UINT32),
uid: ProtoField(2, () => LongMsgUid, true),
groupUin: ProtoField(3, ScalarType.UINT32, true),
payload: ProtoField(4, ScalarType.BYTES, true),
};
export const SendLongMsgResp = {
result: ProtoField(2, () => SendLongMsgResult),
settings: ProtoField(15, () => LongMsgSettings),
};
export const SendLongMsgResult = {
resId: ProtoField(3, ScalarType.STRING),
};
export const SsoGetGroupMsg = {
info: ProtoField(1, () => SsoGetGroupMsgInfo),
direction: ProtoField(2, ScalarType.BOOL),
};
export const SsoGetGroupMsgInfo = {
groupUin: ProtoField(1, ScalarType.UINT32),
startSequence: ProtoField(2, ScalarType.UINT32),
endSequence: ProtoField(3, ScalarType.UINT32),
};
export const SsoGetGroupMsgResponse = {
body: ProtoField(3, () => SsoGetGroupMsgResponseBody),
};
export const SsoGetGroupMsgResponseBody = {
groupUin: ProtoField(3, ScalarType.UINT32),
startSequence: ProtoField(4, ScalarType.UINT32),
endSequence: ProtoField(5, ScalarType.UINT32),
messages: ProtoField(6, () => PushMsgBody, false, true),
};
export const SsoGetRoamMsg = {
friendUid: ProtoField(1, ScalarType.STRING, true),
time: ProtoField(2, ScalarType.UINT32),
random: ProtoField(3, ScalarType.UINT32),
count: ProtoField(4, ScalarType.UINT32),
direction: ProtoField(5, ScalarType.BOOL),
};
export const SsoGetRoamMsgResponse = {
friendUid: ProtoField(3, ScalarType.STRING),
timestamp: ProtoField(5, ScalarType.UINT32),
random: ProtoField(6, ScalarType.UINT32),
messages: ProtoField(7, () => PushMsgBody, false, true),
};
export const SsoGetC2cMsg = {
friendUid: ProtoField(2, ScalarType.STRING, true),
startSequence: ProtoField(3, ScalarType.UINT32),
endSequence: ProtoField(4, ScalarType.UINT32),
};
export const SsoGetC2cMsgResponse = {
friendUid: ProtoField(4, ScalarType.STRING),
messages: ProtoField(7, () => PushMsgBody, false, true),
};
@@ -0,0 +1,10 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const C2C = {
uin: ProtoField(1, ScalarType.UINT32, true),
uid: ProtoField(2, ScalarType.STRING, true),
field3: ProtoField(3, ScalarType.UINT32, true),
sig: ProtoField(4, ScalarType.UINT32, true),
receiverUin: ProtoField(5, ScalarType.UINT32, true),
receiverUid: ProtoField(6, ScalarType.STRING, true),
};
@@ -0,0 +1,165 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
import { Elem } from '@/napcat-core/packet/transformer/proto';
export const Attr = {
codePage: ProtoField(1, ScalarType.INT32),
time: ProtoField(2, ScalarType.INT32),
random: ProtoField(3, ScalarType.INT32),
color: ProtoField(4, ScalarType.INT32),
size: ProtoField(5, ScalarType.INT32),
effect: ProtoField(6, ScalarType.INT32),
charSet: ProtoField(7, ScalarType.INT32),
pitchAndFamily: ProtoField(8, ScalarType.INT32),
fontName: ProtoField(9, ScalarType.STRING),
reserveData: ProtoField(10, ScalarType.BYTES),
};
export const NotOnlineFile = {
fileType: ProtoField(1, ScalarType.INT32, true),
sig: ProtoField(2, ScalarType.BYTES, true),
fileUuid: ProtoField(3, ScalarType.STRING, true),
fileMd5: ProtoField(4, ScalarType.BYTES, true),
fileName: ProtoField(5, ScalarType.STRING, true),
fileSize: ProtoField(6, ScalarType.INT64, true),
note: ProtoField(7, ScalarType.BYTES, true),
reserved: ProtoField(8, ScalarType.INT32, true),
subcmd: ProtoField(9, ScalarType.INT32, true),
microCloud: ProtoField(10, ScalarType.INT32, true),
bytesFileUrls: ProtoField(11, ScalarType.BYTES, false, true),
downloadFlag: ProtoField(12, ScalarType.INT32, true),
dangerEvel: ProtoField(50, ScalarType.INT32, true),
lifeTime: ProtoField(51, ScalarType.INT32, true),
uploadTime: ProtoField(52, ScalarType.INT32, true),
absFileType: ProtoField(53, ScalarType.INT32, true),
clientType: ProtoField(54, ScalarType.INT32, true),
expireTime: ProtoField(55, ScalarType.INT32, true),
pbReserve: ProtoField(56, ScalarType.BYTES, true),
fileHash: ProtoField(57, ScalarType.STRING, true),
};
export const Ptt = {
fileType: ProtoField(1, ScalarType.INT32),
srcUin: ProtoField(2, ScalarType.UINT64),
fileUuid: ProtoField(3, ScalarType.STRING),
fileMd5: ProtoField(4, ScalarType.BYTES),
fileName: ProtoField(5, ScalarType.STRING),
fileSize: ProtoField(6, ScalarType.INT32),
reserve: ProtoField(7, ScalarType.BYTES),
fileId: ProtoField(8, ScalarType.INT32),
serverIp: ProtoField(9, ScalarType.INT32),
serverPort: ProtoField(10, ScalarType.INT32),
boolValid: ProtoField(11, ScalarType.BOOL),
signature: ProtoField(12, ScalarType.BYTES),
shortcut: ProtoField(13, ScalarType.BYTES),
fileKey: ProtoField(14, ScalarType.BYTES),
magicPttIndex: ProtoField(15, ScalarType.INT32),
voiceSwitch: ProtoField(16, ScalarType.INT32),
pttUrl: ProtoField(17, ScalarType.BYTES),
groupFileKey: ProtoField(18, ScalarType.STRING),
time: ProtoField(19, ScalarType.INT32),
downPara: ProtoField(20, ScalarType.BYTES),
format: ProtoField(29, ScalarType.INT32),
pbReserve: ProtoField(30, ScalarType.BYTES),
bytesPttUrls: ProtoField(31, ScalarType.BYTES, false, true),
downloadFlag: ProtoField(32, ScalarType.INT32),
};
export const RichText = {
attr: ProtoField(1, () => Attr, true),
elems: ProtoField(2, () => Elem, false, true),
notOnlineFile: ProtoField(3, () => NotOnlineFile, true),
ptt: ProtoField(4, () => Ptt, true),
};
export const ButtonExtra = {
data: ProtoField(1, () => KeyboardData),
};
export const KeyboardData = {
rows: ProtoField(1, () => Row, false, true),
};
export const Row = {
buttons: ProtoField(1, () => Button, false, true),
};
export const Button = {
id: ProtoField(1, ScalarType.STRING),
renderData: ProtoField(2, () => RenderData),
action: ProtoField(3, () => Action),
};
export const RenderData = {
label: ProtoField(1, ScalarType.STRING),
visitedLabel: ProtoField(2, ScalarType.STRING),
style: ProtoField(3, ScalarType.INT32),
};
export const Action = {
type: ProtoField(1, ScalarType.INT32),
permission: ProtoField(2, () => Permission),
unsupportTips: ProtoField(4, ScalarType.STRING),
data: ProtoField(5, ScalarType.STRING),
reply: ProtoField(7, ScalarType.BOOL),
enter: ProtoField(8, ScalarType.BOOL),
};
export const Permission = {
type: ProtoField(1, ScalarType.INT32),
specifyRoleIds: ProtoField(2, ScalarType.STRING, false, true),
specifyUserIds: ProtoField(3, ScalarType.STRING, false, true),
};
export const FileExtra = {
file: ProtoField(1, () => NotOnlineFile),
field6: ProtoField(6, () => PrivateFileExtra),
};
export const PrivateFileExtra = {
field2: ProtoField(2, () => PrivateFileExtraField2),
};
export const PrivateFileExtraField2 = {
field1: ProtoField(1, ScalarType.UINT32),
fileUuid: ProtoField(4, ScalarType.STRING),
fileName: ProtoField(5, ScalarType.STRING),
field6: ProtoField(6, ScalarType.UINT32),
field7: ProtoField(7, ScalarType.BYTES),
field8: ProtoField(8, ScalarType.BYTES),
timestamp1: ProtoField(9, ScalarType.UINT32),
fileHash: ProtoField(14, ScalarType.STRING),
selfUid: ProtoField(15, ScalarType.STRING),
destUid: ProtoField(16, ScalarType.STRING),
};
export const GroupFileExtra = {
field1: ProtoField(1, ScalarType.UINT32),
fileName: ProtoField(2, ScalarType.STRING),
display: ProtoField(3, ScalarType.STRING),
inner: ProtoField(7, () => GroupFileExtraInner),
};
export const GroupFileExtraInner = {
info: ProtoField(2, () => GroupFileExtraInfo),
};
export const GroupFileExtraInfo = {
busId: ProtoField(1, ScalarType.UINT32),
fileId: ProtoField(2, ScalarType.STRING),
fileSize: ProtoField(3, ScalarType.UINT64),
fileName: ProtoField(4, ScalarType.STRING),
field5: ProtoField(5, ScalarType.UINT32),
fileSha: ProtoField(6, ScalarType.BYTES),
extInfoString: ProtoField(7, ScalarType.STRING),
fileMd5: ProtoField(8, ScalarType.BYTES),
};
export const ImageExtraUrl = {
origUrl: ProtoField(30, ScalarType.STRING),
};
export const PokeExtra = {
type: ProtoField(1, ScalarType.UINT32),
field7: ProtoField(7, ScalarType.UINT32),
field8: ProtoField(8, ScalarType.UINT32),
};
@@ -0,0 +1,360 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const Elem = {
text: ProtoField(1, () => Text, true),
face: ProtoField(2, () => Face, true),
onlineImage: ProtoField(3, () => OnlineImage, true),
notOnlineImage: ProtoField(4, () => NotOnlineImage, true),
transElem: ProtoField(5, () => TransElem, true),
marketFace: ProtoField(6, () => MarketFace, true),
customFace: ProtoField(8, () => CustomFace, true),
elemFlags2: ProtoField(9, () => ElemFlags2, true),
richMsg: ProtoField(12, () => RichMsg, true),
groupFile: ProtoField(13, () => GroupFile, true),
extraInfo: ProtoField(16, () => ExtraInfo, true),
videoFile: ProtoField(19, () => VideoFile, true),
anonymousGroupMessage: ProtoField(21, () => AnonymousGroupMessage, true),
customElem: ProtoField(31, () => CustomElem, true),
generalFlags: ProtoField(37, () => GeneralFlags, true),
srcMsg: ProtoField(45, () => SrcMsg, true),
lightAppElem: ProtoField(51, () => LightAppElem, true),
commonElem: ProtoField(53, () => CommonElem, true),
};
export const Text = {
str: ProtoField(1, ScalarType.STRING, true),
lint: ProtoField(2, ScalarType.STRING, true),
attr6Buf: ProtoField(3, ScalarType.BYTES, true),
attr7Buf: ProtoField(4, ScalarType.BYTES, true),
buf: ProtoField(11, ScalarType.BYTES, true),
pbReserve: ProtoField(12, ScalarType.BYTES, true),
};
export const Face = {
index: ProtoField(1, ScalarType.INT32, true),
old: ProtoField(2, ScalarType.BYTES, true),
buf: ProtoField(11, ScalarType.BYTES, true),
};
export const OnlineImage = {
guid: ProtoField(1, ScalarType.BYTES),
filePath: ProtoField(2, ScalarType.BYTES),
oldVerSendFile: ProtoField(3, ScalarType.BYTES),
};
export const NotOnlineImage = {
filePath: ProtoField(1, ScalarType.STRING),
fileLen: ProtoField(2, ScalarType.UINT32),
downloadPath: ProtoField(3, ScalarType.STRING),
oldVerSendFile: ProtoField(4, ScalarType.BYTES),
imgType: ProtoField(5, ScalarType.INT32),
previewsImage: ProtoField(6, ScalarType.BYTES),
picMd5: ProtoField(7, ScalarType.BYTES),
picHeight: ProtoField(8, ScalarType.UINT32),
picWidth: ProtoField(9, ScalarType.UINT32),
resId: ProtoField(10, ScalarType.STRING),
flag: ProtoField(11, ScalarType.BYTES),
thumbUrl: ProtoField(12, ScalarType.STRING),
original: ProtoField(13, ScalarType.INT32),
bigUrl: ProtoField(14, ScalarType.STRING),
origUrl: ProtoField(15, ScalarType.STRING),
bizType: ProtoField(16, ScalarType.INT32),
result: ProtoField(17, ScalarType.INT32),
index: ProtoField(18, ScalarType.INT32),
opFaceBuf: ProtoField(19, ScalarType.BYTES),
oldPicMd5: ProtoField(20, ScalarType.BOOL),
thumbWidth: ProtoField(21, ScalarType.INT32),
thumbHeight: ProtoField(22, ScalarType.INT32),
fileId: ProtoField(23, ScalarType.INT32),
showLen: ProtoField(24, ScalarType.UINT32),
downloadLen: ProtoField(25, ScalarType.UINT32),
x400Url: ProtoField(26, ScalarType.STRING),
x400Width: ProtoField(27, ScalarType.INT32),
x400Height: ProtoField(28, ScalarType.INT32),
pbRes: ProtoField(29, () => NotOnlineImage_PbReserve),
};
export const NotOnlineImage_PbReserve = {
subType: ProtoField(1, ScalarType.INT32),
field3: ProtoField(3, ScalarType.INT32),
field4: ProtoField(4, ScalarType.INT32),
summary: ProtoField(8, ScalarType.STRING),
field10: ProtoField(10, ScalarType.INT32),
field20: ProtoField(20, () => NotOnlineImage_PbReserve2),
url: ProtoField(30, ScalarType.STRING),
md5Str: ProtoField(31, ScalarType.STRING),
};
export const NotOnlineImage_PbReserve2 = {
field1: ProtoField(1, ScalarType.INT32),
field2: ProtoField(2, ScalarType.STRING),
field3: ProtoField(3, ScalarType.INT32),
field4: ProtoField(4, ScalarType.INT32),
field5: ProtoField(5, ScalarType.INT32),
field7: ProtoField(7, ScalarType.STRING),
};
export const TransElem = {
elemType: ProtoField(1, ScalarType.INT32),
elemValue: ProtoField(2, ScalarType.BYTES),
};
export const MarketFace = {
faceName: ProtoField(1, ScalarType.STRING),
itemType: ProtoField(2, ScalarType.INT32),
faceInfo: ProtoField(3, ScalarType.INT32),
faceId: ProtoField(4, ScalarType.BYTES),
tabId: ProtoField(5, ScalarType.INT32),
subType: ProtoField(6, ScalarType.INT32),
key: ProtoField(7, ScalarType.STRING),
param: ProtoField(8, ScalarType.BYTES),
mediaType: ProtoField(9, ScalarType.INT32),
imageWidth: ProtoField(10, ScalarType.INT32),
imageHeight: ProtoField(11, ScalarType.INT32),
mobileparam: ProtoField(12, ScalarType.BYTES),
pbReserve: ProtoField(13, () => MarketFacePbRes),
};
export const MarketFacePbRes = {
field8: ProtoField(8, ScalarType.INT32),
};
export const CustomFace = {
guid: ProtoField(1, ScalarType.BYTES),
filePath: ProtoField(2, ScalarType.STRING),
shortcut: ProtoField(3, ScalarType.STRING),
buffer: ProtoField(4, ScalarType.BYTES),
flag: ProtoField(5, ScalarType.BYTES),
oldData: ProtoField(6, ScalarType.BYTES, true),
fileId: ProtoField(7, ScalarType.UINT32),
serverIp: ProtoField(8, ScalarType.INT32, true),
serverPort: ProtoField(9, ScalarType.INT32, true),
fileType: ProtoField(10, ScalarType.INT32),
signature: ProtoField(11, ScalarType.BYTES),
useful: ProtoField(12, ScalarType.INT32),
md5: ProtoField(13, ScalarType.BYTES),
thumbUrl: ProtoField(14, ScalarType.STRING),
bigUrl: ProtoField(15, ScalarType.STRING),
origUrl: ProtoField(16, ScalarType.STRING),
bizType: ProtoField(17, ScalarType.INT32),
repeatIndex: ProtoField(18, ScalarType.INT32),
repeatImage: ProtoField(19, ScalarType.INT32),
imageType: ProtoField(20, ScalarType.INT32),
index: ProtoField(21, ScalarType.INT32),
width: ProtoField(22, ScalarType.INT32),
height: ProtoField(23, ScalarType.INT32),
source: ProtoField(24, ScalarType.INT32),
size: ProtoField(25, ScalarType.UINT32),
origin: ProtoField(26, ScalarType.INT32),
thumbWidth: ProtoField(27, ScalarType.INT32, true),
thumbHeight: ProtoField(28, ScalarType.INT32, true),
showLen: ProtoField(29, ScalarType.INT32),
downloadLen: ProtoField(30, ScalarType.INT32),
x400Url: ProtoField(31, ScalarType.STRING, true),
x400Width: ProtoField(32, ScalarType.INT32),
x400Height: ProtoField(33, ScalarType.INT32),
pbRes: ProtoField(34, () => CustomFace_PbReserve, true),
};
export const CustomFace_PbReserve = {
subType: ProtoField(1, ScalarType.INT32),
summary: ProtoField(9, ScalarType.STRING),
};
export const ElemFlags2 = {
colorTextId: ProtoField(1, ScalarType.UINT32),
msgId: ProtoField(2, ScalarType.UINT64),
whisperSessionId: ProtoField(3, ScalarType.UINT32),
pttChangeBit: ProtoField(4, ScalarType.UINT32),
vipStatus: ProtoField(5, ScalarType.UINT32),
compatibleId: ProtoField(6, ScalarType.UINT32),
insts: ProtoField(7, () => Instance, false, true),
msgRptCnt: ProtoField(8, ScalarType.UINT32),
srcInst: ProtoField(9, () => Instance),
longtitude: ProtoField(10, ScalarType.UINT32),
latitude: ProtoField(11, ScalarType.UINT32),
customFont: ProtoField(12, ScalarType.UINT32),
pcSupportDef: ProtoField(13, () => PcSupportDef),
crmFlags: ProtoField(14, ScalarType.UINT32, true),
};
export const PcSupportDef = {
pcPtlBegin: ProtoField(1, ScalarType.UINT32),
pcPtlEnd: ProtoField(2, ScalarType.UINT32),
macPtlBegin: ProtoField(3, ScalarType.UINT32),
macPtlEnd: ProtoField(4, ScalarType.UINT32),
ptlsSupport: ProtoField(5, ScalarType.INT32, false, true),
ptlsNotSupport: ProtoField(6, ScalarType.UINT32, false, true),
};
export const Instance = {
appId: ProtoField(1, ScalarType.UINT32),
instId: ProtoField(2, ScalarType.UINT32),
};
export const RichMsg = {
template1: ProtoField(1, ScalarType.BYTES, true),
serviceId: ProtoField(2, ScalarType.INT32, true),
msgResId: ProtoField(3, ScalarType.BYTES, true),
rand: ProtoField(4, ScalarType.INT32, true),
seq: ProtoField(5, ScalarType.UINT32, true),
};
export const GroupFile = {
filename: ProtoField(1, ScalarType.BYTES),
fileSize: ProtoField(2, ScalarType.UINT64),
fileId: ProtoField(3, ScalarType.BYTES),
batchId: ProtoField(4, ScalarType.BYTES),
fileKey: ProtoField(5, ScalarType.BYTES),
mark: ProtoField(6, ScalarType.BYTES),
sequence: ProtoField(7, ScalarType.UINT64),
batchItemId: ProtoField(8, ScalarType.BYTES),
feedMsgTime: ProtoField(9, ScalarType.INT32),
pbReserve: ProtoField(10, ScalarType.BYTES),
};
export const ExtraInfo = {
nick: ProtoField(1, ScalarType.BYTES),
groupCard: ProtoField(2, ScalarType.BYTES),
level: ProtoField(3, ScalarType.INT32),
flags: ProtoField(4, ScalarType.INT32),
groupMask: ProtoField(5, ScalarType.INT32),
msgTailId: ProtoField(6, ScalarType.INT32),
senderTitle: ProtoField(7, ScalarType.BYTES),
apnsTips: ProtoField(8, ScalarType.BYTES),
uin: ProtoField(9, ScalarType.UINT64),
msgStateFlag: ProtoField(10, ScalarType.INT32),
apnsSoundType: ProtoField(11, ScalarType.INT32),
newGroupFlag: ProtoField(12, ScalarType.INT32),
};
export const VideoFile = {
fileUuid: ProtoField(1, ScalarType.STRING),
fileMd5: ProtoField(2, ScalarType.BYTES),
fileName: ProtoField(3, ScalarType.STRING),
fileFormat: ProtoField(4, ScalarType.INT32),
fileTime: ProtoField(5, ScalarType.INT32),
fileSize: ProtoField(6, ScalarType.INT32),
thumbWidth: ProtoField(7, ScalarType.INT32),
thumbHeight: ProtoField(8, ScalarType.INT32),
thumbFileMd5: ProtoField(9, ScalarType.BYTES),
source: ProtoField(10, ScalarType.BYTES),
thumbFileSize: ProtoField(11, ScalarType.INT32),
busiType: ProtoField(12, ScalarType.INT32),
fromChatType: ProtoField(13, ScalarType.INT32),
toChatType: ProtoField(14, ScalarType.INT32),
boolSupportProgressive: ProtoField(15, ScalarType.BOOL),
fileWidth: ProtoField(16, ScalarType.INT32),
fileHeight: ProtoField(17, ScalarType.INT32),
subBusiType: ProtoField(18, ScalarType.INT32),
videoAttr: ProtoField(19, ScalarType.INT32),
bytesThumbFileUrls: ProtoField(20, ScalarType.BYTES, false, true),
bytesVideoFileUrls: ProtoField(21, ScalarType.BYTES, false, true),
thumbDownloadFlag: ProtoField(22, ScalarType.INT32),
videoDownloadFlag: ProtoField(23, ScalarType.INT32),
pbReserve: ProtoField(24, ScalarType.BYTES),
};
export const AnonymousGroupMessage = {
flags: ProtoField(1, ScalarType.INT32),
anonId: ProtoField(2, ScalarType.BYTES),
anonNick: ProtoField(3, ScalarType.BYTES),
headPortrait: ProtoField(4, ScalarType.INT32),
expireTime: ProtoField(5, ScalarType.INT32),
bubbleId: ProtoField(6, ScalarType.INT32),
rankColor: ProtoField(7, ScalarType.BYTES),
};
export const CustomElem = {
desc: ProtoField(1, ScalarType.BYTES),
data: ProtoField(2, ScalarType.BYTES),
enumType: ProtoField(3, ScalarType.INT32),
ext: ProtoField(4, ScalarType.BYTES),
sound: ProtoField(5, ScalarType.BYTES),
};
export const GeneralFlags = {
bubbleDiyTextId: ProtoField(1, ScalarType.INT32),
groupFlagNew: ProtoField(2, ScalarType.INT32),
uin: ProtoField(3, ScalarType.UINT64),
rpId: ProtoField(4, ScalarType.BYTES),
prpFold: ProtoField(5, ScalarType.INT32),
longTextFlag: ProtoField(6, ScalarType.INT32),
longTextResId: ProtoField(7, ScalarType.STRING, true),
groupType: ProtoField(8, ScalarType.INT32),
toUinFlag: ProtoField(9, ScalarType.INT32),
glamourLevel: ProtoField(10, ScalarType.INT32),
memberLevel: ProtoField(11, ScalarType.INT32),
groupRankSeq: ProtoField(12, ScalarType.UINT64),
olympicTorch: ProtoField(13, ScalarType.INT32),
babyqGuideMsgCookie: ProtoField(14, ScalarType.BYTES),
uin32ExpertFlag: ProtoField(15, ScalarType.INT32),
bubbleSubId: ProtoField(16, ScalarType.INT32),
pendantId: ProtoField(17, ScalarType.UINT64),
rpIndex: ProtoField(18, ScalarType.BYTES),
pbReserve: ProtoField(19, ScalarType.BYTES),
};
export const SrcMsg = {
origSeqs: ProtoField(1, ScalarType.UINT32, false, true),
senderUin: ProtoField(2, ScalarType.UINT64),
time: ProtoField(3, ScalarType.INT32, true),
flag: ProtoField(4, ScalarType.INT32, true),
elems: ProtoField(5, () => Elem, false, true),
type: ProtoField(6, ScalarType.INT32, true),
richMsg: ProtoField(7, ScalarType.BYTES, true),
pbReserve: ProtoField(8, () => SrcMsgPbRes, true),
sourceMsg: ProtoField(9, ScalarType.BYTES, true),
toUin: ProtoField(10, ScalarType.UINT64, true),
troopName: ProtoField(11, ScalarType.BYTES, true),
};
export const SrcMsgPbRes = {
messageId: ProtoField(3, ScalarType.UINT64),
senderUid: ProtoField(6, ScalarType.STRING, true),
receiverUid: ProtoField(7, ScalarType.STRING, true),
friendSeq: ProtoField(8, ScalarType.UINT32, true),
};
export const LightAppElem = {
data: ProtoField(1, ScalarType.BYTES),
msgResid: ProtoField(2, ScalarType.BYTES, true),
};
export const CommonElem = {
serviceType: ProtoField(1, ScalarType.INT32),
pbElem: ProtoField(2, ScalarType.BYTES),
businessType: ProtoField(3, ScalarType.UINT32),
};
export const FaceExtra = {
faceId: ProtoField(1, ScalarType.INT32, true),
};
export const MentionExtra = {
type: ProtoField(3, ScalarType.INT32, true),
uin: ProtoField(4, ScalarType.UINT32, true),
field5: ProtoField(5, ScalarType.INT32, true),
uid: ProtoField(9, ScalarType.STRING, true),
};
export const QBigFaceExtra = {
AniStickerPackId: ProtoField(1, ScalarType.STRING, true),
AniStickerId: ProtoField(2, ScalarType.STRING, true),
faceId: ProtoField(3, ScalarType.INT32, true),
sourceType: ProtoField(4, ScalarType.INT32, true),
AniStickerType: ProtoField(5, ScalarType.INT32, true),
resultId: ProtoField(6, ScalarType.STRING, true),
preview: ProtoField(7, ScalarType.STRING, true),
randomType: ProtoField(9, ScalarType.INT32, true),
};
export const QSmallFaceExtra = {
faceId: ProtoField(1, ScalarType.UINT32),
preview: ProtoField(2, ScalarType.STRING),
preview2: ProtoField(3, ScalarType.STRING),
};
export const MarkdownData = {
content: ProtoField(1, ScalarType.STRING),
};
@@ -0,0 +1,18 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const GroupRecallMsg = {
type: ProtoField(1, ScalarType.UINT32),
groupUin: ProtoField(2, ScalarType.UINT32),
field3: ProtoField(3, () => GroupRecallMsgField3),
field4: ProtoField(4, () => GroupRecallMsgField4),
};
export const GroupRecallMsgField3 = {
sequence: ProtoField(1, ScalarType.UINT32),
random: ProtoField(2, ScalarType.UINT32),
field3: ProtoField(3, ScalarType.UINT32),
};
export const GroupRecallMsgField4 = {
field1: ProtoField(1, ScalarType.UINT32),
};
@@ -0,0 +1,18 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const GroupAdminExtra = {
adminUid: ProtoField(1, ScalarType.STRING),
isPromote: ProtoField(2, ScalarType.BOOL),
};
export const GroupAdminBody = {
extraDisable: ProtoField(1, () => GroupAdminExtra),
extraEnable: ProtoField(2, () => GroupAdminExtra),
};
export const GroupAdmin = {
groupUin: ProtoField(1, ScalarType.UINT32),
flag: ProtoField(2, ScalarType.UINT32),
isPromote: ProtoField(3, ScalarType.BOOL),
body: ProtoField(4, () => GroupAdminBody),
};
@@ -0,0 +1,138 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
import {
C2C,
ForwardHead,
Grp,
GrpTmp,
ResponseForward,
ResponseGrp, RichText,
Trans0X211,
WPATmp,
} from '@/napcat-core/packet/transformer/proto';
export const ContentHead = {
type: ProtoField(1, ScalarType.UINT32),
subType: ProtoField(2, ScalarType.UINT32, true),
c2cCmd: ProtoField(3, ScalarType.UINT32, true),
ranDom: ProtoField(4, ScalarType.UINT32, true),
sequence: ProtoField(5, ScalarType.UINT32, true),
timeStamp: ProtoField(6, ScalarType.UINT32, true),
pkgNum: ProtoField(7, ScalarType.UINT64, true),
pkgIndex: ProtoField(8, ScalarType.UINT32, true),
divSeq: ProtoField(9, ScalarType.UINT32, true),
autoReply: ProtoField(10, ScalarType.UINT32),
ntMsgSeq: ProtoField(10, ScalarType.UINT32, true),
newId: ProtoField(12, ScalarType.UINT64, true),
forward: ProtoField(15, () => ForwardHead, true),
};
export const MessageBody = {
richText: ProtoField(1, () => RichText, true),
msgContent: ProtoField(2, ScalarType.BYTES, true),
msgEncryptContent: ProtoField(3, ScalarType.BYTES, true),
};
export const Message = {
routingHead: ProtoField(1, () => RoutingHead, true),
contentHead: ProtoField(2, () => ContentHead, true),
body: ProtoField(3, () => MessageBody, true),
clientSequence: ProtoField(4, ScalarType.UINT32, true),
random: ProtoField(5, ScalarType.UINT32, true),
syncCookie: ProtoField(6, ScalarType.BYTES, true),
via: ProtoField(8, ScalarType.UINT32, true),
dataStatist: ProtoField(9, ScalarType.UINT32, true),
ctrl: ProtoField(12, () => MessageControl, true),
multiSendSeq: ProtoField(14, ScalarType.UINT32),
};
export const MessageControl = {
msgFlag: ProtoField(1, ScalarType.INT32),
};
export const PushMsg = {
message: ProtoField(1, () => PushMsgBody),
status: ProtoField(3, ScalarType.INT32, true),
pingFlag: ProtoField(5, ScalarType.INT32, true),
generalFlag: ProtoField(9, ScalarType.INT32, true),
};
export const GroupChangeInfo = {
operator: ProtoField(1, () => GroupChangeOperator, true),
};
export const GroupChangeOperator = {
operatorUid: ProtoField(1, ScalarType.STRING, true),
};
export const GroupChange = {
groupUin: ProtoField(1, ScalarType.UINT32),
flag: ProtoField(2, ScalarType.UINT32),
memberUid: ProtoField(3, ScalarType.STRING, true),
decreaseType: ProtoField(4, ScalarType.UINT32),
operatorInfo: ProtoField(5, ScalarType.BYTES, true),
increaseType: ProtoField(6, ScalarType.UINT32),
field7: ProtoField(7, ScalarType.BYTES, true),
};
// Group Reaction Related
export const GroupReactionDataInnerDataTarget = {
seq: ProtoField(1, ScalarType.UINT64, true),
};
export const GroupReactionDataContent = {
code: ProtoField(1, ScalarType.STRING, true),
count: ProtoField(3, ScalarType.UINT32, true),
operatorUid: ProtoField(4, ScalarType.STRING, true),
type: ProtoField(5, ScalarType.UINT32, true),
};
export const GroupReactionDataInnerData = {
groupReactionTarget: ProtoField(2, () => GroupReactionDataInnerDataTarget, true),
groupReactionDataContent: ProtoField(3, () => GroupReactionDataContent, true),
};
export const GroupReactionDataInner = {
data: ProtoField(1, () => GroupReactionDataInnerData, true),
};
export const GroupReactionData = {
data: ProtoField(1, () => GroupReactionDataInner, true),
};
export const GroupReactNotify = {
groupUin: ProtoField(4, ScalarType.UINT64, true),
field13: ProtoField(13, ScalarType.UINT32, true),
groupReactionData: ProtoField(44, () => GroupReactionData, true),
};
// Group Invite Related
export const GroupInvite = {
groupUin: ProtoField(1, ScalarType.UINT32),
field2: ProtoField(2, ScalarType.UINT32),
field3: ProtoField(2, ScalarType.UINT32),
field4: ProtoField(2, ScalarType.UINT32),
invitorUid: ProtoField(5, ScalarType.STRING),
};
export const PushMsgBody = {
responseHead: ProtoField(1, () => ResponseHead),
contentHead: ProtoField(2, () => ContentHead),
body: ProtoField(3, () => MessageBody, true),
};
export const ResponseHead = {
fromUin: ProtoField(1, ScalarType.UINT32),
fromUid: ProtoField(2, ScalarType.STRING, true),
type: ProtoField(3, ScalarType.UINT32),
sigMap: ProtoField(4, ScalarType.UINT32),
toUin: ProtoField(5, ScalarType.UINT32),
toUid: ProtoField(6, ScalarType.STRING, true),
forward: ProtoField(7, () => ResponseForward, true),
grp: ProtoField(8, () => ResponseGrp, true),
};
export const RoutingHead = {
c2c: ProtoField(1, () => C2C, true),
grp: ProtoField(2, () => Grp, true),
grpTmp: ProtoField(3, () => GrpTmp, true),
wpaTmp: ProtoField(6, () => WPATmp, true),
trans0X211: ProtoField(15, () => Trans0X211, true),
};
@@ -0,0 +1,21 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const FriendRecall = {
info: ProtoField(1, () => FriendRecallInfo),
instId: ProtoField(2, ScalarType.UINT32),
appId: ProtoField(3, ScalarType.UINT32),
longMessageFlag: ProtoField(4, ScalarType.UINT32),
reserved: ProtoField(5, ScalarType.BYTES),
};
export const FriendRecallInfo = {
fromUid: ProtoField(1, ScalarType.STRING),
toUid: ProtoField(2, ScalarType.STRING),
sequence: ProtoField(3, ScalarType.UINT32),
newId: ProtoField(4, ScalarType.UINT64),
time: ProtoField(5, ScalarType.UINT32),
random: ProtoField(6, ScalarType.UINT32),
pkgNum: ProtoField(7, ScalarType.UINT32),
pkgIndex: ProtoField(8, ScalarType.UINT32),
divSeq: ProtoField(9, ScalarType.UINT32),
};
@@ -0,0 +1,40 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const ForwardHead = {
field1: ProtoField(1, ScalarType.UINT32, true),
field2: ProtoField(2, ScalarType.UINT32, true),
field3: ProtoField(3, ScalarType.UINT32, true),
unknownBase64: ProtoField(5, ScalarType.STRING, true),
avatar: ProtoField(6, ScalarType.STRING, true),
};
export const Grp = {
groupCode: ProtoField(1, ScalarType.UINT32, true),
};
export const GrpTmp = {
groupUin: ProtoField(1, ScalarType.UINT32, true),
toUin: ProtoField(2, ScalarType.UINT32, true),
};
export const ResponseForward = {
friendName: ProtoField(6, ScalarType.STRING, true),
};
export const ResponseGrp = {
groupUin: ProtoField(1, ScalarType.UINT32),
memberName: ProtoField(4, ScalarType.STRING),
unknown5: ProtoField(5, ScalarType.UINT32),
groupName: ProtoField(7, ScalarType.STRING),
};
export const Trans0X211 = {
toUin: ProtoField(1, ScalarType.UINT64, true),
ccCmd: ProtoField(2, ScalarType.UINT32, true),
uid: ProtoField(8, ScalarType.STRING, true),
};
export const WPATmp = {
toUin: ProtoField(1, ScalarType.UINT64),
sig: ProtoField(2, ScalarType.BYTES),
};
@@ -0,0 +1,6 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const FileId = {
appid: ProtoField(4, ScalarType.UINT32, true),
ttl: ProtoField(10, ScalarType.UINT32, true),
};
@@ -0,0 +1,61 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
import { OidbSvcTrpcTcp0XE37_800_1200Metadata } from '@/napcat-core/packet/transformer/proto';
export const OidbSvcTrpcTcp0XE37_800 = {
subCommand: ProtoField(1, ScalarType.UINT32),
field2: ProtoField(2, ScalarType.INT32),
body: ProtoField(10, () => OidbSvcTrpcTcp0XE37_800Body, true),
field101: ProtoField(101, ScalarType.INT32),
field102: ProtoField(102, ScalarType.INT32),
field200: ProtoField(200, ScalarType.INT32),
};
export const OidbSvcTrpcTcp0XE37_800Body = {
senderUid: ProtoField(10, ScalarType.STRING, true),
receiverUid: ProtoField(20, ScalarType.STRING, true),
fileUuid: ProtoField(30, ScalarType.STRING, true),
fileHash: ProtoField(40, ScalarType.STRING, true),
};
export const OidbSvcTrpcTcp0XE37Response = {
command: ProtoField(1, ScalarType.UINT32),
seq: ProtoField(2, ScalarType.INT32),
upload: ProtoField(19, () => ApplyUploadRespV3, true),
businessId: ProtoField(101, ScalarType.INT32),
clientType: ProtoField(102, ScalarType.INT32),
flagSupportMediaPlatform: ProtoField(200, ScalarType.INT32),
};
export const ApplyUploadRespV3 = {
retCode: ProtoField(10, ScalarType.INT32),
retMsg: ProtoField(20, ScalarType.STRING, true),
totalSpace: ProtoField(30, ScalarType.INT64),
usedSpace: ProtoField(40, ScalarType.INT64),
uploadedSize: ProtoField(50, ScalarType.INT64),
uploadIp: ProtoField(60, ScalarType.STRING, true),
uploadDomain: ProtoField(70, ScalarType.STRING, true),
uploadPort: ProtoField(80, ScalarType.UINT32),
uuid: ProtoField(90, ScalarType.STRING, true),
uploadKey: ProtoField(100, ScalarType.BYTES, true),
boolFileExist: ProtoField(110, ScalarType.BOOL),
packSize: ProtoField(120, ScalarType.INT32),
uploadIpList: ProtoField(130, ScalarType.STRING, false, true), // repeated
uploadHttpsPort: ProtoField(140, ScalarType.INT32),
uploadHttpsDomain: ProtoField(150, ScalarType.STRING, true),
uploadDns: ProtoField(160, ScalarType.STRING, true),
uploadLanip: ProtoField(170, ScalarType.STRING, true),
fileAddon: ProtoField(200, ScalarType.STRING, true),
mediaPlatformUploadKey: ProtoField(220, ScalarType.BYTES, true),
};
export const OidbSvcTrpcTcp0XE37_800Response = {
command: ProtoField(1, ScalarType.UINT32, true),
subCommand: ProtoField(2, ScalarType.UINT32, true),
body: ProtoField(10, () => OidbSvcTrpcTcp0XE37_800ResponseBody, true),
field50: ProtoField(50, ScalarType.UINT32, true),
};
export const OidbSvcTrpcTcp0XE37_800ResponseBody = {
field10: ProtoField(10, ScalarType.UINT32, true),
field30: ProtoField(30, () => OidbSvcTrpcTcp0XE37_800_1200Metadata, true),
};
@@ -0,0 +1,22 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const OidbSvcTrpcTcp0XFE1_2 = {
uin: ProtoField(1, ScalarType.UINT32),
key: ProtoField(3, () => OidbSvcTrpcTcp0XFE1_2Key, false, true),
};
export const OidbSvcTrpcTcp0XFE1_2Key = {
key: ProtoField(1, ScalarType.UINT32),
};
export const OidbSvcTrpcTcp0XFE1_2RSP_Status = {
key: ProtoField(1, ScalarType.UINT32),
value: ProtoField(2, ScalarType.UINT64),
};
export const OidbSvcTrpcTcp0XFE1_2RSP_Data = {
status: ProtoField(2, () => OidbSvcTrpcTcp0XFE1_2RSP_Status),
};
export const OidbSvcTrpcTcp0XFE1_2RSP = {
data: ProtoField(1, () => OidbSvcTrpcTcp0XFE1_2RSP_Data),
};
@@ -0,0 +1,99 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const OidbSvcTrpcTcp0x6D6 = {
file: ProtoField(1, () => OidbSvcTrpcTcp0x6D6Upload, true),
download: ProtoField(3, () => OidbSvcTrpcTcp0x6D6Download, true),
delete: ProtoField(4, () => OidbSvcTrpcTcp0x6D6Delete, true),
rename: ProtoField(5, () => OidbSvcTrpcTcp0x6D6Rename, true),
move: ProtoField(6, () => OidbSvcTrpcTcp0x6D6Move, true),
};
export const OidbSvcTrpcTcp0x6D6Upload = {
groupUin: ProtoField(1, ScalarType.UINT32),
appId: ProtoField(2, ScalarType.UINT32),
busId: ProtoField(3, ScalarType.UINT32),
entrance: ProtoField(4, ScalarType.UINT32),
targetDirectory: ProtoField(5, ScalarType.STRING),
fileName: ProtoField(6, ScalarType.STRING),
localDirectory: ProtoField(7, ScalarType.STRING),
fileSize: ProtoField(8, ScalarType.UINT64),
fileSha1: ProtoField(9, ScalarType.BYTES),
fileSha3: ProtoField(10, ScalarType.BYTES),
fileMd5: ProtoField(11, ScalarType.BYTES),
field15: ProtoField(15, ScalarType.BOOL),
};
export const OidbSvcTrpcTcp0x6D6Download = {
groupUin: ProtoField(1, ScalarType.UINT32),
appId: ProtoField(2, ScalarType.UINT32),
busId: ProtoField(3, ScalarType.UINT32),
fileId: ProtoField(4, ScalarType.STRING),
};
export const OidbSvcTrpcTcp0x6D6Delete = {
groupUin: ProtoField(1, ScalarType.UINT32),
busId: ProtoField(3, ScalarType.UINT32),
fileId: ProtoField(5, ScalarType.STRING),
};
export const OidbSvcTrpcTcp0x6D6Rename = {
groupUin: ProtoField(1, ScalarType.UINT32),
busId: ProtoField(3, ScalarType.UINT32),
fileId: ProtoField(4, ScalarType.STRING),
parentFolder: ProtoField(5, ScalarType.STRING),
newFileName: ProtoField(6, ScalarType.STRING),
};
export const OidbSvcTrpcTcp0x6D6Move = {
groupUin: ProtoField(1, ScalarType.UINT32),
appId: ProtoField(2, ScalarType.UINT32),
busId: ProtoField(3, ScalarType.UINT32),
fileId: ProtoField(4, ScalarType.STRING),
parentDirectory: ProtoField(5, ScalarType.STRING),
targetDirectory: ProtoField(6, ScalarType.STRING),
};
export const OidbSvcTrpcTcp0x6D6Response = {
upload: ProtoField(1, () => OidbSvcTrpcTcp0x6D6_0Response),
download: ProtoField(3, () => OidbSvcTrpcTcp0x6D6_2Response),
delete: ProtoField(4, () => OidbSvcTrpcTcp0x6D6_3_4_5Response),
rename: ProtoField(5, () => OidbSvcTrpcTcp0x6D6_3_4_5Response),
move: ProtoField(6, () => OidbSvcTrpcTcp0x6D6_3_4_5Response),
};
export const OidbSvcTrpcTcp0x6D6_0Response = {
retCode: ProtoField(1, ScalarType.INT32),
retMsg: ProtoField(2, ScalarType.STRING),
clientWording: ProtoField(3, ScalarType.STRING),
uploadIp: ProtoField(4, ScalarType.STRING),
serverDns: ProtoField(5, ScalarType.STRING),
busId: ProtoField(6, ScalarType.INT32),
fileId: ProtoField(7, ScalarType.STRING),
checkKey: ProtoField(8, ScalarType.BYTES),
fileKey: ProtoField(9, ScalarType.BYTES),
boolFileExist: ProtoField(10, ScalarType.BOOL),
uploadIpLanV4: ProtoField(12, ScalarType.STRING, false, true),
uploadIpLanV6: ProtoField(13, ScalarType.STRING, false, true),
uploadPort: ProtoField(14, ScalarType.UINT32),
};
export const OidbSvcTrpcTcp0x6D6_2Response = {
retCode: ProtoField(1, ScalarType.INT32),
retMsg: ProtoField(2, ScalarType.STRING),
clientWording: ProtoField(3, ScalarType.STRING),
downloadIp: ProtoField(4, ScalarType.STRING),
downloadDns: ProtoField(5, ScalarType.STRING),
downloadUrl: ProtoField(6, ScalarType.BYTES),
fileSha1: ProtoField(7, ScalarType.BYTES),
fileSha3: ProtoField(8, ScalarType.BYTES),
fileMd5: ProtoField(9, ScalarType.BYTES),
cookieVal: ProtoField(10, ScalarType.BYTES),
saveFileName: ProtoField(11, ScalarType.STRING),
previewPort: ProtoField(12, ScalarType.UINT32),
};
export const OidbSvcTrpcTcp0x6D6_3_4_5Response = {
retCode: ProtoField(1, ScalarType.INT32),
retMsg: ProtoField(2, ScalarType.STRING),
clientWording: ProtoField(3, ScalarType.STRING),
};
@@ -0,0 +1,14 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
// 设置群头衔 OidbSvcTrpcTcp.0x8fc_2
export const OidbSvcTrpcTcp0X8FC_2_Body = {
targetUid: ProtoField(1, ScalarType.STRING),
specialTitle: ProtoField(5, ScalarType.STRING, true),
expiredTime: ProtoField(6, ScalarType.INT32),
uinName: ProtoField(7, ScalarType.STRING, true),
targetName: ProtoField(8, ScalarType.STRING),
};
export const OidbSvcTrpcTcp0X8FC_2 = {
groupUin: ProtoField(1, ScalarType.UINT32),
body: ProtoField(3, () => OidbSvcTrpcTcp0X8FC_2_Body),
};
@@ -0,0 +1,26 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
import { MultiMediaReqHead } from './common/Ntv2.RichMediaReq';
// Req
export const OidbSvcTrpcTcp0X9067_202 = {
ReqHead: ProtoField(1, () => MultiMediaReqHead),
DownloadRKeyReq: ProtoField(4, () => OidbSvcTrpcTcp0X9067_202Key),
};
export const OidbSvcTrpcTcp0X9067_202Key = {
key: ProtoField(1, ScalarType.INT32, false, true),
};
// Rsp
export const OidbSvcTrpcTcp0X9067_202_RkeyList = {
rkey: ProtoField(1, ScalarType.STRING),
ttl: ProtoField(2, ScalarType.UINT64),
time: ProtoField(4, ScalarType.UINT32),
type: ProtoField(5, ScalarType.UINT32),
};
export const OidbSvcTrpcTcp0X9067_202_Data = {
rkeyList: ProtoField(1, () => OidbSvcTrpcTcp0X9067_202_RkeyList, false, true),
};
export const OidbSvcTrpcTcp0X9067_202_Rsp_Body = {
data: ProtoField(4, () => OidbSvcTrpcTcp0X9067_202_Data),
};
@@ -0,0 +1,41 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
import { MsgInfo } from '@/napcat-core/packet/transformer/proto';
export const OidbSvcTrpcTcp0X929D_0 = {
groupUin: ProtoField(1, ScalarType.UINT32),
chatType: ProtoField(2, ScalarType.UINT32),
};
export const OidbSvcTrpcTcp0X929D_0Resp = {
content: ProtoField(1, () => OidbSvcTrpcTcp0X929D_0RespContent, false, true),
};
export const OidbSvcTrpcTcp0X929D_0RespContent = {
category: ProtoField(1, ScalarType.STRING),
voices: ProtoField(2, () => OidbSvcTrpcTcp0X929D_0RespContentVoice, false, true),
};
export const OidbSvcTrpcTcp0X929D_0RespContentVoice = {
voiceId: ProtoField(1, ScalarType.STRING),
voiceDisplayName: ProtoField(2, ScalarType.STRING),
voiceExampleUrl: ProtoField(3, ScalarType.STRING),
};
export const OidbSvcTrpcTcp0X929B_0 = {
groupUin: ProtoField(1, ScalarType.UINT32),
voiceId: ProtoField(2, ScalarType.STRING),
text: ProtoField(3, ScalarType.STRING),
chatType: ProtoField(4, ScalarType.UINT32),
session: ProtoField(5, () => OidbSvcTrpcTcp0X929B_0_Session),
};
export const OidbSvcTrpcTcp0X929B_0_Session = {
sessionId: ProtoField(1, ScalarType.UINT32),
};
export const OidbSvcTrpcTcp0X929B_0Resp = {
statusCode: ProtoField(1, ScalarType.UINT32),
field2: ProtoField(2, ScalarType.UINT32, true),
field3: ProtoField(3, ScalarType.UINT32),
msgInfo: ProtoField(4, () => MsgInfo, true),
};
@@ -0,0 +1,59 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const OidbSvcTrpcTcp0xE07_0 = {
version: ProtoField(1, ScalarType.UINT32),
client: ProtoField(2, ScalarType.UINT32),
entrance: ProtoField(3, ScalarType.UINT32),
ocrReqBody: ProtoField(10, () => OcrReqBody, true),
};
export const OcrReqBody = {
imageUrl: ProtoField(1, ScalarType.STRING),
languageType: ProtoField(2, ScalarType.UINT32),
scene: ProtoField(3, ScalarType.UINT32),
originMd5: ProtoField(10, ScalarType.STRING),
afterCompressMd5: ProtoField(11, ScalarType.STRING),
afterCompressFileSize: ProtoField(12, ScalarType.STRING),
afterCompressWeight: ProtoField(13, ScalarType.STRING),
afterCompressHeight: ProtoField(14, ScalarType.STRING),
isCut: ProtoField(15, ScalarType.BOOL),
};
export const OidbSvcTrpcTcp0xE07_0_Response = {
retCode: ProtoField(1, ScalarType.INT32),
errMsg: ProtoField(2, ScalarType.STRING),
wording: ProtoField(3, ScalarType.STRING),
ocrRspBody: ProtoField(10, () => OcrRspBody),
};
export const OcrRspBody = {
textDetections: ProtoField(1, () => TextDetection, false, true),
language: ProtoField(2, ScalarType.STRING),
requestId: ProtoField(3, ScalarType.STRING),
ocrLanguageList: ProtoField(101, ScalarType.STRING, false, true),
dstTranslateLanguageList: ProtoField(102, ScalarType.STRING, false, true),
languageList: ProtoField(103, () => Language, false, true),
afterCompressWeight: ProtoField(111, ScalarType.UINT32),
afterCompressHeight: ProtoField(112, ScalarType.UINT32),
};
export const TextDetection = {
detectedText: ProtoField(1, ScalarType.STRING),
confidence: ProtoField(2, ScalarType.UINT32),
polygon: ProtoField(3, () => Polygon),
advancedInfo: ProtoField(4, ScalarType.STRING),
};
export const Polygon = {
coordinates: ProtoField(1, () => Coordinate, false, true),
};
export const Coordinate = {
x: ProtoField(1, ScalarType.INT32),
y: ProtoField(2, ScalarType.INT32),
};
export const Language = {
languageCode: ProtoField(1, ScalarType.STRING),
languageDesc: ProtoField(2, ScalarType.STRING),
};
@@ -0,0 +1,60 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const OidbSvcTrpcTcp0XE37_1200 = {
subCommand: ProtoField(1, ScalarType.UINT32, true),
field2: ProtoField(2, ScalarType.INT32, true),
body: ProtoField(14, () => OidbSvcTrpcTcp0XE37_1200Body, true),
field101: ProtoField(101, ScalarType.INT32, true),
field102: ProtoField(102, ScalarType.INT32, true),
field200: ProtoField(200, ScalarType.INT32, true),
field99999: ProtoField(99999, ScalarType.BYTES, true),
};
export const OidbSvcTrpcTcp0XE37_1200Body = {
receiverUid: ProtoField(10, ScalarType.STRING, true),
fileUuid: ProtoField(20, ScalarType.STRING, true),
type: ProtoField(30, ScalarType.INT32, true),
fileHash: ProtoField(60, ScalarType.STRING, true),
t2: ProtoField(601, ScalarType.INT32, true),
};
export const OidbSvcTrpcTcp0XE37_1200Response = {
command: ProtoField(1, ScalarType.UINT32, true),
subCommand: ProtoField(2, ScalarType.UINT32, true),
body: ProtoField(14, () => OidbSvcTrpcTcp0XE37_1200ResponseBody, true),
field50: ProtoField(50, ScalarType.UINT32, true),
};
export const OidbSvcTrpcTcp0XE37_1200ResponseBody = {
field10: ProtoField(10, ScalarType.UINT32, true),
state: ProtoField(20, ScalarType.STRING, true),
result: ProtoField(30, () => OidbSvcTrpcTcp0XE37_1200Result, true),
metadata: ProtoField(40, () => OidbSvcTrpcTcp0XE37_800_1200Metadata, true),
};
export const OidbSvcTrpcTcp0XE37_1200Result = {
server: ProtoField(20, ScalarType.STRING, true),
port: ProtoField(40, ScalarType.UINT32, true),
url: ProtoField(50, ScalarType.STRING, true),
additionalServer: ProtoField(60, ScalarType.STRING, false, true),
ssoPort: ProtoField(80, ScalarType.UINT32, true),
ssoUrl: ProtoField(90, ScalarType.STRING, true),
extra: ProtoField(120, ScalarType.BYTES, true),
};
export const OidbSvcTrpcTcp0XE37_800_1200Metadata = {
uin: ProtoField(1, ScalarType.UINT32, true),
field2: ProtoField(2, ScalarType.UINT32, true),
field3: ProtoField(3, ScalarType.UINT32, true),
size: ProtoField(4, ScalarType.UINT32, true),
timestamp: ProtoField(5, ScalarType.UINT32, true),
fileUuid: ProtoField(6, ScalarType.STRING, true),
fileName: ProtoField(7, ScalarType.STRING, true),
field100: ProtoField(100, ScalarType.BYTES, true),
field101: ProtoField(101, ScalarType.BYTES, true),
field110: ProtoField(110, ScalarType.UINT32, true),
timestamp1: ProtoField(130, ScalarType.UINT32, true),
fileHash: ProtoField(140, ScalarType.STRING, true),
field141: ProtoField(141, ScalarType.BYTES, true),
field142: ProtoField(142, ScalarType.BYTES, true),
};
@@ -0,0 +1,22 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const OidbSvcTrpcTcp0XE37_1700 = {
command: ProtoField(1, ScalarType.UINT32, true),
seq: ProtoField(2, ScalarType.INT32, true),
upload: ProtoField(19, () => ApplyUploadReqV3, true),
businessId: ProtoField(101, ScalarType.INT32, true),
clientType: ProtoField(102, ScalarType.INT32, true),
flagSupportMediaPlatform: ProtoField(200, ScalarType.INT32, true),
};
export const ApplyUploadReqV3 = {
senderUid: ProtoField(10, ScalarType.STRING, true),
receiverUid: ProtoField(20, ScalarType.STRING, true),
fileSize: ProtoField(30, ScalarType.UINT32, true),
fileName: ProtoField(40, ScalarType.STRING, true),
md510MCheckSum: ProtoField(50, ScalarType.BYTES, true),
sha1CheckSum: ProtoField(60, ScalarType.BYTES, true),
localPath: ProtoField(70, ScalarType.STRING, true),
md5CheckSum: ProtoField(110, ScalarType.BYTES, true),
sha3CheckSum: ProtoField(120, ScalarType.BYTES, true),
};
@@ -0,0 +1,11 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const OidbSvcTrpcTcp0XEB7_Body = {
uin: ProtoField(1, ScalarType.STRING),
groupUin: ProtoField(2, ScalarType.STRING),
version: ProtoField(3, ScalarType.STRING),
};
export const OidbSvcTrpcTcp0XEB7 = {
body: ProtoField(2, () => OidbSvcTrpcTcp0XEB7_Body),
};
@@ -0,0 +1,9 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
// Send Poke
export const OidbSvcTrpcTcp0XED3_1 = {
uin: ProtoField(1, ScalarType.UINT32),
groupUin: ProtoField(2, ScalarType.UINT32),
friendUin: ProtoField(5, ScalarType.UINT32),
ext: ProtoField(6, ScalarType.UINT32, true),
};
@@ -0,0 +1,6 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const OidbSvcTrpcTcp0XF90_1 = {
groupUin: ProtoField(1, ScalarType.UINT32),
msgSeq: ProtoField(2, ScalarType.UINT64),
};
@@ -0,0 +1,13 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const OidbSvcTrpcTcpBase = {
command: ProtoField(1, ScalarType.UINT32),
subCommand: ProtoField(2, ScalarType.UINT32),
errorCode: ProtoField(3, ScalarType.UINT32),
body: ProtoField(4, ScalarType.BYTES),
errorMsg: ProtoField(5, ScalarType.STRING, true),
isReserved: ProtoField(12, ScalarType.UINT32),
};
export const OidbSvcTrpcTcpBaseRsp = {
body: ProtoField(4, ScalarType.BYTES),
};
@@ -0,0 +1,237 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
export const NTV2RichMediaReq = {
ReqHead: ProtoField(1, () => MultiMediaReqHead),
Upload: ProtoField(2, () => UploadReq),
Download: ProtoField(3, () => DownloadReq),
DownloadRKey: ProtoField(4, () => DownloadRKeyReq),
Delete: ProtoField(5, () => DeleteReq),
UploadCompleted: ProtoField(6, () => UploadCompletedReq),
MsgInfoAuth: ProtoField(7, () => MsgInfoAuthReq),
UploadKeyRenewal: ProtoField(8, () => UploadKeyRenewalReq),
DownloadSafe: ProtoField(9, () => DownloadSafeReq),
Extension: ProtoField(99, ScalarType.BYTES, true),
};
export const MultiMediaReqHead = {
Common: ProtoField(1, () => CommonHead),
Scene: ProtoField(2, () => SceneInfo),
Client: ProtoField(3, () => ClientMeta),
};
export const CommonHead = {
RequestId: ProtoField(1, ScalarType.UINT32),
Command: ProtoField(2, ScalarType.UINT32),
};
export const SceneInfo = {
RequestType: ProtoField(101, ScalarType.UINT32),
BusinessType: ProtoField(102, ScalarType.UINT32),
SceneType: ProtoField(200, ScalarType.UINT32),
C2C: ProtoField(201, () => C2CUserInfo, true),
Group: ProtoField(202, () => NTGroupInfo, true),
};
export const C2CUserInfo = {
AccountType: ProtoField(1, ScalarType.UINT32),
TargetUid: ProtoField(2, ScalarType.STRING),
};
export const NTGroupInfo = {
GroupUin: ProtoField(1, ScalarType.UINT32),
};
export const ClientMeta = {
AgentType: ProtoField(1, ScalarType.UINT32),
};
export const DownloadReq = {
Node: ProtoField(1, () => IndexNode),
Download: ProtoField(2, () => DownloadExt),
};
export const IndexNode = {
Info: ProtoField(1, () => FileInfo),
FileUuid: ProtoField(2, ScalarType.STRING),
StoreId: ProtoField(3, ScalarType.UINT32),
UploadTime: ProtoField(4, ScalarType.UINT32),
Ttl: ProtoField(5, ScalarType.UINT32),
SubType: ProtoField(6, ScalarType.UINT32),
};
export const FileInfo = {
FileSize: ProtoField(1, ScalarType.UINT32),
FileHash: ProtoField(2, ScalarType.STRING),
FileSha1: ProtoField(3, ScalarType.STRING),
FileName: ProtoField(4, ScalarType.STRING),
Type: ProtoField(5, () => FileType),
Width: ProtoField(6, ScalarType.UINT32),
Height: ProtoField(7, ScalarType.UINT32),
Time: ProtoField(8, ScalarType.UINT32),
Original: ProtoField(9, ScalarType.UINT32),
};
export const FileType = {
Type: ProtoField(1, ScalarType.UINT32),
PicFormat: ProtoField(2, ScalarType.UINT32),
VideoFormat: ProtoField(3, ScalarType.UINT32),
VoiceFormat: ProtoField(4, ScalarType.UINT32),
};
export const DownloadExt = {
Pic: ProtoField(1, () => PicDownloadExt),
Video: ProtoField(2, () => VideoDownloadExt),
Ptt: ProtoField(3, () => PttDownloadExt),
};
export const VideoDownloadExt = {
BusiType: ProtoField(1, ScalarType.UINT32),
SceneType: ProtoField(2, ScalarType.UINT32),
SubBusiType: ProtoField(3, ScalarType.UINT32),
};
export const PicDownloadExt = {};
export const PttDownloadExt = {};
export const DownloadRKeyReq = {
Types: ProtoField(1, ScalarType.INT32, false, true),
};
export const DeleteReq = {
Index: ProtoField(1, () => IndexNode, false, true),
NeedRecallMsg: ProtoField(2, ScalarType.BOOL),
MsgSeq: ProtoField(3, ScalarType.UINT64),
MsgRandom: ProtoField(4, ScalarType.UINT64),
MsgTime: ProtoField(5, ScalarType.UINT64),
};
export const UploadCompletedReq = {
SrvSendMsg: ProtoField(1, ScalarType.BOOL),
ClientRandomId: ProtoField(2, ScalarType.UINT64),
MsgInfo: ProtoField(3, () => MsgInfo),
ClientSeq: ProtoField(4, ScalarType.UINT32),
};
export const MsgInfoAuthReq = {
Msg: ProtoField(1, ScalarType.BYTES),
AuthTime: ProtoField(2, ScalarType.UINT64),
};
export const DownloadSafeReq = {
Index: ProtoField(1, () => IndexNode),
};
export const UploadKeyRenewalReq = {
OldUKey: ProtoField(1, ScalarType.STRING),
SubType: ProtoField(2, ScalarType.UINT32),
};
export const MsgInfo = {
MsgInfoBody: ProtoField(1, () => MsgInfoBody, false, true),
ExtBizInfo: ProtoField(2, () => ExtBizInfo),
};
export const MsgInfoBody = {
Index: ProtoField(1, () => IndexNode),
Picture: ProtoField(2, () => PictureInfo),
Video: ProtoField(3, () => VideoInfo),
Audio: ProtoField(4, () => AudioInfo),
FileExist: ProtoField(5, ScalarType.BOOL),
HashSum: ProtoField(6, ScalarType.BYTES),
};
export const VideoInfo = {};
export const AudioInfo = {};
export const PictureInfo = {
UrlPath: ProtoField(1, ScalarType.STRING),
Ext: ProtoField(2, () => PicUrlExtInfo),
Domain: ProtoField(3, ScalarType.STRING),
};
export const PicUrlExtInfo = {
OriginalParameter: ProtoField(1, ScalarType.STRING),
BigParameter: ProtoField(2, ScalarType.STRING),
ThumbParameter: ProtoField(3, ScalarType.STRING),
};
export const VideoExtInfo = {
VideoCodecFormat: ProtoField(1, ScalarType.UINT32),
};
export const ExtBizInfo = {
Pic: ProtoField(1, () => PicExtBizInfo),
Video: ProtoField(2, () => VideoExtBizInfo),
Ptt: ProtoField(3, () => PttExtBizInfo),
BusiType: ProtoField(10, ScalarType.UINT32),
};
export const PttExtBizInfo = {
SrcUin: ProtoField(1, ScalarType.UINT64),
PttScene: ProtoField(2, ScalarType.UINT32),
PttType: ProtoField(3, ScalarType.UINT32),
ChangeVoice: ProtoField(4, ScalarType.UINT32),
Waveform: ProtoField(5, ScalarType.BYTES),
AutoConvertText: ProtoField(6, ScalarType.UINT32),
BytesReserve: ProtoField(11, ScalarType.BYTES),
BytesPbReserve: ProtoField(12, ScalarType.BYTES),
BytesGeneralFlags: ProtoField(13, ScalarType.BYTES),
};
export const VideoExtBizInfo = {
FromScene: ProtoField(1, ScalarType.UINT32),
ToScene: ProtoField(2, ScalarType.UINT32),
BytesPbReserve: ProtoField(3, ScalarType.BYTES),
};
export const PicExtBizInfo = {
BizType: ProtoField(1, ScalarType.UINT32),
TextSummary: ProtoField(2, ScalarType.STRING),
BytesPbReserveC2c: ProtoField(11, () => BytesPbReserveC2c),
BytesPbReserveTroop: ProtoField(12, () => BytesPbReserveTroop),
FromScene: ProtoField(1001, ScalarType.UINT32),
ToScene: ProtoField(1002, ScalarType.UINT32),
OldFileId: ProtoField(1003, ScalarType.UINT32),
};
export const UploadReq = {
UploadInfo: ProtoField(1, () => UploadInfo, false, true),
TryFastUploadCompleted: ProtoField(2, ScalarType.BOOL),
SrvSendMsg: ProtoField(3, ScalarType.BOOL),
ClientRandomId: ProtoField(4, ScalarType.UINT64),
CompatQMsgSceneType: ProtoField(5, ScalarType.UINT32),
ExtBizInfo: ProtoField(6, () => ExtBizInfo),
ClientSeq: ProtoField(7, ScalarType.UINT32),
NoNeedCompatMsg: ProtoField(8, ScalarType.BOOL),
};
export const UploadInfo = {
FileInfo: ProtoField(1, () => FileInfo),
SubFileType: ProtoField(2, ScalarType.UINT32),
};
export const BytesPbReserveC2c = {
subType: ProtoField(1, ScalarType.UINT32),
field3: ProtoField(3, ScalarType.UINT32),
field4: ProtoField(4, ScalarType.UINT32),
field8: ProtoField(8, ScalarType.STRING),
field10: ProtoField(10, ScalarType.UINT32),
field12: ProtoField(12, ScalarType.STRING),
field18: ProtoField(18, ScalarType.STRING),
field19: ProtoField(19, ScalarType.STRING),
field20: ProtoField(20, ScalarType.BYTES),
};
export const BytesPbReserveTroop = {
subType: ProtoField(1, ScalarType.UINT32),
field3: ProtoField(3, ScalarType.UINT32),
field4: ProtoField(4, ScalarType.UINT32),
field9: ProtoField(9, ScalarType.STRING),
field10: ProtoField(10, ScalarType.UINT32),
field12: ProtoField(12, ScalarType.STRING),
field18: ProtoField(18, ScalarType.STRING),
field19: ProtoField(19, ScalarType.STRING),
field21: ProtoField(21, ScalarType.BYTES),
};
@@ -0,0 +1,113 @@
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
import { CommonHead, MsgInfo, PicUrlExtInfo, VideoExtInfo } from '@/napcat-core/packet/transformer/proto';
export const NTV2RichMediaResp = {
respHead: ProtoField(1, () => MultiMediaRespHead),
upload: ProtoField(2, () => UploadResp),
download: ProtoField(3, () => DownloadResp),
downloadRKey: ProtoField(4, () => DownloadRKeyResp),
delete: ProtoField(5, () => DeleteResp),
uploadCompleted: ProtoField(6, () => UploadCompletedResp),
msgInfoAuth: ProtoField(7, () => MsgInfoAuthResp),
uploadKeyRenewal: ProtoField(8, () => UploadKeyRenewalResp),
downloadSafe: ProtoField(9, () => DownloadSafeResp),
extension: ProtoField(99, ScalarType.BYTES, true),
};
export const MultiMediaRespHead = {
common: ProtoField(1, () => CommonHead),
retCode: ProtoField(2, ScalarType.UINT32),
message: ProtoField(3, ScalarType.STRING),
};
export const DownloadResp = {
rKeyParam: ProtoField(1, ScalarType.STRING),
rKeyTtlSecond: ProtoField(2, ScalarType.UINT32),
info: ProtoField(3, () => DownloadInfo),
rKeyCreateTime: ProtoField(4, ScalarType.UINT32),
};
export const DownloadInfo = {
domain: ProtoField(1, ScalarType.STRING),
urlPath: ProtoField(2, ScalarType.STRING),
httpsPort: ProtoField(3, ScalarType.UINT32),
ipv4s: ProtoField(4, () => IPv4, false, true),
ipv6s: ProtoField(5, () => IPv6, false, true),
picUrlExtInfo: ProtoField(6, () => PicUrlExtInfo),
videoExtInfo: ProtoField(7, () => VideoExtInfo),
};
export const IPv4 = {
outIP: ProtoField(1, ScalarType.UINT32),
outPort: ProtoField(2, ScalarType.UINT32),
inIP: ProtoField(3, ScalarType.UINT32),
inPort: ProtoField(4, ScalarType.UINT32),
ipType: ProtoField(5, ScalarType.UINT32),
};
export const IPv6 = {
outIP: ProtoField(1, ScalarType.BYTES),
outPort: ProtoField(2, ScalarType.UINT32),
inIP: ProtoField(3, ScalarType.BYTES),
inPort: ProtoField(4, ScalarType.UINT32),
ipType: ProtoField(5, ScalarType.UINT32),
};
export const UploadResp = {
uKey: ProtoField(1, ScalarType.STRING, true),
uKeyTtlSecond: ProtoField(2, ScalarType.UINT32),
ipv4s: ProtoField(3, () => IPv4, false, true),
ipv6s: ProtoField(4, () => IPv6, false, true),
msgSeq: ProtoField(5, ScalarType.UINT64),
msgInfo: ProtoField(6, () => MsgInfo),
ext: ProtoField(7, () => RichMediaStorageTransInfo, false, true),
compatQMsg: ProtoField(8, ScalarType.BYTES),
subFileInfos: ProtoField(10, () => SubFileInfo, false, true),
};
export const RichMediaStorageTransInfo = {
subType: ProtoField(1, ScalarType.UINT32),
extType: ProtoField(2, ScalarType.UINT32),
extValue: ProtoField(3, ScalarType.BYTES),
};
export const SubFileInfo = {
subType: ProtoField(1, ScalarType.UINT32),
uKey: ProtoField(2, ScalarType.STRING),
uKeyTtlSecond: ProtoField(3, ScalarType.UINT32),
ipv4s: ProtoField(4, () => IPv4, false, true),
ipv6s: ProtoField(5, () => IPv6, false, true),
};
export const DownloadSafeResp = {
};
export const UploadKeyRenewalResp = {
ukey: ProtoField(1, ScalarType.STRING),
ukeyTtlSec: ProtoField(2, ScalarType.UINT64),
};
export const MsgInfoAuthResp = {
authCode: ProtoField(1, ScalarType.UINT32),
msg: ProtoField(2, ScalarType.BYTES),
resultTime: ProtoField(3, ScalarType.UINT64),
};
export const UploadCompletedResp = {
msgSeq: ProtoField(1, ScalarType.UINT64),
};
export const DeleteResp = {
};
export const DownloadRKeyResp = {
rKeys: ProtoField(1, () => RKeyInfo, false, true),
};
export const RKeyInfo = {
rkey: ProtoField(1, ScalarType.STRING),
rkeyTtlSec: ProtoField(2, ScalarType.UINT64),
storeId: ProtoField(3, ScalarType.UINT32),
rkeyCreateTime: ProtoField(4, ScalarType.UINT32, true),
type: ProtoField(5, ScalarType.UINT32, true),
};
@@ -0,0 +1,36 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class FetchRkey extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0X9067_202_Rsp_Body> {
build (): OidbPacket {
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0X9067_202).encode({
reqHead: {
common: {
requestId: 1,
command: 202,
},
scene: {
requestType: 2,
businessType: 1,
sceneType: 0,
},
client: {
agentType: 2,
},
},
downloadRKeyReq: {
key: [10, 20, 2],
},
});
return OidbBase.build(0x9067, 202, data);
}
parse (data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
return new NapProtoMsg(proto.OidbSvcTrpcTcp0X9067_202_Rsp_Body).decode(oidbBody);
}
}
export default new FetchRkey();
@@ -0,0 +1 @@
export { default as FetchRkey } from './FetchRkey';
@@ -0,0 +1,47 @@
// love from https://github.com/LagrangeDev/lagrangejs & https://github.com/takayama-lily/oicq
import * as crypto from 'crypto';
import * as stream from 'stream';
import * as fs from 'fs';
import { CalculateStreamBytesTransform } from '@/napcat-core/packet/utils/crypto/sha1StreamBytesTransform';
function sha1Stream (readable: stream.Readable) {
return new Promise<Buffer>((resolve, reject) => {
readable.on('error', reject);
readable.pipe(crypto.createHash('sha1').on('error', reject).on('data', resolve));
});
}
function md5Stream (readable: stream.Readable) {
return new Promise<Buffer>((resolve, reject) => {
readable.on('error', reject);
readable.pipe(crypto.createHash('md5').on('error', reject).on('data', resolve));
});
}
export function calculateSha1 (filePath: string): Promise<Buffer> {
const readable = fs.createReadStream(filePath);
return sha1Stream(readable);
}
export function computeMd5AndLengthWithLimit (filePath: string, limit?: number): Promise<Buffer> {
const readStream = fs.createReadStream(filePath, limit ? { start: 0, end: limit - 1 } : {});
return md5Stream(readStream);
}
export function calculateSha1StreamBytes (filePath: string): Promise<Buffer[]> {
return new Promise((resolve, reject) => {
const readable = fs.createReadStream(filePath);
const calculateStreamBytes = new CalculateStreamBytesTransform();
const byteArrayList: Buffer[] = [];
calculateStreamBytes.on('data', (chunk: Buffer) => {
byteArrayList.push(chunk);
});
calculateStreamBytes.on('end', () => {
resolve(byteArrayList);
});
calculateStreamBytes.on('error', (err: Error) => {
reject(err);
});
readable.pipe(calculateStreamBytes);
});
}
@@ -0,0 +1,19 @@
import crypto from 'crypto';
import assert from 'assert';
import { Sha1Stream } from './sha1Stream';
function testSha1Stream () {
for (let i = 0; i < 100000; i++) {
const randomLength = Math.floor(Math.random() * 1024);
const randomData = crypto.randomBytes(randomLength);
const sha1Stream = new Sha1Stream();
sha1Stream.update(randomData);
const hash = sha1Stream.final();
const expectedDigest = crypto.createHash('sha1').update(randomData).digest();
assert.strictEqual(hash.toString('hex'), expectedDigest.toString('hex'));
console.log(`Test ${i + 1}: Passed`);
}
console.log('All tests passed successfully.');
}
testSha1Stream();
@@ -0,0 +1,125 @@
// @ts-nocheck
export class Sha1Stream {
readonly Sha1BlockSize = 64;
readonly Sha1DigestSize = 20;
private readonly _padding = Buffer.concat([Buffer.from([0x80]), Buffer.alloc(63)]);
private readonly _state = new Uint32Array(5);
private readonly _count = new Uint32Array(2);
private readonly _buffer = Buffer.allocUnsafe(this.Sha1BlockSize);
private readonly _w = new Uint32Array(80);
constructor () {
this.reset();
}
private reset (): void {
this._state[0] = 0x67452301;
this._state[1] = 0xEFCDAB89;
this._state[2] = 0x98BADCFE;
this._state[3] = 0x10325476;
this._state[4] = 0xC3D2E1F0;
this._count[0] = 0;
this._count[1] = 0;
this._buffer.fill(0);
}
private rotateLeft (v: number, o: number): number {
return ((v << o) | (v >>> (32 - o))) >>> 0;
}
private transform (chunk: Buffer, offset: number): void {
const w = this._w;
const view = new DataView(chunk.buffer, chunk.byteOffset + offset, 64);
for (let i = 0; i < 16; i++) {
w[i] = view.getUint32(i * 4, false);
}
for (let i = 16; i < 80; i++) {
w[i] = this.rotateLeft(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1) >>> 0;
}
let a = this._state[0];
let b = this._state[1];
let c = this._state[2];
let d = this._state[3];
let e = this._state[4];
for (let i = 0; i < 80; i++) {
let temp;
if (i < 20) {
temp = ((b & c) | (~b & d)) + 0x5A827999;
} else if (i < 40) {
temp = (b ^ c ^ d) + 0x6ED9EBA1;
} else if (i < 60) {
temp = ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC;
} else {
temp = (b ^ c ^ d) + 0xCA62C1D6;
}
temp += ((this.rotateLeft(a, 5) + e + w[i]) >>> 0);
e = d;
d = c;
c = this.rotateLeft(b, 30) >>> 0;
b = a;
a = temp;
}
this._state[0] = (this._state[0] + a) >>> 0;
this._state[1] = (this._state[1] + b) >>> 0;
this._state[2] = (this._state[2] + c) >>> 0;
this._state[3] = (this._state[3] + d) >>> 0;
this._state[4] = (this._state[4] + e) >>> 0;
}
public update (data: Buffer, len?: number): void {
let index = ((this._count[0] >>> 3) & 0x3F) >>> 0;
const dataLen = len ?? data.length;
this._count[0] = (this._count[0] + (dataLen << 3)) >>> 0;
if (this._count[0] < (dataLen << 3)) this._count[1] = (this._count[1] + 1) >>> 0;
this._count[1] = (this._count[1] + (dataLen >>> 29)) >>> 0;
const partLen = (this.Sha1BlockSize - index) >>> 0;
let i = 0;
if (dataLen >= partLen) {
data.copy(this._buffer, index, 0, partLen);
this.transform(this._buffer, 0);
for (i = partLen; (i + this.Sha1BlockSize) <= dataLen; i = (i + this.Sha1BlockSize) >>> 0) {
this.transform(data, i);
}
index = 0;
}
data.copy(this._buffer, index, i, dataLen);
}
public hash (bigEndian: boolean = true): Buffer {
const digest = Buffer.allocUnsafe(this.Sha1DigestSize);
if (bigEndian) {
for (let i = 0; i < 5; i++) digest.writeUInt32BE(this._state[i], i * 4);
} else {
for (let i = 0; i < 5; i++) digest.writeUInt32LE(this._state[i], i * 4);
}
return digest;
}
public final (): Buffer {
const digest = Buffer.allocUnsafe(this.Sha1DigestSize);
const bits = Buffer.allocUnsafe(8);
bits.writeUInt32BE(this._count[1], 0);
bits.writeUInt32BE(this._count[0], 4);
const index = ((this._count[0] >>> 3) & 0x3F) >>> 0;
const padLen = ((index < 56) ? (56 - index) : (120 - index)) >>> 0;
this.update(this._padding, padLen);
this.update(bits);
for (let i = 0; i < 5; i++) {
digest.writeUInt32BE(this._state[i], i * 4);
}
return digest;
}
}
@@ -0,0 +1,53 @@
import * as stream from 'node:stream';
import { Sha1Stream } from '@/napcat-core/packet/utils/crypto/sha1Stream';
export class CalculateStreamBytesTransform extends stream.Transform {
private readonly blockSize = 1024 * 1024;
private readonly sha1: Sha1Stream;
private buffer: Buffer;
private bytesRead: number;
private readonly byteArrayList: Buffer[];
constructor () {
super();
this.sha1 = new Sha1Stream();
this.buffer = Buffer.alloc(0);
this.bytesRead = 0;
this.byteArrayList = [];
}
override _transform (chunk: Buffer, _: BufferEncoding, callback: stream.TransformCallback): void {
try {
this.buffer = Buffer.concat([this.buffer, chunk]);
let offset = 0;
while (this.buffer.length - offset >= this.sha1.Sha1BlockSize) {
const block = this.buffer.subarray(offset, offset + this.sha1.Sha1BlockSize);
this.sha1.update(block);
offset += this.sha1.Sha1BlockSize;
this.bytesRead += this.sha1.Sha1BlockSize;
if (this.bytesRead % this.blockSize === 0) {
const digest = this.sha1.hash(false);
this.byteArrayList.push(Buffer.from(digest));
}
}
this.buffer = this.buffer.subarray(offset);
callback(null);
} catch (err) {
callback(err as Error);
}
}
override _flush (callback: stream.TransformCallback): void {
try {
if (this.buffer.length > 0) this.sha1.update(this.buffer);
const finalDigest = this.sha1.final();
this.byteArrayList.push(Buffer.from(finalDigest));
for (const digest of this.byteArrayList) {
this.push(digest);
}
callback(null);
} catch (err) {
callback(err as Error);
}
}
}
@@ -0,0 +1,88 @@
// love from https://github.com/LagrangeDev/lagrangejs/blob/main/src/core/tea.ts & https://github.com/takayama-lily/oicq/blob/main/lib/core/tea.ts
// @ts-nocheck
const BUF7 = Buffer.alloc(7);
const deltas = [
0x9e3779b9, 0x3c6ef372, 0xdaa66d2b, 0x78dde6e4, 0x1715609d, 0xb54cda56, 0x5384540f, 0xf1bbcdc8, 0x8ff34781,
0x2e2ac13a, 0xcc623af3, 0x6a99b4ac, 0x08d12e65, 0xa708a81e, 0x454021d7, 0xe3779b90,
];
function _toUInt32 (num: number) {
return num >>> 0;
}
function _encrypt (x: number, y: number, k0: number, k1: number, k2: number, k3: number): [number, number] {
for (let i = 0; i < 16; ++i) {
let aa = ((_toUInt32(((y << 4) >>> 0) + k0) ^ _toUInt32(y + deltas[i])) >>> 0) ^ _toUInt32(~~(y / 32) + k1);
aa >>>= 0;
x = _toUInt32(x + aa);
let bb = ((_toUInt32(((x << 4) >>> 0) + k2) ^ _toUInt32(x + deltas[i])) >>> 0) ^ _toUInt32(~~(x / 32) + k3);
bb >>>= 0;
y = _toUInt32(y + bb);
}
return [x, y];
}
export function encrypt (data: Buffer, key: Buffer) {
let n = (6 - data.length) >>> 0;
n = (n % 8) + 2;
const v = Buffer.concat([Buffer.from([(n - 2) | 0xf8]), Buffer.allocUnsafe(n), data, BUF7]);
const k0 = key.readUInt32BE(0);
const k1 = key.readUInt32BE(4);
const k2 = key.readUInt32BE(8);
const k3 = key.readUInt32BE(12);
let r1 = 0; let r2 = 0; let t1 = 0; let t2 = 0;
for (let i = 0; i < v.length; i += 8) {
const a1 = v.readUInt32BE(i);
const a2 = v.readUInt32BE(i + 4);
const b1 = a1 ^ r1;
const b2 = a2 ^ r2;
const [x, y] = _encrypt(b1 >>> 0, b2 >>> 0, k0, k1, k2, k3);
r1 = x ^ t1;
r2 = y ^ t2;
t1 = b1;
t2 = b2;
v.writeInt32BE(r1, i);
v.writeInt32BE(r2, i + 4);
}
return v;
}
function _decrypt (x: number, y: number, k0: number, k1: number, k2: number, k3: number) {
for (let i = 15; i >= 0; --i) {
const aa = ((_toUInt32(((x << 4) >>> 0) + k2) ^ _toUInt32(x + deltas[i])) >>> 0) ^ _toUInt32(~~(x / 32) + k3);
y = (y - aa) >>> 0;
const bb = ((_toUInt32(((y << 4) >>> 0) + k0) ^ _toUInt32(y + deltas[i])) >>> 0) ^ _toUInt32(~~(y / 32) + k1);
x = (x - bb) >>> 0;
}
return [x, y];
}
export function decrypt (encrypted: Buffer, key: Buffer) {
if (encrypted.length % 8) throw ERROR_ENCRYPTED_LENGTH;
const k0 = key.readUInt32BE(0);
const k1 = key.readUInt32BE(4);
const k2 = key.readUInt32BE(8);
const k3 = key.readUInt32BE(12);
let r1 = 0; let r2 = 0; let t1 = 0; let t2 = 0; let x = 0; let y = 0;
for (let i = 0; i < encrypted.length; i += 8) {
const a1 = encrypted.readUInt32BE(i);
const a2 = encrypted.readUInt32BE(i + 4);
const b1 = a1 ^ x;
const b2 = a2 ^ y;
[x, y] = _decrypt(b1 >>> 0, b2 >>> 0, k0, k1, k2, k3);
r1 = x ^ t1;
r2 = y ^ t2;
t1 = a1;
t2 = a2;
encrypted.writeInt32BE(r1, i);
encrypted.writeInt32BE(r2, i + 4);
}
if (Buffer.compare(encrypted.subarray(encrypted.length - 7), BUF7) !== 0) throw ERROR_ENCRYPTED_ILLEGAL;
// if (Buffer.compare(encrypted.slice(encrypted.length - 7), BUF7) !== 0) throw ERROR_ENCRYPTED_ILLEGAL;
return encrypted.subarray((encrypted[0] & 0x07) + 3, encrypted.length - 7);
// return encrypted.slice((encrypted[0] & 0x07) + 3, encrypted.length - 7);
}
const ERROR_ENCRYPTED_LENGTH = new Error('length of encrypted data must be a multiple of 8');
const ERROR_ENCRYPTED_ILLEGAL = new Error('encrypted data is illegal');
@@ -0,0 +1,94 @@
import {
MiniAppData,
MiniAppReqParams,
MiniAppRawData,
MiniAppReqCustomParams,
MiniAppReqTemplateParams,
} from '@/napcat-core/packet/entities/miniApp';
type MiniAppTemplateNameList = 'bili' | 'weibo';
export abstract class MiniAppInfo {
static readonly sdkId: string = 'V1_PC_MINISDK_99.99.99_1_APP_A';
template: MiniAppReqTemplateParams;
private static readonly appMap = new Map<MiniAppTemplateNameList, MiniAppInfo>();
protected constructor (template: MiniAppReqTemplateParams) {
this.template = template;
}
static get (name: MiniAppTemplateNameList): MiniAppInfo | undefined {
return this.appMap.get(name);
}
static readonly Bili = new class extends MiniAppInfo {
constructor () {
super({
sdkId: MiniAppInfo.sdkId,
appId: '1109937557',
scene: 1,
templateType: 1,
businessType: 0,
verType: 3,
shareType: 0,
versionId: 'cfc5f7b05b44b5956502edaecf9d2240',
withShareTicket: 0,
iconUrl: 'https://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg',
});
MiniAppInfo.appMap.set('bili', this);
}
}();
static readonly WeiBo = new class extends MiniAppInfo {
constructor () {
super({
sdkId: MiniAppInfo.sdkId,
appId: '1109224783',
scene: 1,
templateType: 1,
businessType: 0,
verType: 3,
shareType: 0,
versionId: 'e482a3cc4e574d9b772e96ba6eec9ba2',
withShareTicket: 0,
iconUrl: 'https://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg',
});
MiniAppInfo.appMap.set('weibo', this);
}
}();
}
export class MiniAppInfoHelper {
static generateReq (custom: MiniAppReqCustomParams, template: MiniAppReqTemplateParams): MiniAppReqParams {
return {
...custom,
...template,
};
}
static RawToSend (rawData: MiniAppRawData): MiniAppData {
return {
ver: rawData.ver,
prompt: rawData.prompt,
config: rawData.config,
app: rawData.appName,
view: rawData.appView,
meta: rawData.metaData,
miniappShareOrigin: 3,
miniappOpenRefer: '10002',
};
}
static SendToRaw (data: MiniAppData): MiniAppRawData {
return {
appName: data.app,
appView: data.view,
ver: data.ver,
desc: data.meta.detail_1.desc,
prompt: data.prompt,
metaData: data.meta,
config: data.config,
};
}
}