fix: report non-latest private message recalls (#1998)
This commit is contained in:
1 parent
ead24423b5
commit
56549cd0f2
2 files changed
+416
-23
No files matched your search
+107
-23
@@ -65,6 +65,10 @@ interface ApiListType {
|
||||
QuickActionApi: OneBotQuickActionApi;
|
||||
FileApi: OneBotFileApi;
|
||||
}
|
||||
|
||||
const RECALL_EVENT_DEDUP_MAX_SIZE = 1_000;
|
||||
const RECALL_UPDATE_CLOCK_SKEW_SECONDS = 30;
|
||||
|
||||
// OneBot实现类
|
||||
export class NapCatOneBot11Adapter {
|
||||
readonly core: NapCatCore;
|
||||
@@ -76,6 +80,8 @@ export class NapCatOneBot11Adapter {
|
||||
actions: ActionMap;
|
||||
private readonly bootTime = Date.now() / 1000;
|
||||
recallEventCache = new Map<string, NodeJS.Timeout>();
|
||||
private readonly reportedRecallEventCache = new Map<string, true>();
|
||||
private readonly processingRecallEvents = new Map<string, Promise<void>>();
|
||||
constructor (core: NapCatCore, context: InstanceContext, pathWrapper: NapCatPathWrapper) {
|
||||
this.core = core;
|
||||
this.context = context;
|
||||
@@ -384,36 +390,34 @@ export class NapCatOneBot11Adapter {
|
||||
this.context.logger.logError('处理发送消息失败', error);
|
||||
}
|
||||
};
|
||||
|
||||
msgListener.onMsgInfoListUpdate = async (msgList: RawMessage[]) => {
|
||||
for (const msg of msgList) {
|
||||
const element = this.getRecallElement(msg);
|
||||
if (element && this.isCurrentRecallUpdate(msg)) {
|
||||
// The gray-tip update is authoritative; the recall callback's sequence query can return a newer message.
|
||||
await this.handleRecallMessage(msg, element);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
msgListener.onMsgRecall = async (chatType: ChatType, uid: string, msgSeq: string) => {
|
||||
const peer: Peer = {
|
||||
chatType,
|
||||
peerUid: uid,
|
||||
guildId: '',
|
||||
};
|
||||
let msg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, msgSeq)).msgList.find(e => e.msgType === NTMsgType.KMSGTYPEGRAYTIPS);
|
||||
const element = msg?.elements.find(e => !!e.grayTipElement?.revokeElement);
|
||||
if (msg && element?.grayTipElement?.revokeElement.isSelfOperate) {
|
||||
const isSelfDevice = this.recallEventCache.has(msg.msgId);
|
||||
if (isSelfDevice) {
|
||||
await this.core.eventWrapper.registerListen('NodeIKernelMsgListener/onMsgRecall',
|
||||
(chatType: ChatType, uid: string, msgSeq: string) => {
|
||||
return chatType === msg?.chatType && uid === msg?.peerUid && msgSeq === msg?.msgSeq;
|
||||
}
|
||||
).catch(() => {
|
||||
msg = undefined;
|
||||
this.context.logger.logDebug('自操作消息撤回事件');
|
||||
});
|
||||
}
|
||||
}
|
||||
if (msg && element) {
|
||||
const recallEvent = await this.emitRecallMsg(msg, element);
|
||||
try {
|
||||
if (recallEvent) {
|
||||
await this.networkManager.emitEvent(recallEvent);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('处理消息撤回失败', e);
|
||||
try {
|
||||
const msg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, msgSeq)).msgList
|
||||
.find(message => this.getRecallElement(message));
|
||||
const element = msg && this.getRecallElement(msg);
|
||||
if (msg && element) {
|
||||
await this.handleRecallMessage(msg, element);
|
||||
} else {
|
||||
this.context.logger.logDebug(`撤回回调暂未查询到灰条消息,等待消息更新: ${chatType}/${uid}/${msgSeq}`);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('查询撤回消息失败', e);
|
||||
}
|
||||
};
|
||||
msgListener.onKickedOffLine = async (kick) => {
|
||||
@@ -662,6 +666,86 @@ export class NapCatOneBot11Adapter {
|
||||
}
|
||||
}
|
||||
|
||||
private getRecallElement (message: RawMessage): MessageElement | undefined {
|
||||
if (message.msgType !== NTMsgType.KMSGTYPEGRAYTIPS) {
|
||||
return undefined;
|
||||
}
|
||||
return message.elements.find(element => !!element.grayTipElement?.revokeElement);
|
||||
}
|
||||
|
||||
private isCurrentRecallUpdate (message: RawMessage): boolean {
|
||||
const recallTime = Number(message.recallTime);
|
||||
if (!Number.isFinite(recallTime) || recallTime <= 0) {
|
||||
return false;
|
||||
}
|
||||
const recallTimeInSeconds = recallTime > 10_000_000_000 ? recallTime / 1000 : recallTime;
|
||||
return recallTimeInSeconds >= this.bootTime - RECALL_UPDATE_CLOCK_SKEW_SECONDS;
|
||||
}
|
||||
|
||||
private getRecallEventKey (message: RawMessage): string {
|
||||
return `${message.chatType}/${message.peerUid}/${message.msgId}`;
|
||||
}
|
||||
|
||||
private hasReportedRecallEvent (key: string): boolean {
|
||||
return this.reportedRecallEventCache.has(key);
|
||||
}
|
||||
|
||||
private markRecallEventReported (key: string): void {
|
||||
this.reportedRecallEventCache.delete(key);
|
||||
this.reportedRecallEventCache.set(key, true);
|
||||
while (this.reportedRecallEventCache.size > RECALL_EVENT_DEDUP_MAX_SIZE) {
|
||||
const oldestKey = this.reportedRecallEventCache.keys().next().value;
|
||||
if (oldestKey === undefined) break;
|
||||
this.reportedRecallEventCache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleRecallMessage (message: RawMessage, element: MessageElement): Promise<void> {
|
||||
const revokeElement = element.grayTipElement?.revokeElement;
|
||||
if (!revokeElement) return;
|
||||
|
||||
if (revokeElement.isSelfOperate) {
|
||||
const selfRecallTimeout = this.recallEventCache.get(message.msgId);
|
||||
if (selfRecallTimeout) {
|
||||
clearTimeout(selfRecallTimeout);
|
||||
this.recallEventCache.delete(message.msgId);
|
||||
this.context.logger.logDebug('自操作消息撤回事件');
|
||||
}
|
||||
}
|
||||
|
||||
const key = this.getRecallEventKey(message);
|
||||
while (!this.hasReportedRecallEvent(key)) {
|
||||
const processing = this.processingRecallEvents.get(key);
|
||||
if (processing) {
|
||||
// A duplicate callback becomes the retry path if the in-flight report fails.
|
||||
await processing;
|
||||
continue;
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
try {
|
||||
const recallEvent = await this.emitRecallMsg(message, element);
|
||||
if (recallEvent) {
|
||||
await this.networkManager.emitEvent(recallEvent);
|
||||
this.markRecallEventReported(key);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('处理消息撤回失败', e);
|
||||
}
|
||||
})();
|
||||
|
||||
this.processingRecallEvents.set(key, task);
|
||||
try {
|
||||
await task;
|
||||
} finally {
|
||||
if (this.processingRecallEvents.get(key) === task) {
|
||||
this.processingRecallEvents.delete(key);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private async emitRecallMsg (message: RawMessage, element: MessageElement) {
|
||||
const peer: Peer = { chatType: message.chatType, peerUid: message.peerUid, guildId: '' };
|
||||
const oriMessageId = MessageUnique.getShortIdByMsgId(message.msgId) ?? MessageUnique.createUniqueMsgId(peer, message.msgId);
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
import { describe, expect, test, vi } from 'vitest';
|
||||
import { ChatType, NTMsgType, type RawMessage } from 'napcat-core';
|
||||
import { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
|
||||
|
||||
vi.mock('../napcat-webui-backend/index', () => ({
|
||||
pendingTokenToSend: undefined,
|
||||
}));
|
||||
|
||||
vi.mock('../napcat-webui-backend/src/helper/Data', () => ({
|
||||
WebUiDataRuntime: {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/config', () => ({
|
||||
OB11ConfigLoader: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/network', () => ({
|
||||
OB11HttpClientAdapter: class {},
|
||||
OB11WebSocketClientAdapter: class {},
|
||||
OB11NetworkManager: class {},
|
||||
OB11NetworkReloadType: {},
|
||||
OB11HttpServerAdapter: class {},
|
||||
OB11WebSocketServerAdapter: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/api', () => ({
|
||||
OneBotFriendApi: class {},
|
||||
OneBotGroupApi: class {},
|
||||
OneBotMsgApi: class {},
|
||||
OneBotQuickActionApi: class {},
|
||||
OneBotUserApi: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/action', () => ({
|
||||
createActionMap: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/network/adapter', () => ({
|
||||
IOB11NetworkAdapter: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/network/http-server-sse', () => ({
|
||||
OB11HttpSSEServerAdapter: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/network/plugin-manger', () => ({
|
||||
OB11PluginMangerAdapter: class {},
|
||||
}));
|
||||
|
||||
vi.mock('@/napcat-onebot/api/file', () => ({
|
||||
OneBotFileApi: class {},
|
||||
}));
|
||||
|
||||
interface TestMsgListener {
|
||||
onMsgRecall (chatType: ChatType, uid: string, msgSeq: string): Promise<void> | void;
|
||||
onMsgInfoListUpdate (messages: RawMessage[]): Promise<void> | void;
|
||||
}
|
||||
|
||||
const friendUid = 'u_friend';
|
||||
const friendUin = '123456';
|
||||
const recalledMsgId = 'recalled-message-id';
|
||||
const recalledMsgSeq = '100';
|
||||
const botUin = '999999';
|
||||
|
||||
function createMessage (overrides: Partial<RawMessage>): RawMessage {
|
||||
return {
|
||||
msgId: 'message-id',
|
||||
msgRandom: '1',
|
||||
msgSeq: '101',
|
||||
cntSeq: '101',
|
||||
chatType: ChatType.KCHATTYPEC2C,
|
||||
msgType: NTMsgType.KMSGTYPEUNKNOWN,
|
||||
subMsgType: 0,
|
||||
sendStatus: 2,
|
||||
senderUid: friendUid,
|
||||
senderUin: friendUin,
|
||||
peerUid: friendUid,
|
||||
peerUin: friendUin,
|
||||
peerName: 'friend',
|
||||
sendNickName: 'friend',
|
||||
sendRemarkName: 'friend',
|
||||
msgTime: '1',
|
||||
recallTime: '0',
|
||||
elements: [],
|
||||
records: [],
|
||||
sourceType: 0,
|
||||
isOnlineMsg: true,
|
||||
...overrides,
|
||||
} as RawMessage;
|
||||
}
|
||||
|
||||
function createRecallGrayTip (): RawMessage {
|
||||
return createMessage({
|
||||
msgId: recalledMsgId,
|
||||
msgSeq: recalledMsgSeq,
|
||||
msgType: NTMsgType.KMSGTYPEGRAYTIPS,
|
||||
recallTime: Math.floor(Date.now() / 1000).toString(),
|
||||
elements: [{
|
||||
elementType: 8,
|
||||
elementId: 'recall-element',
|
||||
grayTipElement: {
|
||||
revokeElement: {
|
||||
operatorRole: '0',
|
||||
operatorUid: friendUid,
|
||||
operatorNick: 'friend',
|
||||
operatorRemark: '',
|
||||
isSelfOperate: false,
|
||||
wording: '',
|
||||
},
|
||||
},
|
||||
} as unknown as RawMessage['elements'][number]],
|
||||
});
|
||||
}
|
||||
|
||||
function createHarness (queryResult: RawMessage[], operatorUin = '654321') {
|
||||
let listener: TestMsgListener | undefined;
|
||||
const emitEvent = vi.fn(async (_event: unknown): Promise<void> => undefined);
|
||||
const queryMsgsWithFilterExWithSeq = vi.fn(async () => ({ msgList: queryResult }));
|
||||
const registerListen = vi.fn();
|
||||
const logger = {
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logMessage: vi.fn(),
|
||||
};
|
||||
const context = {
|
||||
logger,
|
||||
session: {
|
||||
getMsgService: () => ({
|
||||
addKernelMsgListener: (registeredListener: TestMsgListener) => {
|
||||
listener = registeredListener;
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
const core = {
|
||||
selfInfo: { uin: botUin },
|
||||
apis: {
|
||||
MsgApi: { queryMsgsWithFilterExWithSeq },
|
||||
UserApi: { getUinByUidV2: vi.fn(async () => operatorUin) },
|
||||
},
|
||||
eventWrapper: { registerListen },
|
||||
};
|
||||
const adapter = Object.create(NapCatOneBot11Adapter.prototype) as NapCatOneBot11Adapter;
|
||||
|
||||
Object.assign(adapter, {
|
||||
core,
|
||||
context,
|
||||
networkManager: { emitEvent },
|
||||
bootTime: Date.now() / 1000,
|
||||
recallEventCache: new Map(),
|
||||
reportedRecallEventCache: new Map(),
|
||||
processingRecallEvents: new Map(),
|
||||
});
|
||||
|
||||
(adapter as unknown as { initMsgListener (): void }).initMsgListener();
|
||||
|
||||
if (!listener) {
|
||||
throw new Error('message listener was not registered');
|
||||
}
|
||||
|
||||
return { adapter, listener, emitEvent, logger, queryMsgsWithFilterExWithSeq, registerListen };
|
||||
}
|
||||
|
||||
describe('friend recall reporting', () => {
|
||||
test('reports a recalled non-latest private message from its gray-tip update', async () => {
|
||||
const botReply = createMessage({
|
||||
msgId: 'bot-reply-id',
|
||||
msgSeq: '101',
|
||||
senderUid: 'u_bot',
|
||||
senderUin: botUin,
|
||||
});
|
||||
const grayTip = createRecallGrayTip();
|
||||
const { listener, emitEvent } = createHarness([botReply]);
|
||||
|
||||
await listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(1);
|
||||
expect(emitEvent).toHaveBeenCalledWith(expect.objectContaining({
|
||||
notice_type: 'friend_recall',
|
||||
user_id: Number(friendUin),
|
||||
}));
|
||||
});
|
||||
|
||||
test('deduplicates the same recall from the gray-tip update and recall callback', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
const { listener, emitEvent } = createHarness([grayTip]);
|
||||
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
await listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('deduplicates concurrent update and callback processing', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
const { listener, emitEvent } = createHarness([grayTip]);
|
||||
let finishEmit: (() => void) | undefined;
|
||||
emitEvent.mockImplementationOnce(() => new Promise<void>((resolve) => {
|
||||
finishEmit = resolve;
|
||||
}));
|
||||
|
||||
const updateTask = listener.onMsgInfoListUpdate([grayTip]);
|
||||
await vi.waitFor(() => expect(emitEvent).toHaveBeenCalledTimes(1));
|
||||
const callbackTask = listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
|
||||
|
||||
finishEmit?.();
|
||||
await Promise.all([updateTask, callbackTask]);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('uses a concurrent duplicate callback to retry a failed report', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
const { listener, emitEvent, logger } = createHarness([grayTip]);
|
||||
let failFirstEmit: (() => void) | undefined;
|
||||
emitEvent
|
||||
.mockImplementationOnce(() => new Promise<void>((_resolve, reject) => {
|
||||
failFirstEmit = () => reject(new Error('network unavailable'));
|
||||
}))
|
||||
.mockResolvedValueOnce(undefined);
|
||||
|
||||
const updateTask = listener.onMsgInfoListUpdate([grayTip]);
|
||||
await vi.waitFor(() => expect(emitEvent).toHaveBeenCalledTimes(1));
|
||||
const callbackTask = listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
|
||||
|
||||
failFirstEmit?.();
|
||||
await Promise.all([updateTask, callbackTask]);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(2);
|
||||
expect(logger.logError).toHaveBeenCalledWith('处理消息撤回失败', expect.any(Error));
|
||||
});
|
||||
|
||||
test('reports one self recall without waiting for a duplicate callback', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
const revokeElement = grayTip.elements[0]?.grayTipElement?.revokeElement;
|
||||
if (!revokeElement) throw new Error('missing revoke element');
|
||||
revokeElement.isSelfOperate = true;
|
||||
|
||||
const { adapter, listener, emitEvent, registerListen } = createHarness([grayTip]);
|
||||
const originTimeout = setTimeout(() => undefined, 60_000);
|
||||
adapter.recallEventCache.set(recalledMsgId, originTimeout);
|
||||
|
||||
await listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
|
||||
await listener.onMsgRecall(ChatType.KCHATTYPEC2C, friendUid, recalledMsgSeq);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(1);
|
||||
expect(adapter.recallEventCache.has(recalledMsgId)).toBe(false);
|
||||
expect(registerListen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('retries reporting when the first network emission fails', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
const { listener, emitEvent, logger } = createHarness([grayTip]);
|
||||
emitEvent
|
||||
.mockRejectedValueOnce(new Error('network unavailable'))
|
||||
.mockResolvedValueOnce(undefined);
|
||||
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(2);
|
||||
expect(logger.logError).toHaveBeenCalledWith('处理消息撤回失败', expect.any(Error));
|
||||
});
|
||||
|
||||
test('ignores historical recall rows replayed during startup sync', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
grayTip.recallTime = Math.floor(Date.now() / 1000 - 120).toString();
|
||||
const { listener, emitEvent } = createHarness([]);
|
||||
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
|
||||
expect(emitEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('ignores ordinary message updates', async () => {
|
||||
const ordinaryMessage = createMessage({ recallTime: Math.floor(Date.now() / 1000).toString() });
|
||||
const { listener, emitEvent } = createHarness([]);
|
||||
|
||||
await listener.onMsgInfoListUpdate([ordinaryMessage]);
|
||||
|
||||
expect(emitEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('group recall reporting', () => {
|
||||
test('preserves group, sender and operator fields', async () => {
|
||||
const grayTip = createRecallGrayTip();
|
||||
const groupUin = '112233';
|
||||
const senderUin = '223344';
|
||||
grayTip.chatType = ChatType.KCHATTYPEGROUP;
|
||||
grayTip.peerUid = groupUin;
|
||||
grayTip.peerUin = groupUin;
|
||||
grayTip.senderUin = senderUin;
|
||||
|
||||
const { listener, emitEvent } = createHarness([], '334455');
|
||||
|
||||
await listener.onMsgInfoListUpdate([grayTip]);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(1);
|
||||
expect(emitEvent).toHaveBeenCalledWith(expect.objectContaining({
|
||||
notice_type: 'group_recall',
|
||||
group_id: Number(groupUin),
|
||||
user_id: Number(senderUin),
|
||||
operator_id: 334455,
|
||||
}));
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user