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){ for(let group of _groups){
let existGroup = groups.find(g=>g.groupCode == group.groupCode) let existGroup = groups.find(g=>g.groupCode == group.groupCode)
if (!existGroup){ if (!existGroup){
log("update group") // log("update group")
let _membeers = await NTQQApi.getGroupMembers(group.groupCode) let _membeers = await NTQQApi.getGroupMembers(group.groupCode)
if (_membeers){ if (_membeers){
group.members = _membeers group.members = _membeers

View File

@ -146,23 +146,23 @@ export class NTQQApi {
} }
// static async getFriends(forced = false) { 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) 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[] = []; let _friends: Friend[] = [];
// for (const fData of data.data) { for (const fData of data.data) {
// _friends.push(...fData.buddyList) _friends.push(...fData.buddyList)
// } }
// return _friends return _friends
// } }
// static async getGroups(forced = false) { static async getGroups(forced = false) {
// let cbCmd = ReceiveCmd.GROUPS let cbCmd = ReceiveCmd.GROUPS
// if (process.platform != "win32") { if (process.platform != "win32") {
// cbCmd = ReceiveCmd.GROUPS_UNIX 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) 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 return result.groupList
// } }
static async getGroupMembers(groupQQ: string, num = 3000) { static async getGroupMembers(groupQQ: string, num = 3000) {
const sceneId = await callNTQQApi(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.GROUP_MEMBER_SCENE, [{ 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 { OB11Response } from "./utils"
import { OB11Return } from "../types";
class BaseAction { class BaseAction<PayloadType, ReturnDataType> {
async check(jsonData: any): Promise<BaseCheckResult> { actionName: ActionName
protected async check(payload: PayloadType): Promise<BaseCheckResult> {
return { return {
valid: true, valid: true,
} }
} }
async handle(jsonData: any) { public async handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
const result = await this.check(jsonData) const result = await this.check(payload)
if (!result.valid) { if (!result.valid) {
return OB11Response.error(result.message) return OB11Response.error(result.message)
} }
const resData = await this._handle(jsonData) try {
return resData const resData = await this._handle(payload)
return OB11Response.ok(resData)
}catch (e) {
return OB11Response.error(e.toString())
}
} }
async _handle(payload: unknown): Promise<unknown> { protected async _handle(payload: PayloadType): Promise<ReturnDataType> {
return throw `pleas override ${this.actionName} _handle`
} }
} }

View File

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

View File

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

View File

@ -1,22 +1,16 @@
import { OB11Response } from "./utils"; import { OB11Group } from '../types';
import { OB11Group, OB11Return } from '../types';
import { OB11Constructor } from "../constructor"; import { OB11Constructor } from "../constructor";
import { groups } from "../../common/data"; import { groups } from "../../common/data";
import BaseAction from "./BaseAction"; 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 { protected async _handle(payload: null){
static ACTION_TYPE: ActionType = 'get_group_list' return OB11Constructor.groups(groups);
async _handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
return OB11Response.ok(OB11Constructor.groups(groups));
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -1,24 +1,9 @@
import { OB11PostSendMsg, OB11Return } from '../types';
import SendMsg from "./SendMsg"; import SendMsg from "./SendMsg";
import BaseAction from './BaseAction'; import { ActionName } from "./types";
export type ActionType = 'send_group_msg'
export interface PayloadType extends OB11PostSendMsg { class SendGroupMsg extends SendMsg{
action: ActionType actionName = ActionName.SendGroupMsg
}
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)
}
} }
export default SendGroupMsg export default SendGroupMsg

View File

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

View File

@ -1,6 +1,3 @@
import { OB11Return } from '../types';
import { OB11Response } from './utils'
import GetMsg from './GetMsg' import GetMsg from './GetMsg'
import GetLoginInfo from './GetLoginInfo' import GetLoginInfo from './GetLoginInfo'
import GetFriendList from './GetFriendList' import GetFriendList from './GetFriendList'
@ -12,26 +9,10 @@ import SendGroupMsg from './SendGroupMsg'
import SendPrivateMsg from './SendPrivateMsg' import SendPrivateMsg from './SendPrivateMsg'
import SendMsg from './SendMsg' import SendMsg from './SendMsg'
export const actionHandles = { export const actionHandlers = [
[GetMsg.ACTION_TYPE]: new GetMsg(), new GetMsg(),
[GetLoginInfo.ACTION_TYPE]: new GetLoginInfo(), new GetLoginInfo(),
[GetFriendList.ACTION_TYPE]: new GetFriendList(), new GetFriendList(),
[GetGroupList.ACTION_TYPE]: new GetGroupList(), new GetGroupList(), new GetGroupInfo(), new GetGroupMemberList(), new GetGroupMemberInfo(),
[GetGroupInfo.ACTION_TYPE]: new GetGroupInfo(), new SendGroupMsg(), new SendPrivateMsg(), new SendMsg()
[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}`)
}
}

View File

@ -10,3 +10,17 @@ export interface InvalidCheckResult {
message: string message: string
[k: string | number]: any [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'; 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 { export class OB11Response {
static res<T>(data: T, status: number = 0, message: string = ""): OB11Return<T> { static res<T>(data: T, status: number = 0, message: string = ""): OB11Return<T> {
return { return {

View File

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