feat: face msg

feat: recall notice
This commit is contained in:
linyuchen 2024-02-17 20:06:17 +08:00
parent ba387b40ca
commit 1a1d673c8c
11 changed files with 173 additions and 103 deletions

View File

@ -1,22 +1,16 @@
// 运行在 Electron 主进程 下的插件入口
import * as path from "path";
import { BrowserWindow, ipcMain } from 'electron';
import * as util from 'util';
import { Config } from "../common/types";
import {
CHANNEL_GET_CONFIG,
CHANNEL_LOG,
CHANNEL_SET_CONFIG,
} from "../common/channels";
import { CHANNEL_GET_CONFIG, CHANNEL_LOG, CHANNEL_SET_CONFIG, } from "../common/channels";
import { postMsg, setToken, startHTTPServer, startWSServer } from "../onebot11/server";
import { CONFIG_DIR, getConfigUtil, log } from "../common/utils";
import { addHistoryMsg, msgHistory, selfInfo } from "../common/data";
import { addHistoryMsg, getGroupMember, msgHistory, selfInfo, uidMaps } from "../common/data";
import { hookNTQQApiReceive, ReceiveCmd, registerReceiveHook } from "../ntqqapi/hook";
import { OB11Constructor } from "../onebot11/constructor";
import { NTQQApi } from "../ntqqapi/ntcall";
import { Group, RawMessage, SelfInfo } from "../ntqqapi/types";
import { ChatType, RawMessage } from "../ntqqapi/types";
const fs = require('fs');
@ -39,13 +33,13 @@ function onLoad() {
ipcMain.on(CHANNEL_SET_CONFIG, (event: any, arg: Config) => {
let oldConfig = getConfigUtil().getConfig();
getConfigUtil().setConfig(arg)
if (arg.port != oldConfig.port){
if (arg.port != oldConfig.port) {
startHTTPServer(arg.port)
}
if (arg.wsPort != oldConfig.wsPort){
if (arg.wsPort != oldConfig.wsPort) {
startWSServer(arg.wsPort)
}
if (arg.token != oldConfig.token){
if (arg.token != oldConfig.token) {
setToken(arg.token);
}
})
@ -58,6 +52,7 @@ function onLoad() {
function postRawMsg(msgList: RawMessage[]) {
const {debug, reportSelfMessage} = getConfigUtil().getConfig();
for (let message of msgList) {
log("收到新消息", message)
message.msgShortId = msgHistory[message.msgId]?.msgShortId
if (!message.msgShortId) {
addHistoryMsg(message)
@ -76,7 +71,7 @@ function onLoad() {
}
function start() {
async function start() {
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload) => {
try {
// log("received msg length", payload.msgList.length);
@ -85,7 +80,38 @@ function onLoad() {
log("report message error: ", e.toString())
}
})
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.UPDATE_MSG, async (payload) => {
for (const message of payload.msgList) {
// log("message update", message, message.sendStatus)
if (message.sendStatus === 2) {
// 撤回消息上报
const oriMessage = msgHistory[message.msgId]
if (!oriMessage) {
continue
}
if (message.chatType == ChatType.friend) {
const friendRecallEvent = OB11Constructor.friendRecallEvent(message.senderUin, oriMessage.msgShortId)
postMsg(friendRecallEvent)
} else if (message.chatType == ChatType.group) {
let operatorId = message.senderUin
for (const element of message.elements) {
const operatorUid = element.grayTipElement?.revokeElement.operatorUid
const operator = await getGroupMember(message.peerUin, null, operatorUid)
operatorId = operator.uin
}
const groupRecallEvent = OB11Constructor.groupRecallEvent(
message.peerUin,
message.senderUin,
operatorId,
oriMessage.msgShortId
)
postMsg(groupRecallEvent)
}
continue
}
addHistoryMsg(message)
}
})
registerReceiveHook<{ msgRecord: RawMessage }>(ReceiveCmd.SELF_SEND_MSG, (payload) => {
const {reportSelfMessage} = getConfigUtil().getConfig()
if (!reportSelfMessage) {
@ -128,9 +154,8 @@ function onLoad() {
log("get self nickname failed", e.toString())
return setTimeout(init, 1000)
}
start();
}
else{
start().then();
} else {
setTimeout(init, 1000)
}
}

View File

@ -1,5 +1,13 @@
import {ElementType, SendPicElement, SendPttElement, SendReplyElement, SendTextElement, AtType} from "./types";
import {NTQQApi} from "./ntcall";
import {
ElementType,
SendPicElement,
SendPttElement,
SendReplyElement,
SendTextElement,
AtType,
SendFaceElement
} from "./types";
import { NTQQApi } from "./ntcall";
export class SendMsgElementConstructor {
@ -44,7 +52,7 @@ export class SendMsgElementConstructor {
}
}
static async pic(picPath: string): Promise<SendPicElement>{
static async pic(picPath: string): Promise<SendPicElement> {
const {md5, fileName, path, fileSize} = await NTQQApi.uploadFile(picPath);
const imageSize = await NTQQApi.getImageSize(picPath);
const picElement = {
@ -70,7 +78,7 @@ export class SendMsgElementConstructor {
};
}
static async ptt(pttPath: string):Promise<SendPttElement> {
static async ptt(pttPath: string): Promise<SendPttElement> {
const {md5, fileName, path, fileSize} = await NTQQApi.uploadFile(pttPath);
return {
elementType: ElementType.PTT,
@ -94,4 +102,15 @@ export class SendMsgElementConstructor {
}
};
}
static face(faceId: number): SendFaceElement {
return {
elementType: ElementType.FACE,
elementId: "",
faceElement: {
faceIndex: faceId,
faceType: 1
}
}
}
}

View File

@ -34,14 +34,14 @@ interface NTQQApiReturnData<PayloadType = unknown> extends Array<any> {
let receiveHooks: Array<{
method: ReceiveCmd,
hookFunc: (payload: any) => void,
hookFunc: ((payload: any) => void | Promise<void>)
id: string
}> = []
export function hookNTQQApiReceive(window: BrowserWindow) {
const originalSend = window.webContents.send;
const patchSend = (channel: string, ...args: NTQQApiReturnData) => {
log(`received ntqq api message: ${channel}`, JSON.stringify(args))
// log(`received ntqq api message: ${channel}`, JSON.stringify(args))
if (args?.[1] instanceof Array) {
for (let receiveData of args?.[1]) {
const ntQQApiMethodName = receiveData.cmdName;
@ -50,7 +50,10 @@ export function hookNTQQApiReceive(window: BrowserWindow) {
if (hook.method === ntQQApiMethodName) {
new Promise((resolve, reject) => {
try {
hook.hookFunc(receiveData.payload);
let _ = hook.hookFunc(receiveData.payload)
if (hook.hookFunc.constructor.name === "AsyncFunction"){
(_ as Promise<void>).then()
}
} catch (e) {
log("hook error", e, receiveData.payload)
}
@ -129,11 +132,7 @@ registerReceiveHook<{
// log("user info", payload);
// })
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.UPDATE_MSG, (payload) => {
for (const message of payload.msgList) {
addHistoryMsg(message)
}
})
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload) => {
for (const message of payload.msgList) {

View File

@ -7,13 +7,14 @@ export interface User {
remark?: string
}
export interface SelfInfo extends User{
export interface SelfInfo extends User {
}
export interface Friend extends User{}
export interface Friend extends User {
}
export interface Group{
export interface Group {
groupCode: string,
maxMember: number,
memberCount: number,
@ -62,6 +63,7 @@ export enum ElementType {
TEXT = 1,
PIC = 2,
PTT = 4,
FACE = 6,
REPLY = 7,
}
@ -76,6 +78,7 @@ export interface SendTextElement {
atNtUid: string,
}
}
export interface SendPttElement {
elementType: ElementType.PTT,
elementId: "",
@ -127,7 +130,13 @@ export interface SendReplyElement {
}
}
export type SendMessageElement = SendTextElement | SendPttElement | SendPicElement | SendReplyElement
export interface SendFaceElement {
elementType: ElementType.FACE,
elementId: "",
faceElement: FaceElement
}
export type SendMessageElement = SendTextElement | SendPttElement | SendPicElement | SendReplyElement | SendFaceElement
export enum AtType {
notAt = 0,
@ -140,6 +149,7 @@ export enum ChatType {
group = 2,
temp = 100
}
export interface PttElement {
canConvert2Text: boolean;
duration: number; // 秒数
@ -180,6 +190,22 @@ export interface PicElement {
fileUuid: string;
}
export interface GrayTipElement {
revokeElement: {
operatorRole: string;
operatorUid: string;
operatorNick: string;
operatorRemark: string;
operatorMemRemark?: string;
wording: string; // 自定义的撤回提示语
}
}
export interface FaceElement {
faceIndex: number,
faceType: 1
}
export interface RawMessage {
msgId: string;
msgShortId?: number; // 自己维护的消息id
@ -191,6 +217,7 @@ export interface RawMessage {
sendNickName: string;
sendMemberName?: string; // 发送者群名片
chatType: ChatType;
sendStatus?: number; // 消息状态2是已撤回
elements: {
elementId: string,
replyElement: {
@ -208,17 +235,7 @@ export interface RawMessage {
picElement: PicElement;
pttElement: PttElement;
arkElement: ArkElement;
grayTipElement: GrayTipElement;
faceElement: FaceElement;
}[];
}
export interface MessageElement {
raw: RawMessage;
peer: any;
sender: {
uid: string; // 一串加密的字符串
memberName: string;
nickname: string;
};
}

View File

@ -17,6 +17,9 @@ class GetMsg extends BaseAction<PayloadType, OB11Message> {
protected async _handle(payload: PayloadType){
// log("history msg ids", Object.keys(msgHistory));
if (!payload.message_id){
throw("参数message_id不能为空")
}
const msg = getHistoryMsgByShortId(payload.message_id)
if (msg) {
const msgData = await OB11Constructor.message(msg);

View File

@ -1,19 +1,10 @@
import { AtType, ChatType, Group } from "../../ntqqapi/types";
import {
addHistoryMsg,
friends,
getGroup,
getHistoryMsgByShortId,
getStrangerByUin,
} from "../../common/data";
import { AtType, ChatType, Group, SendMessageElement } from "../../ntqqapi/types";
import { addHistoryMsg, friends, getGroup, getHistoryMsgByShortId, getStrangerByUin, } from "../../common/data";
import { OB11MessageData, OB11MessageDataType, OB11PostSendMsg } from '../types';
import { NTQQApi } from "../../ntqqapi/ntcall";
import { Peer } from "../../ntqqapi/ntcall";
import { SendMessageElement } from "../../ntqqapi/types";
import { NTQQApi, Peer } from "../../ntqqapi/ntcall";
import { SendMsgElementConstructor } from "../../ntqqapi/constructor";
import { uri2local } from "../utils";
import { v4 as uuid4 } from 'uuid';
import { log } from "../../common/utils";
import BaseAction from "./BaseAction";
import { ActionName } from "./types";
import * as fs from "fs";
@ -25,7 +16,7 @@ export interface ReturnDataType {
class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
actionName = ActionName.SendMsg
protected async _handle(payload: OB11PostSendMsg){
protected async _handle(payload: OB11PostSendMsg) {
const peer: Peer = {
chatType: ChatType.friend,
peerUid: ""
@ -40,18 +31,16 @@ class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
peer.chatType = ChatType.group
// peer.name = group.name
peer.peerUid = group.groupCode
}
else if (payload?.user_id) {
} else if (payload?.user_id) {
const friend = friends.find(f => f.uin == payload.user_id.toString())
if (friend) {
// peer.name = friend.nickName
peer.peerUid = friend.uid
}
else {
} else {
peer.chatType = ChatType.temp
const tempUser = getStrangerByUin(payload.user_id.toString())
if (!tempUser) {
throw(`找不到私聊对象${payload.user_id}`)
throw (`找不到私聊对象${payload.user_id}`)
}
// peer.name = tempUser.nickName
peer.peerUid = tempUser.uid
@ -64,8 +53,7 @@ class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
text: payload.message
}
}] as OB11MessageData[]
}
else if (!Array.isArray(payload.message)) {
} else if (!Array.isArray(payload.message)) {
payload.message = [payload.message]
}
const sendElements: SendMessageElement[] = []
@ -76,22 +64,23 @@ class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
if (text) {
sendElements.push(SendMsgElementConstructor.text(sendMsg.data!.text))
}
} break;
}
break;
case OB11MessageDataType.at: {
let atQQ = sendMsg.data?.qq;
if (atQQ) {
atQQ = atQQ.toString()
if (atQQ === "all") {
sendElements.push(SendMsgElementConstructor.at(atQQ, atQQ, AtType.atAll, "全体成员"))
}
else {
} else {
const atMember = group?.members.find(m => m.uin == atQQ)
if (atMember) {
sendElements.push(SendMsgElementConstructor.at(atQQ, atMember.uid, AtType.atUser, atMember.cardName || atMember.nick))
}
}
}
} break;
}
break;
case OB11MessageDataType.reply: {
let replyMsgId = sendMsg.data.id;
if (replyMsgId) {
@ -101,20 +90,27 @@ class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
sendElements.push(SendMsgElementConstructor.reply(replyMsg.msgSeq, replyMsg.msgId, replyMsg.senderUin, replyMsg.senderUin))
}
}
} break;
}
break;
case OB11MessageDataType.face: {
const faceId = sendMsg.data?.id
if (faceId) {
sendElements.push(SendMsgElementConstructor.face(parseInt(faceId)))
}
}
break;
case OB11MessageDataType.image:
case OB11MessageDataType.voice: {
const file = sendMsg.data?.file
if (file) {
const {path, isLocal} = (await uri2local(uuid4(), file))
if (path) {
if (!isLocal){ // 只删除http和base64转过来的文件
if (!isLocal) { // 只删除http和base64转过来的文件
deleteAfterSentFiles.push(path)
}
if (sendMsg.type === OB11MessageDataType.image){
if (sendMsg.type === OB11MessageDataType.image) {
sendElements.push(await SendMsgElementConstructor.pic(path))
}
else {
} else {
sendElements.push(await SendMsgElementConstructor.ptt(path))
}
}
@ -126,10 +122,11 @@ class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
try {
const returnMsg = await NTQQApi.sendMsg(peer, sendElements)
addHistoryMsg(returnMsg)
deleteAfterSentFiles.map(f=>fs.unlink(f, ()=>{}))
return { message_id: returnMsg.msgShortId }
deleteAfterSentFiles.map(f => fs.unlink(f, () => {
}))
return {message_id: returnMsg.msgShortId}
} catch (e) {
throw(e.toString())
throw (e.toString())
}
}
}

View File

@ -113,6 +113,9 @@ export class OB11Constructor extends OB11EventConstructor{
} else if (element.arkElement) {
message_data["type"] = OB11MessageDataType.json;
message_data["data"]["data"] = element.arkElement.bytesData;
} else if (element.faceElement){
message_data["type"] = OB11MessageDataType.face;
message_data["data"]["id"] = element.faceElement.faceIndex.toString();
}
if (message_data.data.http_file) {
message_data.data.file = message_data.data.http_file

View File

@ -3,7 +3,7 @@ import {
OB11EventPostType, OB11FriendRecallNoticeEvent,
OB11GroupRecallNoticeEvent,
OB11HeartEvent,
OB11LifeCycleEvent, OB11MetaEvent, OB11NoticeBase
OB11LifeCycleEvent, OB11MetaEvent, OB11NoticeEvent
} from "./types";
import { heartInterval, selfInfo } from "../../common/data";
@ -16,7 +16,7 @@ function eventBase(post_type: OB11EventPostType): OB11EventBase {
}
export class OB11EventConstructor {
static lifeCycle(): OB11LifeCycleEvent {
static lifeCycleEvent(): OB11LifeCycleEvent {
return {
...eventBase(OB11EventPostType.META) as OB11MetaEvent,
meta_event_type: "lifecycle",
@ -24,7 +24,7 @@ export class OB11EventConstructor {
}
}
static heart(): OB11HeartEvent {
static heartEvent(): OB11HeartEvent {
return {
...eventBase(OB11EventPostType.META) as OB11MetaEvent,
meta_event_type: "heartbeat",
@ -36,9 +36,9 @@ export class OB11EventConstructor {
}
}
static groupRecall(group_id: string, user_id: string, operator_id: string, message_id: number): OB11GroupRecallNoticeEvent {
static groupRecallEvent(group_id: string, user_id: string, operator_id: string, message_id: number): OB11GroupRecallNoticeEvent {
return {
...eventBase(OB11EventPostType.NOTICE) as OB11NoticeBase,
...eventBase(OB11EventPostType.NOTICE) as OB11NoticeEvent,
notice_type: "group_recall",
group_id: parseInt(group_id),
user_id: parseInt(user_id),
@ -47,9 +47,9 @@ export class OB11EventConstructor {
}
}
static friendRecall(user_id: string, operator_id: string, message_id: number): OB11FriendRecallNoticeEvent {
static friendRecallEvent(user_id: string, message_id: number): OB11FriendRecallNoticeEvent {
return {
...eventBase(OB11EventPostType.NOTICE) as OB11NoticeBase,
...eventBase(OB11EventPostType.NOTICE) as OB11NoticeEvent,
notice_type: "friend_recall",
user_id: parseInt(user_id),
message_id

View File

@ -16,12 +16,12 @@ export interface OB11MetaEvent extends OB11EventBase{
meta_event_type: "lifecycle" | "heartbeat"
}
export interface OB11NoticeBase extends OB11EventBase{
export interface OB11NoticeEvent extends OB11EventBase{
post_type: OB11EventPostType.NOTICE
notice_type: "group_admin" | "group_decrease" | "group_increase" | "group_ban" | "friend_add" | "group_recall" | "friend_recall"
}
interface OB11GroupNoticeBase extends OB11NoticeBase{
interface OB11GroupNoticeBase extends OB11NoticeEvent{
group_id: number
user_id: number
}
@ -49,7 +49,7 @@ export interface OB11GroupRecallNoticeEvent extends OB11GroupNoticeBase{
message_id: number
}
export interface OB11FriendRecallNoticeEvent extends OB11NoticeBase{
export interface OB11FriendRecallNoticeEvent extends OB11NoticeEvent{
notice_type: "friend_recall"
user_id: number
message_id: number

View File

@ -12,7 +12,7 @@ import { OB11Response } from "./actions/utils";
import { ActionName } from "./actions/types";
import BaseAction from "./actions/BaseAction";
import { OB11Constructor } from "./constructor";
import { OB11LifeCycleEvent, OB11MetaEvent } from "./events/types";
import { OB11EventBase, OB11LifeCycleEvent, OB11MetaEvent, OB11NoticeEvent } from "./events/types";
let wsServer: websocket.Server = null;
let accessToken = ""
@ -60,8 +60,6 @@ const expressAuthorize = (req: Request, res: Response, next: () => void) => {
return res.status(403).send(JSON.stringify({message: 'token verify failed!'}));
}
}
next();
};
@ -87,7 +85,7 @@ let wsEventClients: websocket.WebSocket[] = [];
type RouterHandler = (payload: any) => Promise<OB11Return<any>>
let routers: Record<string, RouterHandler> = {};
function wsReply(wsClient: websocket.WebSocket, data: OB11Return<any> | OB11Message | OB11MetaEvent) {
function wsReply(wsClient: websocket.WebSocket, data: OB11Return<any> | PostMsgType) {
try {
wsClient.send(JSON.stringify(data))
log("ws 消息上报", data)
@ -163,14 +161,14 @@ export function startWSServer(port: number) {
log("event上报ws客户端已连接")
wsEventClients.push(ws)
try {
wsReply(ws, OB11Constructor.lifeCycle())
wsReply(ws, OB11Constructor.lifeCycleEvent())
}catch (e){
log("发送生命周期失败", e)
}
// 心跳
let wsHeart = setInterval(()=>{
if (wsEventClients.find(c => c == ws)){
wsReply(ws, OB11Constructor.heart())
wsReply(ws, OB11Constructor.heartEvent())
}
}, heartInterval)
ws.on("close", () => {
@ -182,11 +180,13 @@ export function startWSServer(port: number) {
})
}
type PostMsgType = OB11Message | OB11MetaEvent | OB11NoticeEvent
export function postMsg(msg: OB11Message) {
export function postMsg(msg: PostMsgType) {
const {reportSelfMessage} = getConfigUtil().getConfig()
// 判断msg是否是event
if (!reportSelfMessage) {
if (msg.user_id.toString() == selfInfo.uin) {
if ((msg as OB11Message).user_id.toString() == selfInfo.uin) {
return
}
}
@ -231,10 +231,10 @@ function registerRouter(action: string, handle: (payload: any) => Promise<any>)
}
expressAPP.post(url, expressAuthorize, (req: Request, res: Response) => {
_handle(res, req.body).then()
_handle(res, req.body || {}).then()
});
expressAPP.get(url, expressAuthorize, (req: Request, res: Response) => {
_handle(res, req.query as any).then()
_handle(res, req.query as any || {}).then()
});
routers[action] = handle
}

View File

@ -1,18 +1,18 @@
import { AtType, RawMessage } from "../ntqqapi/types";
export interface OB11User{
export interface OB11User {
user_id: number;
nickname: string;
remark?: string
}
export enum OB11UserSex{
export enum OB11UserSex {
male = "male",
female = "female",
unknown = "unknown"
}
export enum OB11GroupMemberRole{
export enum OB11GroupMemberRole {
owner = "owner",
admin = "admin",
member = "member",
@ -32,7 +32,7 @@ export interface OB11GroupMember {
title?: string
}
export interface OB11Group{
export interface OB11Group {
group_id: number
group_name: string
member_count?: number
@ -92,7 +92,8 @@ export interface OB11Return<DataType> {
echo?: string
}
export interface OB11SendMsgReturn extends OB11Return<{message_id: string}>{}
export interface OB11SendMsgReturn extends OB11Return<{ message_id: string }> {
}
export enum OB11MessageDataType {
text = "text",
@ -100,7 +101,8 @@ export enum OB11MessageDataType {
voice = "record",
at = "at",
reply = "reply",
json = "json"
json = "json",
face = "face"
}
export type OB11MessageData = {
@ -132,6 +134,11 @@ export type OB11MessageData = {
data: {
id: string,
}
} | {
type: OB11MessageDataType.face,
data: {
id: string
}
}
export interface OB11PostSendMsg {