refactor: MsgId

This commit is contained in:
手瓜一十雪
2024-07-22 11:15:01 +08:00
parent 0522ba35fe
commit 334e43e764
18 changed files with 90 additions and 104 deletions

View File

@@ -1,5 +1,5 @@
import { Peer } from '@/core'; import { Peer } from '@/core';
import crypto from 'crypto'; import crypto, { randomInt, randomUUID } from 'crypto';
class LimitedHashTable<K, V> { class LimitedHashTable<K, V> {
private keyToValue: Map<K, V> = new Map(); private keyToValue: Map<K, V> = new Map();
@@ -17,14 +17,17 @@ class LimitedHashTable<K, V> {
} }
this.keyToValue.set(key, value); this.keyToValue.set(key, value);
this.valueToKey.set(value, key); this.valueToKey.set(value, key);
while (this.keyToValue.size !== this.valueToKey.size){ while (this.keyToValue.size !== this.valueToKey.size) {
console.log('keyToValue.size !== valueToKey.size'); console.log('keyToValue.size !== valueToKey.size Error Atom');
} }
// console.log('---------------');
// console.log(this.keyToValue);
// console.log(this.valueToKey);
// console.log('---------------');
while (this.keyToValue.size > this.maxSize || this.valueToKey.size > this.maxSize) { while (this.keyToValue.size > this.maxSize || this.valueToKey.size > this.maxSize) {
//删除旧的值
const oldestKey = this.keyToValue.keys().next().value; const oldestKey = this.keyToValue.keys().next().value;
this.valueToKey.delete(this.keyToValue.get(oldestKey)!);
this.keyToValue.delete(oldestKey); this.keyToValue.delete(oldestKey);
this.valueToKey.delete(oldestKey);
} }
} }
@@ -91,5 +94,4 @@ class MessageUniqueWrapper {
} }
} }
export const MessageUnique = new MessageUniqueWrapper(); export const MessageUnique = new MessageUniqueWrapper(1000);

View File

@@ -13,6 +13,8 @@ import { deleteOldFiles, UpdateConfig } from './common/utils/helper';
import { dirname } from 'node:path'; import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import chalk from 'chalk'; import chalk from 'chalk';
import { randomInt } from 'crypto';
import { MessageUnique } from './common/utils/MessageUnique';
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
@@ -25,6 +27,16 @@ program
//deleteOldFiles(path.join(__dirname, 'logs'), 3).then().catch(); //deleteOldFiles(path.join(__dirname, 'logs'), 3).then().catch();
// UpdateConfig().catch(logError); 移除支持 // UpdateConfig().catch(logError); 移除支持
// 启动WebUi // 启动WebUi
for (let i = 0; i < 100; i++) {
console.log('---------------');
let msgid = randomInt(1000000000).toString();
let shortId = MessageUnique.createMsg({ chatType: 1, peerUid: '123' }, msgid);
console.log(`${msgid}--->${shortId}`);
msgid = MessageUnique.getMsgIdAndPeerByShortId(shortId!)?.MsgId!;
console.log(`${msgid}<---${shortId}`);
}
InitWebUi(); InitWebUi();
const cmdOptions = program.opts(); const cmdOptions = program.opts();
// console.log(process.argv); // console.log(process.argv);

View File

@@ -6,6 +6,7 @@ import { OB11Constructor } from '../../constructor';
import { ActionName, BaseCheckResult } from '../types'; import { ActionName, BaseCheckResult } from '../types';
import { FromSchema, JSONSchema } from 'json-schema-to-ts'; import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import Ajv from 'ajv'; import Ajv from 'ajv';
import { MessageUnique } from '@/common/utils/MessageUnique';
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
@@ -29,17 +30,12 @@ export class GoCQHTTPGetForwardMsgAction extends BaseAction<Payload, any> {
if (!msgId) { if (!msgId) {
throw Error('message_id is required'); throw Error('message_id is required');
} }
let rootMsg = await dbUtil.getMsgByLongId(msgId); let rootMsgId = MessageUnique.getShortIdByMsgId(msgId);
if (!rootMsg) { let rootMsg = MessageUnique.getMsgIdAndPeerByShortId(rootMsgId || parseInt(msgId))
rootMsg = await dbUtil.getMsgByShortId(parseInt(msgId));
if (!rootMsg) { if (!rootMsg) {
throw Error('msg not found'); throw Error('msg not found');
} }
} const data = await NTQQMsgApi.getMultiMsg(rootMsg.Peer, rootMsg.MsgId, rootMsg.MsgId);
const data = await NTQQMsgApi.getMultiMsg({
chatType: rootMsg.chatType,
peerUid: rootMsg.peerUid
}, rootMsg.msgId, rootMsg.msgId);
if (!data || data.result !== 0) { if (!data || data.result !== 0) {
throw Error('找不到相关的聊天记录' + data?.errMsg); throw Error('找不到相关的聊天记录' + data?.errMsg);
} }

View File

@@ -2,11 +2,11 @@ import BaseAction from '../BaseAction';
import { OB11Message, OB11User } from '../../types'; import { OB11Message, OB11User } from '../../types';
import { ActionName } from '../types'; import { ActionName } from '../types';
import { ChatType } from '@/core/entities'; import { ChatType } from '@/core/entities';
import { dbUtil } from '@/common/utils/db';
import { NTQQMsgApi } from '@/core/apis/msg'; import { NTQQMsgApi } from '@/core/apis/msg';
import { OB11Constructor } from '../../constructor'; import { OB11Constructor } from '../../constructor';
import { FromSchema, JSONSchema } from 'json-schema-to-ts'; import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { NTQQFriendApi, NTQQUserApi } from '@/core'; import { NTQQFriendApi, NTQQUserApi } from '@/core';
import { MessageUnique } from '@/common/utils/MessageUnique';
interface Response { interface Response {
messages: OB11Message[]; messages: OB11Message[];
@@ -32,7 +32,7 @@ export default class GetFriendMsgHistory extends BaseAction<Payload, Response> {
if (!uid) { if (!uid) {
throw `记录${payload.user_id}不存在`; throw `记录${payload.user_id}不存在`;
} }
const startMsgId = (await dbUtil.getMsgByShortId(payload.message_seq))?.msgId || '0'; const startMsgId = (await MessageUnique.getMsgIdAndPeerByShortId(payload.message_seq))?.MsgId || '0';
const friend = await NTQQFriendApi.isBuddy(uid); const friend = await NTQQFriendApi.isBuddy(uid);
const historyResult = (await NTQQMsgApi.getMsgHistory({ const historyResult = (await NTQQMsgApi.getMsgHistory({
chatType: friend ? ChatType.friend : ChatType.temp, chatType: friend ? ChatType.friend : ChatType.temp,
@@ -41,7 +41,7 @@ export default class GetFriendMsgHistory extends BaseAction<Payload, Response> {
//logDebug(historyResult); //logDebug(historyResult);
const msgList = historyResult.msgList; const msgList = historyResult.msgList;
await Promise.all(msgList.map(async msg => { await Promise.all(msgList.map(async msg => {
msg.id = await dbUtil.addMsg(msg); msg.id = await MessageUnique.createMsg({ guildId: '', chatType: msg.chatType, peerUid: msg.peerUid }, msg.msgId);
})); }));
const ob11MsgList = await Promise.all(msgList.map(msg => OB11Constructor.message(msg))); const ob11MsgList = await Promise.all(msgList.map(msg => OB11Constructor.message(msg)));
return { 'messages': ob11MsgList }; return { 'messages': ob11MsgList };

View File

@@ -3,11 +3,10 @@ import { OB11Message, OB11User } from '../../types';
import { getGroup, groups } from '@/core/data'; import { getGroup, groups } from '@/core/data';
import { ActionName } from '../types'; import { ActionName } from '../types';
import { ChatType } from '@/core/entities'; import { ChatType } from '@/core/entities';
import { dbUtil } from '@/common/utils/db';
import { NTQQMsgApi } from '@/core/apis/msg'; import { NTQQMsgApi } from '@/core/apis/msg';
import { OB11Constructor } from '../../constructor'; import { OB11Constructor } from '../../constructor';
import { logDebug } from '@/common/utils/log';
import { FromSchema, JSONSchema } from 'json-schema-to-ts'; import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { MessageUnique } from '@/common/utils/MessageUnique';
interface Response { interface Response {
messages: OB11Message[]; messages: OB11Message[];
} }
@@ -15,7 +14,7 @@ interface Response {
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
properties: { properties: {
group_id: { type: [ 'number' , 'string' ] }, group_id: { type: ['number', 'string'] },
message_seq: { type: 'number' }, message_seq: { type: 'number' },
count: { type: 'number' } count: { type: 'number' }
}, },
@@ -32,7 +31,7 @@ export default class GoCQHTTPGetGroupMsgHistory extends BaseAction<Payload, Resp
if (!group) { if (!group) {
throw `${payload.group_id}不存在`; throw `${payload.group_id}不存在`;
} }
const startMsgId = (await dbUtil.getMsgByShortId(payload.message_seq))?.msgId || '0'; const startMsgId = (await MessageUnique.getMsgIdAndPeerByShortId(payload.message_seq))?.MsgId || '0';
// log("startMsgId", startMsgId) // log("startMsgId", startMsgId)
const historyResult = (await NTQQMsgApi.getMsgHistory({ const historyResult = (await NTQQMsgApi.getMsgHistory({
chatType: ChatType.group, chatType: ChatType.group,
@@ -41,7 +40,7 @@ export default class GoCQHTTPGetGroupMsgHistory extends BaseAction<Payload, Resp
//logDebug(historyResult); //logDebug(historyResult);
const msgList = historyResult.msgList; const msgList = historyResult.msgList;
await Promise.all(msgList.map(async msg => { await Promise.all(msgList.map(async msg => {
msg.id = await dbUtil.addMsg(msg); msg.id = await MessageUnique.createMsg({ guildId: '', chatType: msg.chatType, peerUid: msg.peerUid }, msg.msgId);
})); }));
const ob11MsgList = await Promise.all(msgList.map(msg => OB11Constructor.message(msg))); const ob11MsgList = await Promise.all(msgList.map(msg => OB11Constructor.message(msg)));
return { 'messages': ob11MsgList }; return { 'messages': ob11MsgList };

View File

@@ -1,9 +1,9 @@
import { dbUtil } from '@/common/utils/db';
import BaseAction from '../BaseAction'; import BaseAction from '../BaseAction';
import { ActionName } from '../types'; import { ActionName } from '../types';
import { FromSchema, JSONSchema } from 'json-schema-to-ts'; import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { NTQQGroupApi } from '@/core'; import { NTQQGroupApi } from '@/core';
import { MessageUnique } from '@/common/utils/MessageUnique';
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
@@ -19,13 +19,13 @@ export default class DelEssenceMsg extends BaseAction<Payload, any> {
actionName = ActionName.DelEssenceMsg; actionName = ActionName.DelEssenceMsg;
PayloadSchema = SchemaData; PayloadSchema = SchemaData;
protected async _handle(payload: Payload): Promise<any> { protected async _handle(payload: Payload): Promise<any> {
const msg = await dbUtil.getMsgByShortId(parseInt(payload.message_id.toString())); const msg = await MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString()));
if (!msg) { if (!msg) {
throw new Error('msg not found'); throw new Error('msg not found');
} }
return await NTQQGroupApi.removeGroupEssence( return await NTQQGroupApi.removeGroupEssence(
msg.peerUin, msg.Peer.peerUid,
msg.msgId msg.MsgId
); );
} }
} }

View File

@@ -3,13 +3,9 @@ import { OB11GroupMember } from '../../types';
import { OB11Constructor } from '../../constructor'; import { OB11Constructor } from '../../constructor';
import BaseAction from '../BaseAction'; import BaseAction from '../BaseAction';
import { ActionName } from '../types'; import { ActionName } from '../types';
import { napCatCore, NTQQGroupApi, NTQQUserApi } from '@/core'; import { NTQQGroupApi } from '@/core';
import { WebApi } from '@/core/apis/webapi'; import { WebApi } from '@/core/apis/webapi';
import { logDebug } from '@/common/utils/log';
import { FromSchema, JSONSchema } from 'json-schema-to-ts'; import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { ob11Config } from '@/onebot11/config';
import { dbUtil } from '@/common/utils/db';
import { TypeConvert } from '@/common/utils/type';
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
@@ -63,15 +59,6 @@ class GetGroupMemberList extends BaseAction<Payload, OB11GroupMember[]> {
MemberMap.set(webGroupMembers[i]?.uin, MemberData); MemberMap.set(webGroupMembers[i]?.uin, MemberData);
} }
} }
} else if (ob11Config.GroupLocalTime.Record && ob11Config.GroupLocalTime.RecordList[0] === '-1' || ob11Config.GroupLocalTime.RecordList.includes(payload.group_id.toString())) {
const _sendAndJoinRember = await dbUtil.getLastSentTimeAndJoinTime(TypeConvert.toNumber(payload.group_id));
_sendAndJoinRember.forEach((element) => {
const MemberData = MemberMap.get(element.user_id);
if (MemberData) {
MemberData.join_time = element.join_time;
MemberData.last_sent_time = element.last_sent_time;
}
});
} }
// 还原索引到Array 一同返回 // 还原索引到Array 一同返回

View File

@@ -1,8 +1,8 @@
import { dbUtil } from '@/common/utils/db';
import BaseAction from '../BaseAction'; import BaseAction from '../BaseAction';
import { ActionName } from '../types'; import { ActionName } from '../types';
import { FromSchema, JSONSchema } from 'json-schema-to-ts'; import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { NTQQGroupApi, NTQQMsgApi } from '@/core'; import { NTQQGroupApi, NTQQMsgApi } from '@/core';
import { MessageUnique } from '@/common/utils/MessageUnique';
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
@@ -18,13 +18,13 @@ export default class SetEssenceMsg extends BaseAction<Payload, any> {
actionName = ActionName.SetEssenceMsg; actionName = ActionName.SetEssenceMsg;
PayloadSchema = SchemaData; PayloadSchema = SchemaData;
protected async _handle(payload: Payload): Promise<any> { protected async _handle(payload: Payload): Promise<any> {
const msg = await dbUtil.getMsgByShortId(parseInt(payload.message_id.toString())); const msg = await MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString()));
if (!msg) { if (!msg) {
throw new Error('msg not found'); throw new Error('msg not found');
} }
return await NTQQGroupApi.addGroupEssence( return await NTQQGroupApi.addGroupEssence(
msg.peerUin, msg.Peer.peerUid,
msg.msgId msg.MsgId
); );
} }
} }

View File

@@ -1,8 +1,8 @@
import { NTQQMsgApi } from '@/core/apis'; import { NTQQMsgApi } from '@/core/apis';
import { ActionName } from '../types'; import { ActionName } from '../types';
import BaseAction from '../BaseAction'; import BaseAction from '../BaseAction';
import { dbUtil } from '@/common/utils/db';
import { FromSchema, JSONSchema } from 'json-schema-to-ts'; import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { MessageUnique } from '@/common/utils/MessageUnique';
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
@@ -23,9 +23,9 @@ class DeleteMsg extends BaseAction<Payload, void> {
actionName = ActionName.DeleteMsg; actionName = ActionName.DeleteMsg;
PayloadSchema = SchemaData; PayloadSchema = SchemaData;
protected async _handle(payload: Payload) { protected async _handle(payload: Payload) {
const msg = await dbUtil.getMsgByShortId(Number(payload.message_id)); const msg = await MessageUnique.getMsgIdAndPeerByShortId(Number(payload.message_id));
if (msg) { if (msg) {
await NTQQMsgApi.recallMsg({ peerUid: msg.peerUid, chatType: msg.chatType }, [msg.msgId]); await NTQQMsgApi.recallMsg(msg.Peer, [msg.MsgId]);
} }
} }
} }

View File

@@ -1,16 +1,16 @@
import BaseAction from '../BaseAction'; import BaseAction from '../BaseAction';
import { NTQQMsgApi, NTQQUserApi } from '@/core/apis'; import { NTQQMsgApi, NTQQUserApi } from '@/core/apis';
import { ChatType, Peer } from '@/core/entities'; import { ChatType, Peer } from '@/core/entities';
import { dbUtil } from '@/common/utils/db';
import { ActionName } from '../types'; import { ActionName } from '../types';
import { FromSchema, JSONSchema } from 'json-schema-to-ts'; import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { MessageUnique } from '@/common/utils/MessageUnique';
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
properties: { properties: {
message_id: { type: 'number' }, message_id: { type: 'number' },
group_id: { type: [ 'number' , 'string' ] }, group_id: { type: ['number', 'string'] },
user_id: { type: [ 'number' , 'string' ] } user_id: { type: ['number', 'string'] }
}, },
required: ['message_id'] required: ['message_id']
} as const satisfies JSONSchema; } as const satisfies JSONSchema;
@@ -30,18 +30,14 @@ class ForwardSingleMsg extends BaseAction<Payload, null> {
} }
protected async _handle(payload: Payload): Promise<null> { protected async _handle(payload: Payload): Promise<null> {
const msg = await dbUtil.getMsgByShortId(payload.message_id); const msg = await MessageUnique.getMsgIdAndPeerByShortId(payload.message_id);
if (!msg) { if (!msg) {
throw new Error(`无法找到消息${payload.message_id}`); throw new Error(`无法找到消息${payload.message_id}`);
} }
const peer = await this.getTargetPeer(payload); const peer = await this.getTargetPeer(payload);
const ret = await NTQQMsgApi.forwardMsg( const ret = await NTQQMsgApi.forwardMsg(msg.Peer,
{
chatType: msg.chatType,
peerUid: msg.peerUid,
},
peer, peer,
[msg.msgId], [msg.MsgId],
); );
if (ret.result !== 0) { if (ret.result !== 0) {
throw new Error(`转发消息失败 ${ret.errMsg}`); throw new Error(`转发消息失败 ${ret.errMsg}`);

View File

@@ -4,6 +4,8 @@ import BaseAction from '../BaseAction';
import { ActionName } from '../types'; import { ActionName } from '../types';
import { dbUtil } from '@/common/utils/db'; import { dbUtil } from '@/common/utils/db';
import { FromSchema, JSONSchema } from 'json-schema-to-ts'; import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { MessageUnique } from '@/common/utils/MessageUnique';
import { NTQQMsgApi } from '@/core';
export type ReturnDataType = OB11Message export type ReturnDataType = OB11Message
@@ -11,7 +13,7 @@ export type ReturnDataType = OB11Message
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
properties: { properties: {
message_id: { type: ['number','string'] }, message_id: { type: ['number', 'string'] },
}, },
required: ['message_id'] required: ['message_id']
} as const satisfies JSONSchema; } as const satisfies JSONSchema;
@@ -26,14 +28,15 @@ class GetMsg extends BaseAction<Payload, OB11Message> {
if (!payload.message_id) { if (!payload.message_id) {
throw Error('参数message_id不能为空'); throw Error('参数message_id不能为空');
} }
let msg = await dbUtil.getMsgByShortId(parseInt(payload.message_id.toString())); let MsgShortId = await MessageUnique.getShortIdByMsgId(payload.message_id.toString());
if (!msg) { let msgIdWithPeer = await MessageUnique.getMsgIdAndPeerByShortId(MsgShortId || parseInt(payload.message_id.toString()));
msg = await dbUtil.getMsgByLongId(payload.message_id.toString()); if (!msgIdWithPeer) {
}
if (!msg) {
throw ('消息不存在'); throw ('消息不存在');
} }
return await OB11Constructor.message(msg); let msg = await NTQQMsgApi.getMsgsByMsgId(
{ guildId: '', peerUid: msgIdWithPeer?.Peer.peerUid, chatType: msgIdWithPeer.Peer.chatType },
[msgIdWithPeer?.MsgId || payload.message_id.toString()]);
return await OB11Constructor.message(msg.msgList[0]);
} }
} }

View File

@@ -7,6 +7,7 @@ import { logDebug, logError } from '@/common/utils/log';
import { sleep } from '@/common/utils/helper'; import { sleep } from '@/common/utils/helper';
import fs from 'node:fs'; import fs from 'node:fs';
import { normalize, sendMsg } from '@/onebot11/action/msg/SendMsg/index'; import { normalize, sendMsg } from '@/onebot11/action/msg/SendMsg/index';
import { MessageUnique } from '@/common/utils/MessageUnique';
async function cloneMsg(msg: RawMessage): Promise<RawMessage | undefined> { async function cloneMsg(msg: RawMessage): Promise<RawMessage | undefined> {
const selfPeer = { const selfPeer = {
@@ -54,13 +55,14 @@ export async function handleForwardNode(destPeer: Peer, messageNodes: OB11Messag
const nodeId = messageNode.data.id; const nodeId = messageNode.data.id;
// 有nodeId表示一个子转发消息卡片 // 有nodeId表示一个子转发消息卡片
if (nodeId) { if (nodeId) {
const nodeMsg = await dbUtil.getMsgByShortId(parseInt(nodeId)); const nodeMsg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(nodeId));
if (!needClone) { if (!needClone) {
nodeMsgIds.push(nodeMsg!.msgId); nodeMsgIds.push(nodeMsg!.MsgId);
} else { } else {
if (nodeMsg!.peerUid !== selfInfo.uid) { if (nodeMsg!.Peer.peerUid !== selfInfo.uid) {
// need cloning // need cloning
const clonedMsg = await cloneMsg(nodeMsg!); let rawClone = await NTQQMsgApi.getMsgsByMsgId(nodeMsg?.Peer!,[nodeMsg?.MsgId!]);
const clonedMsg = await cloneMsg(rawClone.msgList[0]);
if (clonedMsg) { if (clonedMsg) {
nodeMsgIds.push(clonedMsg.msgId); nodeMsgIds.push(clonedMsg.msgId);
} }

View File

@@ -8,13 +8,13 @@ import {
} from '@/onebot11/types'; } from '@/onebot11/types';
import { ActionName, BaseCheckResult } from '@/onebot11/action/types'; import { ActionName, BaseCheckResult } from '@/onebot11/action/types';
import { getGroup } from '@/core/data'; import { getGroup } from '@/core/data';
import { dbUtil } from '@/common/utils/db';
import { ChatType, ElementType, Group, NTQQFileApi, NTQQFriendApi, NTQQMsgApi, NTQQUserApi, Peer, SendMessageElement, } from '@/core'; import { ChatType, ElementType, Group, NTQQFileApi, NTQQFriendApi, NTQQMsgApi, NTQQUserApi, Peer, SendMessageElement, } from '@/core';
import fs from 'node:fs'; import fs from 'node:fs';
import { logDebug, logError } from '@/common/utils/log'; import { logDebug, logError } from '@/common/utils/log';
import { decodeCQCode } from '@/onebot11/cqcode'; import { decodeCQCode } from '@/onebot11/cqcode';
import createSendElements from './create-send-elements'; import createSendElements from './create-send-elements';
import { handleForwardNode } from '@/onebot11/action/msg/SendMsg/handle-forward-node'; import { handleForwardNode } from '@/onebot11/action/msg/SendMsg/handle-forward-node';
import { MessageUnique } from '@/common/utils/MessageUnique';
export interface ReturnDataType { export interface ReturnDataType {
message_id: number; message_id: number;
@@ -66,7 +66,7 @@ export async function sendMsg(peer: Peer, sendElements: SendMessageElement[], de
} }
const returnMsg = await NTQQMsgApi.sendMsg(peer, sendElements, waitComplete, timeout); const returnMsg = await NTQQMsgApi.sendMsg(peer, sendElements, waitComplete, timeout);
try { try {
returnMsg.id = await dbUtil.addMsg(returnMsg, false); returnMsg.id = await MessageUnique.createMsg({ chatType: peer.chatType, guildId: '', peerUid: peer.peerUid }, returnMsg.msgId);
} catch (e: any) { } catch (e: any) {
logDebug('发送消息id获取失败', e); logDebug('发送消息id获取失败', e);
returnMsg.id = 0; returnMsg.id = 0;
@@ -155,8 +155,8 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
if (getSpecialMsgNum(payload, OB11MessageDataType.node)) { if (getSpecialMsgNum(payload, OB11MessageDataType.node)) {
const returnMsg = await handleForwardNode(peer, messages as OB11MessageNode[], group); const returnMsg = await handleForwardNode(peer, messages as OB11MessageNode[], group);
if (returnMsg) { if (returnMsg) {
const msgShortId = await dbUtil.addMsg(returnMsg!, false); const msgShortId = await MessageUnique.createMsg({ guildId: '', peerUid: peer.peerUid, chatType: peer.chatType }, returnMsg!.msgId);
return { message_id: msgShortId }; return { message_id: msgShortId! };
} else { } else {
throw Error('发送转发消息失败'); throw Error('发送转发消息失败');
} }

View File

@@ -1,8 +1,8 @@
import { ActionName } from '../types'; import { ActionName } from '../types';
import BaseAction from '../BaseAction'; import BaseAction from '../BaseAction';
import { dbUtil } from '@/common/utils/db';
import { NTQQMsgApi } from '@/core/apis'; import { NTQQMsgApi } from '@/core/apis';
import { FromSchema, JSONSchema } from 'json-schema-to-ts'; import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { MessageUnique } from '@/common/utils/MessageUnique';
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
@@ -19,16 +19,14 @@ export class SetMsgEmojiLike extends BaseAction<Payload, any> {
actionName = ActionName.SetMsgEmojiLike; actionName = ActionName.SetMsgEmojiLike;
PayloadSchema = SchemaData; PayloadSchema = SchemaData;
protected async _handle(payload: Payload) { protected async _handle(payload: Payload) {
const msg = await dbUtil.getMsgByShortId(parseInt(payload.message_id.toString())); const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString()));
if (!msg) { if (!msg) {
throw new Error('msg not found'); throw new Error('msg not found');
} }
if (!payload.emoji_id){ if (!payload.emoji_id){
throw new Error('emojiId not found'); throw new Error('emojiId not found');
} }
return await NTQQMsgApi.setEmojiLike({ let msgSeq = (await NTQQMsgApi.getMsgsByMsgId(msg.Peer, [msg.MsgId])).msgList[0].msgSeq;
chatType: msg.chatType, return await NTQQMsgApi.setEmojiLike(msg.Peer, msgSeq, payload.emoji_id.toString(), true);
peerUid: msg.peerUid
}, msg.msgSeq, payload.emoji_id.toString(), true);
} }
} }

View File

@@ -47,6 +47,7 @@ import { napCatCore } from '@/core';
import { OB11FriendPokeEvent, OB11GroupPokeEvent } from './event/notice/OB11PokeEvent'; import { OB11FriendPokeEvent, OB11GroupPokeEvent } from './event/notice/OB11PokeEvent';
import { OB11BaseNoticeEvent } from './event/notice/OB11BaseNoticeEvent'; import { OB11BaseNoticeEvent } from './event/notice/OB11BaseNoticeEvent';
import { OB11GroupEssenceEvent } from './event/notice/OB11GroupEssenceEvent'; import { OB11GroupEssenceEvent } from './event/notice/OB11GroupEssenceEvent';
import { MessageUnique } from '@/common/utils/MessageUnique';
export class OB11Constructor { export class OB11Constructor {
@@ -408,11 +409,12 @@ export class OB11Constructor {
const senderUin = emojiLikeData.gtip.qq.jp; const senderUin = emojiLikeData.gtip.qq.jp;
const msgSeq = emojiLikeData.gtip.url.msgseq; const msgSeq = emojiLikeData.gtip.url.msgseq;
const emojiId = emojiLikeData.gtip.face.id; const emojiId = emojiLikeData.gtip.face.id;
let msgList = (await NTQQMsgApi.getMsgsBySeqAndCount({ chatType: ChatType.group, guildId: '', peerUid: msg.peerUid }, msgSeq, 1, true, true)).msgList;
const replyMsg = await dbUtil.getMsgBySeq(msg.peerUid, msgSeq); const replyMsg = await dbUtil.getMsgBySeq(msg.peerUid, msgSeq);
if (!replyMsg) { if (msgList.length < 1) {
return; return;
} }
return new OB11GroupMsgEmojiLikeEvent(parseInt(msg.peerUid), parseInt(senderUin), replyMsg.id!, [{ return new OB11GroupMsgEmojiLikeEvent(parseInt(msg.peerUid), parseInt(senderUin), MessageUnique.getShortIdByMsgId(replyMsg?.msgId!)!, [{
emoji_id: emojiId, emoji_id: emojiId,
count: 1 count: 1
}]); }]);
@@ -463,7 +465,7 @@ export class OB11Constructor {
peerUid: Group! peerUid: Group!
}; };
let msgData = await NTQQMsgApi.getMsgsBySeqAndCount(Peer, msgSeq.toString(), 1, true, true); let msgData = await NTQQMsgApi.getMsgsBySeqAndCount(Peer, msgSeq.toString(), 1, true, true);
return new OB11GroupEssenceEvent(parseInt(msg.peerUid), await dbUtil.addMsg(msgData.msgList[0]), parseInt(msgData.msgList[0].senderUin)); return new OB11GroupEssenceEvent(parseInt(msg.peerUid), MessageUnique.getShortIdByMsgId(msgData.msgList[0].msgId)!, parseInt(msgData.msgList[0].senderUin));
// 获取MsgSeq+Peer可获取具体消息 // 获取MsgSeq+Peer可获取具体消息
} }
if (grayTipElement.jsonGrayTipElement.busiId == 2407) { if (grayTipElement.jsonGrayTipElement.busiId == 2407) {

View File

@@ -13,8 +13,5 @@ export class OB11GroupIncreaseEvent extends OB11GroupNoticeEvent {
this.operator_id = operatorId; this.operator_id = operatorId;
this.user_id = userId; this.user_id = userId;
this.sub_type = subType; this.sub_type = subType;
if(ob11Config.GroupLocalTime.Record && (ob11Config.GroupLocalTime.RecordList[0] == '-1' || ob11Config.GroupLocalTime.RecordList.includes(groupId.toString())))
dbUtil.insertJoinTime(groupId, userId, Math.floor(Date.now() / 1000));
} }
} }

View File

@@ -37,6 +37,7 @@ import { Data as SysData } from '@/proto/SysMessage';
import { Data as DeviceData } from '@/proto/SysMessage.DeviceChange'; import { Data as DeviceData } from '@/proto/SysMessage.DeviceChange';
import { OB11FriendPokeEvent, OB11GroupPokeEvent } from './event/notice/OB11PokeEvent'; import { OB11FriendPokeEvent, OB11GroupPokeEvent } from './event/notice/OB11PokeEvent';
import { isEqual } from '@/common/utils/helper'; import { isEqual } from '@/common/utils/helper';
import { MessageUnique } from '@/common/utils/MessageUnique';
//下面几个其实应该移进Core-Data 缓存实现 但是现在在这里方便 //下面几个其实应该移进Core-Data 缓存实现 但是现在在这里方便
// //
@@ -229,10 +230,8 @@ export class NapCatOnebot11 {
// }); // });
// console.log(ret); // console.log(ret);
new Promise((resolve) => { new Promise((resolve) => {
dbUtil.addMsg(m).then(msgShortId => { m.id = MessageUnique.createMsg({ chatType: m.chatType, peerUid: m.peerUid, guildId: '' }, m.msgId);
m.id = msgShortId;
this.postReceiveMsg([m]).then().catch(logError); this.postReceiveMsg([m]).then().catch(logError);
}).catch(logError);
}).then(); }).then();
} }
}; };
@@ -245,10 +244,8 @@ export class NapCatOnebot11 {
logMessage(_msg as OB11Message).then().catch(logError); logMessage(_msg as OB11Message).then().catch(logError);
}).catch(logError); }).catch(logError);
if (ob11Config.reportSelfMessage) { if (ob11Config.reportSelfMessage) {
dbUtil.addMsg(msg).then(id => { msg.id = MessageUnique.createMsg({ chatType: msg.chatType, peerUid: msg.peerUid, guildId: '' }, msg.msgId);
msg.id = id;
this.postReceiveMsg([msg]).then().catch(logError); this.postReceiveMsg([msg]).then().catch(logError);
});
} }
}; };
napCatCore.addListener(msgListener); napCatCore.addListener(msgListener);
@@ -349,10 +346,6 @@ export class NapCatOnebot11 {
} }
if (msg.post_type === 'message') { if (msg.post_type === 'message') {
logMessage(msg as OB11Message).then().catch(logError); logMessage(msg as OB11Message).then().catch(logError);
// 大概测试了一下10000个以内 includes 和 find 性能差距不大
if (msg.message_type == 'group' && msg.group_id && ob11Config.GroupLocalTime.Record && (ob11Config.GroupLocalTime.RecordList[0] === '-1' || ob11Config.GroupLocalTime.RecordList.find(gid => gid == msg.group_id?.toString()))) {
dbUtil.insertLastSentTime(msg.group_id, msg.user_id, msg.time);
}
} else if (msg.post_type === 'notice') { } else if (msg.post_type === 'notice') {
logNotice(msg).then().catch(logError); logNotice(msg).then().catch(logError);
} else if (msg.post_type === 'request') { } else if (msg.post_type === 'request') {
@@ -534,12 +527,12 @@ export class NapCatOnebot11 {
// log("message update", message.sendStatus, message.msgId, message.msgSeq) // log("message update", message.sendStatus, message.msgId, message.msgSeq)
if (message.recallTime != '0') { //todo: 这个判断方法不太好,应该使用灰色消息元素来判断? if (message.recallTime != '0') { //todo: 这个判断方法不太好,应该使用灰色消息元素来判断?
// 撤回消息上报 // 撤回消息上报
const oriMessage = await dbUtil.getMsgByLongId(message.msgId); const oriMessageId = await MessageUnique.getShortIdByMsgId(message.msgId);
if (!oriMessage) { if (!oriMessageId) {
continue; continue;
} }
if (message.chatType == ChatType.friend) { if (message.chatType == ChatType.friend) {
const friendRecallEvent = new OB11FriendRecallNoticeEvent(parseInt(message!.senderUin), oriMessage!.id!); const friendRecallEvent = new OB11FriendRecallNoticeEvent(parseInt(message!.senderUin), oriMessageId);
postOB11Event(friendRecallEvent); postOB11Event(friendRecallEvent);
} else if (message.chatType == ChatType.group) { } else if (message.chatType == ChatType.group) {
let operatorId = message.senderUin; let operatorId = message.senderUin;
@@ -552,7 +545,7 @@ export class NapCatOnebot11 {
parseInt(message.peerUin), parseInt(message.peerUin),
parseInt(message.senderUin), parseInt(message.senderUin),
parseInt(operatorId), parseInt(operatorId),
oriMessage.id! oriMessageId
); );
postOB11Event(groupRecallEvent); postOB11Event(groupRecallEvent);
} }

View File

@@ -125,7 +125,6 @@ export function postOB11Event(msg: QuickActionEvent, reportSelf = false, postWs
} }
async function handleMsg(msg: OB11Message, quickAction: QuickAction) { async function handleMsg(msg: OB11Message, quickAction: QuickAction) {
msg = msg as OB11Message; msg = msg as OB11Message;
const rawMessage = await dbUtil.getMsgByShortId(msg.message_id);
const reply = quickAction.reply; const reply = quickAction.reply;
const peer: Peer = { const peer: Peer = {
chatType: ChatType.friend, chatType: ChatType.friend,