refactor: Action

This commit is contained in:
linyuchen 2024-02-12 21:54:58 +08:00
parent 2d5d1c69c1
commit 0a8e25c121
18 changed files with 122 additions and 263 deletions

View File

@ -94,7 +94,7 @@ async function updateGroups(_groups: Group[]){
for(let group of _groups){
let existGroup = groups.find(g=>g.groupCode == group.groupCode)
if (!existGroup){
log("update group")
// log("update group")
let _membeers = await NTQQApi.getGroupMembers(group.groupCode)
if (_membeers){
group.members = _membeers

View File

@ -146,23 +146,23 @@ export class NTQQApi {
}
// static async getFriends(forced = false) {
// const data = await callNTQQApi<{ data: { categoryId: number, categroyName: string, categroyMbCount: number, buddyList: Friend[] }[] }>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.FRIENDS, [{ force_update: forced }, undefined], ReceiveCmd.FRIENDS)
// let _friends: Friend[] = [];
// for (const fData of data.data) {
// _friends.push(...fData.buddyList)
// }
// return _friends
// }
static async getFriends(forced = false) {
const data = await callNTQQApi<{ data: { categoryId: number, categroyName: string, categroyMbCount: number, buddyList: Friend[] }[] }>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.FRIENDS, [{ force_update: forced }, undefined], ReceiveCmd.FRIENDS)
let _friends: Friend[] = [];
for (const fData of data.data) {
_friends.push(...fData.buddyList)
}
return _friends
}
// static async getGroups(forced = false) {
// let cbCmd = ReceiveCmd.GROUPS
// if (process.platform != "win32") {
// cbCmd = ReceiveCmd.GROUPS_UNIX
// }
// const result = await callNTQQApi<{ updateType: number, groupList: Group[] }>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.GROUPS, [{ force_update: forced }, undefined], cbCmd)
// return result.groupList
// }
static async getGroups(forced = false) {
let cbCmd = ReceiveCmd.GROUPS
if (process.platform != "win32") {
cbCmd = ReceiveCmd.GROUPS_UNIX
}
const result = await callNTQQApi<{ updateType: number, groupList: Group[] }>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.GROUPS, [{ force_update: forced }, undefined], cbCmd)
return result.groupList
}
static async getGroupMembers(groupQQ: string, num = 3000) {
const sceneId = await callNTQQApi(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.GROUP_MEMBER_SCENE, [{

View File

@ -1,26 +0,0 @@
// import { OB11Return } from '../types';
// import BaseAction from "./BaseAction";
// export type ActionType = ''
// export interface PayloadType {
// action: ActionType
// // 参数定义待完善
// [k: string | number]: any
// }
// export interface ReturnDataType {
// // 参数定义待完善
// [k: string | number]: any
// }
// class ActionTemplate extends BaseAction {
// static ACTION_TYPE: ActionType = ''
// async _handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
// return
// }
// }
// export default ActionTemplate

View File

@ -1,24 +1,30 @@
import { BaseCheckResult } from "./types"
import {ActionName, BaseCheckResult} from "./types"
import { OB11Response } from "./utils"
import { OB11Return } from "../types";
class BaseAction {
async check(jsonData: any): Promise<BaseCheckResult> {
class BaseAction<PayloadType, ReturnDataType> {
actionName: ActionName
protected async check(payload: PayloadType): Promise<BaseCheckResult> {
return {
valid: true,
}
}
async handle(jsonData: any) {
const result = await this.check(jsonData)
public async handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
const result = await this.check(payload)
if (!result.valid) {
return OB11Response.error(result.message)
}
const resData = await this._handle(jsonData)
return resData
try {
const resData = await this._handle(payload)
return OB11Response.ok(resData)
}catch (e) {
return OB11Response.error(e.toString())
}
}
async _handle(payload: unknown): Promise<unknown> {
return
protected async _handle(payload: PayloadType): Promise<ReturnDataType> {
throw `pleas override ${this.actionName} _handle`
}
}

View File

@ -1,22 +1,15 @@
import { OB11Response } from "./utils";
import { OB11Return, OB11User } from '../types';
import { OB11User } from '../types';
import { OB11Constructor } from "../constructor";
import { friends } from "../../common/data";
import BaseAction from "./BaseAction";
import { ActionName } from "./types";
export type ActionType = 'get_friend_list'
export interface PayloadType {
action: ActionType
}
class GetFriendList extends BaseAction<null, OB11User[]> {
actionName = ActionName.GetFriendList
export type ReturnDataType = OB11User[]
class GetFriendList extends BaseAction {
static ACTION_TYPE: ActionType = 'get_friend_list'
async _handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
return OB11Response.ok(OB11Constructor.friends(friends));
protected async _handle(payload: null){
return OB11Constructor.friends(friends);
}
}

View File

@ -1,28 +1,22 @@
import { OB11Response } from "./utils";
import { OB11Group, OB11Return } from '../types';
import { OB11Group } from '../types';
import { getGroup, groups } from "../../common/data";
import { OB11Constructor } from "../constructor";
import BaseAction from "./BaseAction";
import { ActionName } from "./types";
export type ActionType = 'get_group_info'
export interface PayloadType {
action: ActionType
interface PayloadType {
group_id: number
}
export type ReturnDataType = OB11Group[]
class GetGroupInfo extends BaseAction<PayloadType, OB11Group[]> {
actionName = ActionName.GetGroupInfo
class GetGroupInfo extends BaseAction {
static ACTION_TYPE: ActionType = 'get_group_info'
async _handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
protected async _handle(payload: PayloadType) {
const group = await getGroup(payload.group_id.toString())
if (group) {
return OB11Response.ok(OB11Constructor.groups(groups));
}
else {
return OB11Response.error(`${payload.group_id}不存在`)
return OB11Constructor.groups(groups)
} else {
throw `${payload.group_id}不存在`
}
}
}

View File

@ -1,22 +1,16 @@
import { OB11Response } from "./utils";
import { OB11Group, OB11Return } from '../types';
import { OB11Group } from '../types';
import { OB11Constructor } from "../constructor";
import { groups } from "../../common/data";
import BaseAction from "./BaseAction";
import { ActionName } from "./types";
export type ActionType = 'get_group_list'
export interface PayloadType {
action: ActionType
}
export type ReturnDataType = OB11Group[]
class GetGroupList extends BaseAction<null, OB11Group[]> {
actionName = ActionName.GetGroupList
class GetGroupList extends BaseAction {
static ACTION_TYPE: ActionType = 'get_group_list'
async _handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
return OB11Response.ok(OB11Constructor.groups(groups));
protected async _handle(payload: null){
return OB11Constructor.groups(groups);
}
}

View File

@ -1,29 +1,25 @@
import { OB11Response } from "./utils";
import { OB11GroupMember, OB11Return } from '../types';
import { OB11GroupMember } from '../types';
import { getGroupMember } from "../../common/data";
import { OB11Constructor } from "../constructor";
import BaseAction from "./BaseAction";
import { ActionName } from "./types";
export type ActionType = 'get_group_member_info'
export interface PayloadType {
action: ActionType
group_id: number
user_id: number
}
export type ReturnDataType = OB11GroupMember
class GetGroupMemberInfo extends BaseAction<PayloadType, OB11GroupMember> {
actionName = ActionName.GetGroupMemberInfo
class GetGroupMemberInfo extends BaseAction {
static ACTION_TYPE: ActionType = 'get_group_member_info'
async _handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
protected async _handle(payload: PayloadType){
const member = await getGroupMember(payload.group_id.toString(), payload.user_id.toString())
if (member) {
return OB11Response.ok(OB11Constructor.groupMember(payload.group_id.toString(), member))
return OB11Constructor.groupMember(payload.group_id.toString(), member)
}
else {
return OB11Response.error(`群成员${payload.user_id}不存在`)
throw(`群成员${payload.user_id}不存在`)
}
}
}

View File

@ -1,32 +1,28 @@
import { OB11Response } from "./utils";
import { OB11GroupMember, OB11Return } from '../types';
import { OB11GroupMember } from '../types';
import { getGroup } from "../../common/data";
import { NTQQApi } from "../../ntqqapi/ntcall";
import { OB11Constructor } from "../constructor";
import BaseAction from "./BaseAction";
export type ActionType = 'get_group_member_list'
import { ActionName } from "./types";
export interface PayloadType {
action: ActionType
group_id: number
}
export type ReturnDataType = OB11GroupMember[]
class GetGroupMemberList extends BaseAction {
static ACTION_TYPE: ActionType = 'get_group_member_list'
class GetGroupMemberList extends BaseAction<PayloadType, OB11GroupMember[]> {
actionName = ActionName.GetGroupMemberList
async _handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
protected async _handle(payload: PayloadType){
const group = await getGroup(payload.group_id.toString());
if (group) {
if (!group.members?.length) {
group.members = await NTQQApi.getGroupMembers(payload.group_id.toString())
}
return OB11Response.ok(OB11Constructor.groupMembers(group));
return OB11Constructor.groupMembers(group);
}
else {
return OB11Response.error(`${payload.group_id}不存在`)
throw (`${payload.group_id}不存在`)
}
}
}

View File

@ -1,22 +1,15 @@
import { OB11Response } from "./utils";
import { OB11Return, OB11User } from '../types';
import { OB11User } from '../types';
import { OB11Constructor } from "../constructor";
import { selfInfo } from "../../common/data";
import BaseAction from "./BaseAction";
import { ActionName } from "./types";
export type ActionType = 'get_login_info'
export interface PayloadType {
action: ActionType
}
class GetLoginInfo extends BaseAction<null, OB11User> {
actionName = ActionName.GetLoginInfo
export type ReturnDataType = OB11User
class GetLoginInfo extends BaseAction {
static ACTION_TYPE: ActionType = 'get_login_info'
async _handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
return OB11Response.ok(OB11Constructor.selfInfo(selfInfo));
protected async _handle(payload: null){
return OB11Constructor.selfInfo(selfInfo);
}
}

View File

@ -1,30 +1,28 @@
import { OB11Response } from "./utils";
import { msgHistory } from "../../common/data";
import { OB11Message, OB11Return } from '../types';
import { OB11Message } from '../types';
import { OB11Constructor } from "../constructor";
import { log } from "../../common/utils";
import BaseAction from "./BaseAction";
import { ActionName } from "./types";
export type ActionType = 'get_msg'
export interface PayloadType {
action: ActionType
message_id: string
}
export type ReturnDataType = OB11Message
class GetMsg extends BaseAction {
static ACTION_TYPE: ActionType = 'get_msg'
class GetMsg extends BaseAction<PayloadType, OB11Message> {
actionName = ActionName.GetMsg
async _handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
log("history msg ids", Object.keys(msgHistory));
protected async _handle(payload: PayloadType){
// log("history msg ids", Object.keys(msgHistory));
const msg = msgHistory[payload.message_id.toString()]
if (msg) {
const msgData = await OB11Constructor.message(msg);
return OB11Response.ok(msgData)
return msgData
} else {
return OB11Response.error("消息不存在")
throw("消息不存在")
}
}
}

View File

@ -1,24 +1,9 @@
import { OB11PostSendMsg, OB11Return } from '../types';
import SendMsg from "./SendMsg";
import BaseAction from './BaseAction';
import { ActionName } from "./types";
export type ActionType = 'send_group_msg'
export interface PayloadType extends OB11PostSendMsg {
action: ActionType
}
export interface ReturnDataType {
message_id: string
}
class SendGroupMsg extends BaseAction {
static ACTION_TYPE: ActionType = 'send_group_msg'
async _handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
// 偷懒借用现有逻辑
return new SendMsg()._handle(payload as any)
}
class SendGroupMsg extends SendMsg{
actionName = ActionName.SendGroupMsg
}
export default SendGroupMsg

View File

@ -1,30 +1,24 @@
import { AtType, ChatType, Group } from "../../ntqqapi/types";
import { friends, getGroup, getStrangerByUin, msgHistory } from "../../common/data";
import { OB11Return, OB11MessageData, OB11MessageDataType, OB11PostSendMsg } from '../types';
import { OB11MessageData, OB11MessageDataType, OB11PostSendMsg } from '../types';
import { NTQQApi } from "../../ntqqapi/ntcall";
import { Peer } from "../../ntqqapi/ntcall";
import { SendMessageElement } from "../../ntqqapi/types";
import { SendMsgElementConstructor } from "../../ntqqapi/constructor";
import { uri2local } from "../utils";
import { OB11Response } from "./utils";
import { v4 as uuid4 } from 'uuid';
import { log } from "../../common/utils";
import BaseAction from "./BaseAction";
export type ActionType = 'send_msg'
export interface PayloadType extends OB11PostSendMsg {
action: ActionType
}
import { ActionName } from "./types";
export interface ReturnDataType {
message_id: string
}
class SendMsg extends BaseAction {
static ACTION_TYPE: ActionType = 'send_msg'
class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
actionName = ActionName.SendMsg
async _handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
protected async _handle(payload: OB11PostSendMsg){
const peer: Peer = {
chatType: ChatType.friend,
peerUid: ""
@ -33,7 +27,7 @@ class SendMsg extends BaseAction {
if (payload?.group_id) {
group = await getGroup(payload.group_id.toString())
if (!group) {
return OB11Response.error(`${payload.group_id}不存在`)
throw (`${payload.group_id}不存在`)
}
peer.chatType = ChatType.group
// peer.name = group.name
@ -49,7 +43,7 @@ class SendMsg extends BaseAction {
peer.chatType = ChatType.temp
const tempUser = getStrangerByUin(payload.user_id.toString())
if (!tempUser) {
return OB11Response.error(`找不到私聊对象${payload.user_id}`)
throw(`找不到私聊对象${payload.user_id}`)
}
// peer.name = tempUser.nickName
peer.peerUid = tempUser.uid
@ -120,12 +114,12 @@ class SendMsg extends BaseAction {
}
}
}
log("send msg:", peer, sendElements)
// log("send msg:", peer, sendElements)
try {
const returnMsg = await NTQQApi.sendMsg(peer, sendElements)
return OB11Response.ok({ message_id: returnMsg.msgId })
return { message_id: returnMsg.msgId }
} catch (e) {
return OB11Response.error(e.toString())
throw(e.toString())
}
}
}

View File

@ -1,24 +1,8 @@
import { OB11PostSendMsg, OB11Return } from '../types';
import SendMsg from "./SendMsg";
import BaseAction from './BaseAction';
import { ActionName } from "./types";
export type ActionType = 'send_private_msg'
export interface PayloadType extends OB11PostSendMsg {
action: ActionType
}
export interface ReturnDataType {
message_id: string
}
class SendPrivateMsg extends BaseAction {
static ACTION_TYPE: ActionType = 'send_private_msg'
async _handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
// 偷懒借用现有逻辑
return new SendMsg()._handle(payload as any)
}
class SendPrivateMsg extends SendMsg {
actionName = ActionName.SendPrivateMsg
}
export default SendPrivateMsg

View File

@ -1,6 +1,3 @@
import { OB11Return } from '../types';
import { OB11Response } from './utils'
import GetMsg from './GetMsg'
import GetLoginInfo from './GetLoginInfo'
import GetFriendList from './GetFriendList'
@ -12,26 +9,10 @@ import SendGroupMsg from './SendGroupMsg'
import SendPrivateMsg from './SendPrivateMsg'
import SendMsg from './SendMsg'
export const actionHandles = {
[GetMsg.ACTION_TYPE]: new GetMsg(),
[GetLoginInfo.ACTION_TYPE]: new GetLoginInfo(),
[GetFriendList.ACTION_TYPE]: new GetFriendList(),
[GetGroupList.ACTION_TYPE]: new GetGroupList(),
[GetGroupInfo.ACTION_TYPE]: new GetGroupInfo(),
[GetGroupMemberList.ACTION_TYPE]: new GetGroupMemberList(),
[GetGroupMemberInfo.ACTION_TYPE]: new GetGroupMemberInfo(),
[SendGroupMsg.ACTION_TYPE]: new SendGroupMsg(),
[SendPrivateMsg.ACTION_TYPE]: new SendPrivateMsg(),
[SendMsg.ACTION_TYPE]: new SendMsg(),
}
export async function handleAction(
jsonData: any,
): Promise<OB11Return<any>> {
const handler = actionHandles[jsonData.action]
if (handler) {
return await handler.handle(jsonData)
} else {
return OB11Response.error(`未知的 action: ${jsonData.action}`)
}
}
export const actionHandlers = [
new GetMsg(),
new GetLoginInfo(),
new GetFriendList(),
new GetGroupList(), new GetGroupInfo(), new GetGroupMemberList(), new GetGroupMemberInfo(),
new SendGroupMsg(), new SendPrivateMsg(), new SendMsg()
]

View File

@ -10,3 +10,17 @@ export interface InvalidCheckResult {
message: string
[k: string | number]: any
}
export enum ActionName{
GetLoginInfo = "get_login_info",
GetFriendList = "get_friend_list",
GetGroupInfo = "get_group_info",
GetGroupList = "get_group_list",
GetGroupMemberInfo = "get_group_member_info",
GetGroupMemberList = "get_group_member_list",
GetMsg = "get_msg",
SendMsg = "send_msg",
SendGroupMsg = "send_group_msg",
SendPrivateMsg = "send_private_msg",
DeleteMsg = "delete_msg"
}

View File

@ -1,48 +1,5 @@
import { OB11Return } from '../types';
// export function createSuccessActionResponse<T>({
// status = 0,
// retcode = 0,
// data = {} as T,
// ...others
// }: Partial<OB11Return<any>> = {} = {}): OB11Return<any> {
// return {
// status,
// retcode,
// data,
// message: '',
// ...others
// }
// }
// export function createFailedActionResponse({
// status = -1,
// retcode = -1,
// message = '',
// ...others
// }: Partial<OB11Return<any>> = {}): OB11Return<any> {
// return {
// status,
// retcode,
// data: {},
// message,
// ...others,
// }
// }
// export function createActionParamsErrorResponse(type, others = {}) {
// return createFailedActionResponse({
// message: `${type} 接收到了不正确的参数`,
// ...others,
// })
// }
// export function createErrorResponseWithParams(params = {}) {
// return createFailedActionResponse({
// ...params,
// })
// }
export class OB11Response {
static res<T>(data: T, status: number = 0, message: string = ""): OB11Return<T> {
return {

View File

@ -7,7 +7,7 @@ import { Response } from 'express';
const JSONbig = require('json-bigint')({ storeAsString: true });
import { selfInfo } from "../common/data";
import { OB11Message, OB11Return, OB11MessageData } from './types';
import { actionHandles } from "./actions";
import { actionHandlers } from "./actions";
// @SiberianHusky 2021-08-15
@ -156,6 +156,6 @@ function registerRouter(action: string, handle: (payload: any) => Promise<any>)
routers[url] = handle
}
for (const [action, handler] of Object.entries(actionHandles)) {
registerRouter(action, (payload) => handler.handle(payload))
}
for (const action of actionHandlers) {
registerRouter(action.actionName, (payload) => action.handle(payload))
}