Skip to content

Commit

Permalink
fix: 进一步重构
Browse files Browse the repository at this point in the history
  • Loading branch information
MliKiowa committed Jan 21, 2025
1 parent f5db961 commit 4b53e9a
Show file tree
Hide file tree
Showing 14 changed files with 157 additions and 311 deletions.
11 changes: 6 additions & 5 deletions src/onebot/action/OneBotAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ActionName, BaseCheckResult } from './router';
import Ajv, { ErrorObject, ValidateFunction } from 'ajv';
import { NapCatCore } from '@/core';
import { NapCatOneBot11Adapter, OB11Return } from '@/onebot';
import { NetworkAdapterConfig } from '../config/config';

export class OB11Response {
private static createResponse<T>(data: T, status: string, retcode: number, message: string = '', echo: any = null): OB11Return<T> {
Expand Down Expand Up @@ -55,33 +56,33 @@ export abstract class OneBotAction<PayloadType, ReturnDataType> {
return { valid: true };
}

public async handle(payload: PayloadType, adaptername: string): Promise<OB11Return<ReturnDataType | null>> {
public async handle(payload: PayloadType, adaptername: string, config: NetworkAdapterConfig): Promise<OB11Return<ReturnDataType | null>> {
const result = await this.check(payload);
if (!result.valid) {
return OB11Response.error(result.message, 400);
}
try {
const resData = await this._handle(payload, adaptername);
const resData = await this._handle(payload, adaptername, config);
return OB11Response.ok(resData);
} catch (e: any) {
this.core.context.logger.logError('发生错误', e);
return OB11Response.error((e as Error).message.toString() || e?.stack?.toString() || '未知错误,可能操作超时', 200);
}
}

public async websocketHandle(payload: PayloadType, echo: any, adaptername: string): Promise<OB11Return<ReturnDataType | null>> {
public async websocketHandle(payload: PayloadType, echo: any, adaptername: string, config: NetworkAdapterConfig): Promise<OB11Return<ReturnDataType | null>> {
const result = await this.check(payload);
if (!result.valid) {
return OB11Response.error(result.message, 1400, echo);
}
try {
const resData = await this._handle(payload, adaptername);
const resData = await this._handle(payload, adaptername, config);
return OB11Response.ok(resData, echo);
} catch (e: any) {
this.core.context.logger.logError('发生错误', e);
return OB11Response.error((e as Error).message.toString() || e.stack?.toString(), 1200, echo);
}
}

abstract _handle(payload: PayloadType, adaptername: string): Promise<ReturnDataType>;
abstract _handle(payload: PayloadType, adaptername: string, config: NetworkAdapterConfig): Promise<ReturnDataType>;
}
8 changes: 4 additions & 4 deletions src/onebot/action/go-cqhttp/GetFriendMsgHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { OB11Message } from '@/onebot';
import { ActionName } from '@/onebot/action/router';
import { ChatType } from '@/core/types';
import { MessageUnique } from '@/common/message-unique';
import { AdapterConfigWrap } from '@/onebot/config/config';

import { Static, Type } from '@sinclair/typebox';
import { NetworkAdapterConfig } from '@/onebot/config/config';

interface Response {
messages: OB11Message[];
Expand All @@ -23,7 +24,7 @@ export default class GetFriendMsgHistory extends OneBotAction<Payload, Response>
actionName = ActionName.GetFriendMsgHistory;
payloadSchema = SchemaData;

async _handle(payload: Payload, adapter: string): Promise<Response> {
async _handle(payload: Payload, adapter: string, config: NetworkAdapterConfig): Promise<Response> {
//处理参数
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());

Expand All @@ -42,10 +43,9 @@ export default class GetFriendMsgHistory extends OneBotAction<Payload, Response>
await Promise.all(msgList.map(async msg => {
msg.id = MessageUnique.createUniqueMsgId({ guildId: '', chatType: msg.chatType, peerUid: msg.peerUid }, msg.msgId);
}));
const network = Object.values(this.obContext.configLoader.configData.network) as Array<AdapterConfigWrap>;
//烘焙消息
const ob11MsgList = (await Promise.all(
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, network.flat().find(e => e.name === adapter)?.messagePostFormat ?? 'array')))
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat)))
).filter(msg => msg !== undefined);
return { 'messages': ob11MsgList };
}
Expand Down
8 changes: 3 additions & 5 deletions src/onebot/action/go-cqhttp/GetGroupMsgHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { OB11Message } from '@/onebot';
import { ActionName } from '@/onebot/action/router';
import { ChatType, Peer } from '@/core/types';
import { MessageUnique } from '@/common/message-unique';
import { AdapterConfigWrap } from '@/onebot/config/config';
import { Static, Type } from '@sinclair/typebox';
import { NetworkAdapterConfig } from '@/onebot/config/config';

interface Response {
messages: OB11Message[];
Expand All @@ -25,7 +25,7 @@ export default class GoCQHTTPGetGroupMsgHistory extends OneBotAction<Payload, Re
actionName = ActionName.GoCQHTTP_GetGroupMsgHistory;
payloadSchema = SchemaData;

async _handle(payload: Payload, adapter: string): Promise<Response> {
async _handle(payload: Payload, adapter: string, config: NetworkAdapterConfig): Promise<Response> {
//处理参数
const isReverseOrder = typeof payload.reverseOrder === 'string' ? payload.reverseOrder === 'true' : !!payload.reverseOrder;
const peer: Peer = { chatType: ChatType.KCHATTYPEGROUP, peerUid: payload.group_id.toString() };
Expand All @@ -41,11 +41,9 @@ export default class GoCQHTTPGetGroupMsgHistory extends OneBotAction<Payload, Re
await Promise.all(msgList.map(async msg => {
msg.id = MessageUnique.createUniqueMsgId({ guildId: '', chatType: msg.chatType, peerUid: msg.peerUid }, msg.msgId);
}));
const network = Object.values(this.obContext.configLoader.configData.network) as Array<AdapterConfigWrap>;
//烘焙消息
const msgFormat = network.flat().find(e => e.name === adapter)?.messagePostFormat ?? 'array';
const ob11MsgList = (await Promise.all(
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, msgFormat)))
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat)))
).filter(msg => msg !== undefined);
return { 'messages': ob11MsgList };
}
Expand Down
8 changes: 3 additions & 5 deletions src/onebot/action/group/GetGroupEssence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { OneBotAction } from '@/onebot/action/OneBotAction';
import { ActionName } from '@/onebot/action/router';
import { MessageUnique } from '@/common/message-unique';
import crypto from 'crypto';
import { AdapterConfigWrap } from '@/onebot/config/config';
import { Static, Type } from '@sinclair/typebox';
import { NetworkAdapterConfig } from '@/onebot/config/config';

const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
Expand All @@ -27,9 +27,7 @@ export class GetGroupEssence extends OneBotAction<Payload, any> {
};
}

async _handle(payload: Payload, adapter: string) {
const network = Object.values(this.obContext.configLoader.configData.network) as Array<AdapterConfigWrap>;
const msgFormat = network.flat().find(e => e.name === adapter)?.messagePostFormat ?? 'array';
async _handle(payload: Payload, adapter: string, config: NetworkAdapterConfig) {
const msglist = (await this.core.apis.WebApi.getGroupEssenceMsgAll(payload.group_id.toString())).flatMap((e) => e.data.msg_list);
if (!msglist) {
throw new Error('获取失败');
Expand All @@ -50,7 +48,7 @@ export class GetGroupEssence extends OneBotAction<Payload, any> {
operator_nick: msg.add_digest_nick,
message_id: message_id,
operator_time: msg.add_digest_time,
content: (await this.obContext.apis.MsgApi.parseMessage(rawMessage, msgFormat))?.message
content: (await this.obContext.apis.MsgApi.parseMessage(rawMessage, config.messagePostFormat))?.message
};
}
const msgTempData = JSON.stringify({
Expand Down
8 changes: 3 additions & 5 deletions src/onebot/action/msg/GetMsg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { OneBotAction } from '@/onebot/action/OneBotAction';
import { ActionName } from '@/onebot/action/router';
import { MessageUnique } from '@/common/message-unique';
import { RawMessage } from '@/core';
import { AdapterConfigWrap } from '@/onebot/config/config';
import { Static, Type } from '@sinclair/typebox';
import { NetworkAdapterConfig } from '@/onebot/config/config';

export type ReturnDataType = OB11Message

Expand All @@ -18,10 +18,8 @@ class GetMsg extends OneBotAction<Payload, OB11Message> {
actionName = ActionName.GetMsg;
payloadSchema = SchemaData;

async _handle(payload: Payload, adapter: string) {
async _handle(payload: Payload, adapter: string, config: NetworkAdapterConfig) {
// log("history msg ids", Object.keys(msgHistory));
const network = Object.values(this.obContext.configLoader.configData.network) as Array<AdapterConfigWrap>;
const msgFormat = network.flat().find(e => e.name === adapter)?.messagePostFormat ?? 'array';
if (!payload.message_id) {
throw Error('参数message_id不能为空');
}
Expand All @@ -38,7 +36,7 @@ class GetMsg extends OneBotAction<Payload, OB11Message> {
} else {
msg = (await this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgIdWithPeer?.MsgId || payload.message_id.toString()])).msgList[0];
}
const retMsg = await this.obContext.apis.MsgApi.parseMessage(msg, msgFormat);
const retMsg = await this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat);
if (!retMsg) throw Error('消息为空');
try {
retMsg.message_id = MessageUnique.createUniqueMsgId(peer, msg.msgId)!;
Expand Down
8 changes: 3 additions & 5 deletions src/onebot/action/user/GetRecentContact.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

import { OneBotAction } from '@/onebot/action/OneBotAction';
import { ActionName } from '@/onebot/action/router';
import { AdapterConfigWrap } from '@/onebot/config/config';
import { NetworkAdapterConfig } from '@/onebot/config/config';
import { Static, Type } from '@sinclair/typebox';

const SchemaData = Type.Object({
Expand All @@ -14,16 +14,14 @@ export default class GetRecentContact extends OneBotAction<Payload, any> {
actionName = ActionName.GetRecentContact;
payloadSchema = SchemaData;

async _handle(payload: Payload, adapter: string) {
async _handle(payload: Payload, adapter: string, config: NetworkAdapterConfig) {
const ret = await this.core.apis.UserApi.getRecentContactListSnapShot(+payload.count);
const network = Object.values(this.obContext.configLoader.configData.network) as Array<AdapterConfigWrap>;
//烘焙消息
const msgFormat = network.flat().find(e => e.name === adapter)?.messagePostFormat ?? 'array';
return await Promise.all(ret.info.changedList.map(async (t) => {
const FastMsg = await this.core.apis.MsgApi.getMsgsByMsgId({ chatType: t.chatType, peerUid: t.peerUid }, [t.msgId]);
if (FastMsg.msgList.length > 0) {
//扩展ret.info.changedList
const lastestMsg = await this.obContext.apis.MsgApi.parseMessage(FastMsg.msgList[0], msgFormat);
const lastestMsg = await this.obContext.apis.MsgApi.parseMessage(FastMsg.msgList[0], config.messagePostFormat);
return {
lastestMsg: lastestMsg,
peerUin: t.peerUin,
Expand Down
36 changes: 18 additions & 18 deletions src/onebot/api/msg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -906,16 +906,16 @@ export class OneBotMsgApi {
const calculateTotalSize = async (elements: SendMessageElement[]): Promise<number> => {
const sizePromises = elements.map(async element => {
switch (element.elementType) {
case ElementType.PTT:
return (await fsPromise.stat(element.pttElement.filePath)).size;
case ElementType.FILE:
return (await fsPromise.stat(element.fileElement.filePath)).size;
case ElementType.VIDEO:
return (await fsPromise.stat(element.videoElement.filePath)).size;
case ElementType.PIC:
return (await fsPromise.stat(element.picElement.sourcePath)).size;
default:
return 0;
case ElementType.PTT:
return (await fsPromise.stat(element.pttElement.filePath)).size;
case ElementType.FILE:
return (await fsPromise.stat(element.fileElement.filePath)).size;
case ElementType.VIDEO:
return (await fsPromise.stat(element.videoElement.filePath)).size;
case ElementType.PIC:
return (await fsPromise.stat(element.picElement.sourcePath)).size;
default:
return 0;
}
});
const sizes = await Promise.all(sizePromises);
Expand Down Expand Up @@ -1008,14 +1008,14 @@ export class OneBotMsgApi {
}
groupChangDecreseType2String(type: number): GroupDecreaseSubType {
switch (type) {
case 130:
return 'leave';
case 131:
return 'kick';
case 3:
return 'kick_me';
default:
return 'kick';
case 130:
return 'leave';
case 131:
return 'kick';
case 3:
return 'kick_me';
default:
return 'kick';
}
}

Expand Down
Loading

0 comments on commit 4b53e9a

Please sign in to comment.