refactor: packet x1
This commit is contained in:
1 parent
af29c17814
commit
7fd94a03b7
105 files changed
+2286
-1962
No files matched your search
@@ -1,9 +1,7 @@
|
||||
import { LRUCache } from "@/common/lru-cache";
|
||||
import { NapCatCore } from "@/core";
|
||||
import { LogWrapper } from "@/common/log";
|
||||
import crypto, { createHash } from "crypto";
|
||||
import { OidbPacket, PacketHexStr } from "@/core/packet/packer";
|
||||
import { NapCatConfig } from "@/core/helper/config";
|
||||
import { PacketContext } from "@/core/packet/context/packetContext";
|
||||
import { OidbPacket, PacketHexStr } from "@/core/packet/transformer/base";
|
||||
|
||||
export interface RecvPacket {
|
||||
type: string, // 仅recv
|
||||
@@ -17,38 +15,28 @@ export interface RecvPacketData {
|
||||
hex_data: string
|
||||
}
|
||||
|
||||
export abstract class PacketClient {
|
||||
readonly napCatCore: NapCatCore;
|
||||
protected readonly logger: LogWrapper;
|
||||
function randText(len: number): string {
|
||||
let text = '';
|
||||
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
for (let i = 0; i < len; i++) {
|
||||
text += possible.charAt(Math.floor(Math.random() * possible.length));
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
export abstract class IPacketClient {
|
||||
protected readonly context: PacketContext;
|
||||
protected readonly cb = new LRUCache<string, (json: RecvPacketData) => Promise<void>>(500); // trace_id-type callback
|
||||
protected isAvailable: boolean = false;
|
||||
protected config: NapCatConfig;
|
||||
available: boolean = false;
|
||||
|
||||
protected constructor(core: NapCatCore) {
|
||||
this.napCatCore = core;
|
||||
this.logger = core.context.logger;
|
||||
this.config = core.configLoader.configData;
|
||||
protected constructor(context: PacketContext) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
private randText(len: number): string {
|
||||
let text = '';
|
||||
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
for (let i = 0; i < len; i++) {
|
||||
text += possible.charAt(Math.floor(Math.random() * possible.length));
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
get available(): boolean {
|
||||
return this.isAvailable;
|
||||
}
|
||||
|
||||
abstract check(core: NapCatCore): boolean;
|
||||
abstract check(): boolean;
|
||||
|
||||
abstract init(pid: number, recv: string, send: string): Promise<void>;
|
||||
|
||||
abstract connect(cb: () => void): Promise<void>;
|
||||
|
||||
abstract sendCommandImpl(cmd: string, data: string, trace_id: string): void;
|
||||
|
||||
private async registerCallback(trace_id: string, type: string, callback: (json: RecvPacketData) => Promise<void>): Promise<void> {
|
||||
@@ -58,9 +46,14 @@ export abstract class PacketClient {
|
||||
private async sendCommand(cmd: string, data: string, trace_id: string, rsp: boolean = false, timeout: number = 20000, sendcb: (json: RecvPacketData) => void = () => {
|
||||
}): Promise<RecvPacketData> {
|
||||
return new Promise<RecvPacketData>((resolve, reject) => {
|
||||
if (!this.available) {
|
||||
reject(new Error('packetBackend 当前不可用!'));
|
||||
}
|
||||
|
||||
const timeoutHandle = setTimeout(() => {
|
||||
reject(new Error(`sendCommand timed out after ${timeout} ms for ${cmd} with trace_id ${trace_id}`));
|
||||
}, timeout);
|
||||
|
||||
this.registerCallback(trace_id, 'send', async (json: RecvPacketData) => {
|
||||
sendcb(json);
|
||||
if (!rsp) {
|
||||
@@ -68,30 +61,23 @@ export abstract class PacketClient {
|
||||
resolve(json);
|
||||
}
|
||||
});
|
||||
|
||||
if (rsp) {
|
||||
this.registerCallback(trace_id, 'recv', async (json: RecvPacketData) => {
|
||||
clearTimeout(timeoutHandle);
|
||||
resolve(json);
|
||||
});
|
||||
}
|
||||
|
||||
this.sendCommandImpl(cmd, data, trace_id);
|
||||
});
|
||||
}
|
||||
|
||||
async sendPacket(cmd: string, data: PacketHexStr, rsp = false): Promise<RecvPacketData> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!this.available) {
|
||||
this.logger.logError('NapCat.Packet 未初始化!');
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const md5 = crypto.createHash('md5').update(data).digest('hex');
|
||||
const trace_id = (this.randText(4) + md5 + data).slice(0, data.length / 2);
|
||||
|
||||
this.sendCommand(cmd, data, trace_id, rsp, 20000, async () => {
|
||||
//console.log('sendPacket:', cmd, data, trace_id);
|
||||
await this.napCatCore.context.session.getMsgService().sendSsoCmdReqByContend(cmd, trace_id);
|
||||
}).then((res) => resolve(res)).catch((e: Error) => reject(e));
|
||||
const md5 = crypto.createHash('md5').update(data).digest('hex');
|
||||
const trace_id = (randText(4) + md5 + data).slice(0, data.length / 2);
|
||||
return this.sendCommand(cmd, data, trace_id, rsp, 20000, async () => {
|
||||
await this.context.napcore.sendSsoCmdReqByContend(cmd, trace_id);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,37 +1,36 @@
|
||||
import crypto, { createHash } from "crypto";
|
||||
import { NapCatCore } from "@/core";
|
||||
import { createHash } from "crypto";
|
||||
import path, { dirname } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import fs from "fs";
|
||||
import { PacketClient } from "@/core/packet/client/client";
|
||||
import { IPacketClient } from "@/core/packet/client/baseClient";
|
||||
import { constants } from "node:os";
|
||||
import { LRUCache } from "@/common/lru-cache";
|
||||
//0 send 1recv
|
||||
import { PacketContext } from "@/core/packet/context/packetContext";
|
||||
|
||||
// 0 send 1 recv
|
||||
export interface NativePacketExportType {
|
||||
InitHook?: (recv: string, send: string, callback: (type: number, uin: string, cmd: string, seq: number, hex_data: string) => void) => boolean;
|
||||
SendPacket?: (cmd: string, data: string, trace_id: string) => void;
|
||||
}
|
||||
export class NativePacketClient extends PacketClient {
|
||||
|
||||
export class NativePacketClient extends IPacketClient {
|
||||
private readonly supportedPlatforms = ['win32.x64', 'linux.x64', 'linux.arm64'];
|
||||
private MoeHooExport: { exports: NativePacketExportType } = { exports: {} };
|
||||
private sendEvent = new LRUCache<number, string>(500);//seq->trace_id
|
||||
constructor(core: NapCatCore) {
|
||||
super(core);
|
||||
}
|
||||
private sendEvent = new LRUCache<number, string>(500); // seq->trace_id
|
||||
|
||||
get available(): boolean {
|
||||
return this.isAvailable;
|
||||
constructor(context: PacketContext) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
check(): boolean {
|
||||
const platform = process.platform + '.' + process.arch;
|
||||
if (!this.supportedPlatforms.includes(platform)) {
|
||||
this.logger.logWarn(`[Core] [Packet:Native] 不支持的平台: ${platform}`);
|
||||
this.context.logger.warn(`不支持的平台: ${platform}`);
|
||||
return false;
|
||||
}
|
||||
const moehoo_path = path.join(dirname(fileURLToPath(import.meta.url)), './moehoo/MoeHoo.' + platform + '.node');
|
||||
if (!fs.existsSync(moehoo_path)) {
|
||||
this.logger.logWarn(`[Core] [Packet:Native] 缺失运行时文件: ${moehoo_path}`);
|
||||
this.context.logger.warn(`[Core] [Packet:Native] 缺失运行时文件: ${moehoo_path}`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -54,27 +53,13 @@ export class NativePacketClient extends PacketClient {
|
||||
// console.log('callback:', callback, trace_id);
|
||||
callback?.({ seq, cmd, hex_data });
|
||||
}
|
||||
|
||||
// const callback = this.cb.get(createHash('md5').update(Buffer.from(hex_data, 'hex')).digest('hex') + (type === 0 ? 'send' : 'recv'));
|
||||
// if (callback) {
|
||||
// callback({ seq, cmd, hex_data });
|
||||
// } else {
|
||||
// this.logger.logError(`Callback not found for hex_data: ${hex_data}`);
|
||||
// }
|
||||
//console.log('type:', type, 'cmd:', cmd, 'trace_id:', trace_id);
|
||||
});
|
||||
this.isAvailable = true;
|
||||
this.available = true;
|
||||
}
|
||||
|
||||
sendCommandImpl(cmd: string, data: string, trace_id: string): void {
|
||||
const trace_id_md5 = createHash('md5').update(trace_id).digest('hex');
|
||||
//console.log('sendCommandImpl:', cmd, data, trace_id_md5);
|
||||
this.MoeHooExport.exports.SendPacket?.(cmd, data, trace_id_md5);
|
||||
this.cb.get(trace_id_md5 + 'send')?.({ seq: 0, cmd, hex_data: '' });
|
||||
}
|
||||
|
||||
connect(cb: () => void): Promise<void> {
|
||||
cb();
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
@@ -1,98 +1,100 @@
|
||||
import { Data, WebSocket } from "ws";
|
||||
import { NapCatCore } from "@/core";
|
||||
import { PacketClient, RecvPacket } from "@/core/packet/client/client";
|
||||
import { IPacketClient, RecvPacket } from "@/core/packet/client/baseClient";
|
||||
import { PacketContext } from "@/core/packet/context/packetContext";
|
||||
|
||||
export class wsPacketClient extends PacketClient {
|
||||
private websocket: WebSocket | undefined;
|
||||
export class wsPacketClient extends IPacketClient {
|
||||
private websocket: WebSocket | null = null;
|
||||
private reconnectAttempts: number = 0;
|
||||
private readonly maxReconnectAttempts: number = 60; // 现在暂时不可配置
|
||||
private readonly clientUrl: string | null = null;
|
||||
private clientUrlWrap: (url: string) => string = (url: string) => `ws://${url}/ws`;
|
||||
private readonly clientUrl: string;
|
||||
private readonly clientUrlWrap: (url: string) => string = (url: string) => `ws://${url}/ws`;
|
||||
|
||||
constructor(core: NapCatCore) {
|
||||
super(core);
|
||||
this.clientUrl = this.config.packetServer ? this.clientUrlWrap( this.config.packetServer) : null;
|
||||
private isInitialized: boolean = false;
|
||||
private initPayload: { pid: number, recv: string, send: string } | null = null;
|
||||
|
||||
constructor(context: PacketContext) {
|
||||
super(context);
|
||||
this.clientUrl = this.context.napcore.config.packetServer
|
||||
? this.clientUrlWrap(this.context.napcore.config.packetServer)
|
||||
: this.clientUrlWrap('127.0.0.1:8083');
|
||||
}
|
||||
|
||||
check(): boolean {
|
||||
if (!this.clientUrl) {
|
||||
this.logger.logWarn(`[Core] [Packet:Server] 未配置服务器地址`);
|
||||
if (!this.context.napcore.config.packetServer) {
|
||||
this.context.logger.warn(`wsPacketClient 未配置服务器地址`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
connect(cb: () => void): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
//this.logger.log.bind(this.logger)(`[Core] [Packet Server] Attempting to connect to ${this.clientUrl}`);
|
||||
this.websocket = new WebSocket(this.clientUrl!);
|
||||
this.websocket.on('error', (err) => { }/*this.logger.logError.bind(this.logger)('[Core] [Packet Server] Error:', err.message)*/);
|
||||
async init(pid: number, recv: string, send: string): Promise<void> {
|
||||
this.initPayload = { pid, recv, send };
|
||||
await this.connectWithRetry();
|
||||
}
|
||||
|
||||
sendCommandImpl(cmd: string, data: string, trace_id: string): void {
|
||||
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
|
||||
this.websocket.send(JSON.stringify({
|
||||
action: 'send',
|
||||
cmd,
|
||||
data,
|
||||
trace_id
|
||||
}));
|
||||
} else {
|
||||
this.context.logger.warn(`WebSocket 未连接,无法发送命令: ${cmd}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async connectWithRetry(): Promise<void> {
|
||||
while (this.reconnectAttempts < this.maxReconnectAttempts) {
|
||||
try {
|
||||
await this.connect();
|
||||
return;
|
||||
} catch (error) {
|
||||
this.reconnectAttempts++;
|
||||
this.context.logger.warn(`第 ${this.reconnectAttempts}/${this.maxReconnectAttempts} 次尝试重连失败!`);
|
||||
await this.delay(5000);
|
||||
}
|
||||
}
|
||||
this.context.logger.error(`wsPacketClient 在 ${this.clientUrl} 达到最大重连次数 (${this.maxReconnectAttempts})!`);
|
||||
throw new Error(`无法连接到 WebSocket 服务器:${this.clientUrl}`);
|
||||
}
|
||||
|
||||
private connect(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.websocket = new WebSocket(this.clientUrl);
|
||||
this.websocket.onopen = () => {
|
||||
this.isAvailable = true;
|
||||
this.available = true;
|
||||
this.reconnectAttempts = 0;
|
||||
this.logger.log.bind(this.logger)(`[Core] [Packet:Server] 已连接到 ${this.clientUrl}`);
|
||||
cb();
|
||||
this.context.logger.info(`wsPacketClient 已连接到 ${this.clientUrl}`);
|
||||
if (!this.isInitialized && this.initPayload) {
|
||||
this.websocket!.send(JSON.stringify({
|
||||
action: 'init',
|
||||
...this.initPayload
|
||||
}));
|
||||
this.isInitialized = true;
|
||||
}
|
||||
resolve();
|
||||
};
|
||||
|
||||
this.websocket.onerror = (error) => {
|
||||
//this.logger.logError.bind(this.logger)(`WebSocket error: ${error}`);
|
||||
reject(new Error(`${error.message}`));
|
||||
};
|
||||
|
||||
this.websocket.onmessage = (event) => {
|
||||
// const message = JSON.parse(event.data.toString());
|
||||
// console.log("Received message:", message);
|
||||
this.handleMessage(event.data).then().catch();
|
||||
};
|
||||
|
||||
this.websocket.onclose = () => {
|
||||
this.isAvailable = false;
|
||||
//this.logger.logWarn.bind(this.logger)(`[Core] [Packet Server] Disconnected from ${this.clientUrl}`);
|
||||
this.attemptReconnect(cb);
|
||||
this.available = false;
|
||||
this.context.logger.warn(`WebSocket 连接关闭,尝试重连...`);
|
||||
reject(new Error('WebSocket 连接关闭'));
|
||||
};
|
||||
this.websocket.onmessage = (event) => this.handleMessage(event.data).catch(err => {
|
||||
this.context.logger.error(`处理消息时出错: ${err}`);
|
||||
});
|
||||
this.websocket.onerror = (error) => {
|
||||
this.available = false;
|
||||
this.context.logger.error(`WebSocket 出错: ${error.message}`);
|
||||
this.websocket?.close();
|
||||
reject(error);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private attemptReconnect(cb: any): void {
|
||||
try {
|
||||
if (this.reconnectAttempts < this.maxReconnectAttempts) {
|
||||
this.reconnectAttempts++;
|
||||
setTimeout(() => {
|
||||
this.connect(cb).catch((error) => {
|
||||
this.logger.logError.bind(this.logger)(`[Core] [Packet:Server] 尝试重连失败:${error.message}`);
|
||||
});
|
||||
}, 5000 * this.reconnectAttempts);
|
||||
} else {
|
||||
this.logger.logError.bind(this.logger)(`[Core] [Packet:Server] ${this.clientUrl} 已达到最大重连次数!`);
|
||||
}
|
||||
} catch (error: any) {
|
||||
this.logger.logError.bind(this.logger)(`[Core] [Packet:Server] 重连时出错: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async init(pid: number, recv: string, send: string): Promise<void> {
|
||||
if (!this.isAvailable || !this.websocket) {
|
||||
throw new Error("WebSocket is not connected");
|
||||
}
|
||||
const initMessage = {
|
||||
action: 'init',
|
||||
pid: pid,
|
||||
recv: recv,
|
||||
send: send
|
||||
};
|
||||
this.websocket.send(JSON.stringify(initMessage));
|
||||
}
|
||||
|
||||
sendCommandImpl(cmd: string, data: string, trace_id: string) : void {
|
||||
const commandMessage = {
|
||||
action: 'send',
|
||||
cmd: cmd,
|
||||
data: data,
|
||||
trace_id: trace_id
|
||||
};
|
||||
this.websocket!.send(JSON.stringify(commandMessage));
|
||||
private delay(ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
private async handleMessage(message: Data): Promise<void> {
|
||||
@@ -100,13 +102,10 @@ export class wsPacketClient extends PacketClient {
|
||||
const json: RecvPacket = JSON.parse(message.toString());
|
||||
const trace_id_md5 = json.trace_id_md5;
|
||||
const action = json?.type ?? 'init';
|
||||
const event = this.cb.get(trace_id_md5 + action);
|
||||
if (event) {
|
||||
await event(json.data);
|
||||
}
|
||||
//console.log("Received message:", json);
|
||||
const event = this.cb.get(`${trace_id_md5}${action}`);
|
||||
if (event) await event(json.data);
|
||||
} catch (error) {
|
||||
this.logger.logError.bind(this.logger)(`Error parsing message: ${error}`);
|
||||
this.context.logger.error(`解析ws消息时出错: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user