fix(onebot): disambiguate same-second private replies
Carry quoted text into receipt lookup and require a unique content match when several outgoing messages share a timestamp. Preserve sequence matches and log unresolved ambiguity. Fixes #502
This commit is contained in:
7 files changed
+100
-12
No files matched your search
@@ -228,6 +228,7 @@ export const ELEMENT_CODECS = {
|
|||||||
element.replyTime && element.replyTime > 0
|
element.replyTime && element.replyTime > 0
|
||||||
? element.replyTime
|
? element.replyTime
|
||||||
: Number.MAX_SAFE_INTEGER,
|
: Number.MAX_SAFE_INTEGER,
|
||||||
|
element.replyElements,
|
||||||
);
|
);
|
||||||
return { type: 'reply', data: { id: String(id) } };
|
return { type: 'reply', data: { id: String(id) } };
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ export type MessageIdResolver = (
|
|||||||
sequence: number,
|
sequence: number,
|
||||||
eventName: string,
|
eventName: string,
|
||||||
timestamp?: number,
|
timestamp?: number,
|
||||||
|
replyElements?: readonly MessageElement[],
|
||||||
) => number;
|
) => number;
|
||||||
|
|
||||||
export type MediaSegmentSink = (
|
export type MediaSegmentSink = (
|
||||||
@@ -120,4 +121,3 @@ export async function convertEvent(
|
|||||||
return (converter as (ctx: ConverterContext, event: QQEventVariant) => JsonObject | Promise<JsonObject>)(ctx, event);
|
return (converter as (ctx: ConverterContext, event: QQEventVariant) => JsonObject | Promise<JsonObject>)(ctx, event);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
|
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
|
||||||
import type { MessageIdResolver } from './index';
|
import type { MessageIdResolver } from './index';
|
||||||
|
import type { MessageElement } from '@snowluma/protocol/events';
|
||||||
|
|
||||||
export function parseSelfId(instanceUin: string): number {
|
export function parseSelfId(instanceUin: string): number {
|
||||||
const parsed = Number.parseInt(instanceUin, 10);
|
const parsed = Number.parseInt(instanceUin, 10);
|
||||||
@@ -39,12 +40,13 @@ export function resolveReplyId(
|
|||||||
resolver?: MessageIdResolver | null,
|
resolver?: MessageIdResolver | null,
|
||||||
eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT,
|
eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT,
|
||||||
timestamp?: number,
|
timestamp?: number,
|
||||||
|
replyElements?: readonly MessageElement[],
|
||||||
): number {
|
): number {
|
||||||
const seq = Math.trunc(sequence);
|
const seq = Math.trunc(sequence);
|
||||||
if (seq === 0) return 0;
|
if (seq === 0) return 0;
|
||||||
|
|
||||||
if (resolver) {
|
if (resolver) {
|
||||||
const resolved = resolver(isGroup, sessionId, seq, eventName, timestamp);
|
const resolved = resolver(isGroup, sessionId, seq, eventName, timestamp, replyElements);
|
||||||
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
|
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -143,7 +143,7 @@ export class OneBotInstance {
|
|||||||
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
|
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
|
||||||
mediaUrlResolver: (element, isGroup, sessionId) =>
|
mediaUrlResolver: (element, isGroup, sessionId) =>
|
||||||
mediaUrlResolver.resolve(element, isGroup, sessionId),
|
mediaUrlResolver.resolve(element, isGroup, sessionId),
|
||||||
messageIdResolver: (isGroup, sessionId, sequence, eventName, timestamp) => {
|
messageIdResolver: (isGroup, sessionId, sequence, eventName, timestamp, replyElements) => {
|
||||||
const resolvedEventName = eventName
|
const resolvedEventName = eventName
|
||||||
|| (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT);
|
|| (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT);
|
||||||
if (!isGroup
|
if (!isGroup
|
||||||
@@ -155,6 +155,7 @@ export class OneBotInstance {
|
|||||||
sequence,
|
sequence,
|
||||||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
|
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
|
||||||
timestamp,
|
timestamp,
|
||||||
|
replyElements,
|
||||||
);
|
);
|
||||||
if (storedId !== null) return storedId;
|
if (storedId !== null) return storedId;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||||
import { createLogger } from '@snowluma/common/logger';
|
import { createLogger } from '@snowluma/common/logger';
|
||||||
import type { JsonObject, MessageMeta } from './types';
|
import type { JsonObject, MessageMeta } from './types';
|
||||||
|
import type { MessageElement } from '@snowluma/protocol/events';
|
||||||
|
import { cqUnescape } from './helper/cq';
|
||||||
import { openSqliteDb } from './sqlite-open';
|
import { openSqliteDb } from './sqlite-open';
|
||||||
import {
|
import {
|
||||||
createMessageStoreIndexes,
|
createMessageStoreIndexes,
|
||||||
@@ -191,11 +193,9 @@ export class MessageStore {
|
|||||||
);
|
);
|
||||||
|
|
||||||
this.stmtFindPrivateMessageAtTime = this.db.prepare(
|
this.stmtFindPrivateMessageAtTime = this.db.prepare(
|
||||||
`SELECT message_hash
|
`SELECT message_hash, data
|
||||||
FROM messages
|
FROM messages
|
||||||
WHERE is_group = 0 AND session_id = ? AND private_direction = ? AND timestamp = ?
|
WHERE is_group = 0 AND session_id = ? AND private_direction = ? AND timestamp = ?`,
|
||||||
ORDER BY sequence DESC
|
|
||||||
LIMIT 1`,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
this.stmtFindPrivateMessageBySequence = this.db.prepare(
|
this.stmtFindPrivateMessageBySequence = this.db.prepare(
|
||||||
@@ -514,6 +514,7 @@ export class MessageStore {
|
|||||||
replySequence: number,
|
replySequence: number,
|
||||||
sentBySelf: boolean,
|
sentBySelf: boolean,
|
||||||
timestamp?: number,
|
timestamp?: number,
|
||||||
|
replyElements?: readonly MessageElement[],
|
||||||
): number | null {
|
): number | null {
|
||||||
if (Number.isSafeInteger(replySequence) && replySequence > 0) {
|
if (Number.isSafeInteger(replySequence) && replySequence > 0) {
|
||||||
const byClientSequence = this.findPrivateMessageId(
|
const byClientSequence = this.findPrivateMessageId(
|
||||||
@@ -531,7 +532,7 @@ export class MessageStore {
|
|||||||
if (byConversationSequence !== null) return byConversationSequence;
|
if (byConversationSequence !== null) return byConversationSequence;
|
||||||
}
|
}
|
||||||
if (!sentBySelf) return null;
|
if (!sentBySelf) return null;
|
||||||
const byExactTime = this.findPrivateMessageIdAtTime(sessionId, true, timestamp);
|
const byExactTime = this.findPrivateMessageIdAtTime(sessionId, true, timestamp, replyElements);
|
||||||
if (byExactTime !== null) return byExactTime;
|
if (byExactTime !== null) return byExactTime;
|
||||||
const byNearbyTime = this.findUniquePrivateOutgoingNearTime(sessionId, timestamp);
|
const byNearbyTime = this.findUniquePrivateOutgoingNearTime(sessionId, timestamp);
|
||||||
if (byNearbyTime !== null) return byNearbyTime;
|
if (byNearbyTime !== null) return byNearbyTime;
|
||||||
@@ -542,15 +543,29 @@ export class MessageStore {
|
|||||||
sessionId: number,
|
sessionId: number,
|
||||||
sentBySelf: boolean,
|
sentBySelf: boolean,
|
||||||
timestamp?: number,
|
timestamp?: number,
|
||||||
|
replyElements?: readonly MessageElement[],
|
||||||
): number | null {
|
): number | null {
|
||||||
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) return null;
|
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) return null;
|
||||||
if (!isUsablePrivateQuoteTime(timestamp)) return null;
|
if (!isUsablePrivateQuoteTime(timestamp)) return null;
|
||||||
const row = this.stmtFindPrivateMessageAtTime.get(
|
const rows = this.stmtFindPrivateMessageAtTime.all(
|
||||||
sessionId,
|
sessionId,
|
||||||
sentBySelf ? 1 : 0,
|
sentBySelf ? 1 : 0,
|
||||||
timestamp,
|
timestamp,
|
||||||
) as { message_hash: number } | undefined;
|
) as { message_hash: number; data: string | null }[];
|
||||||
if (!row) return null;
|
if (rows.length === 0) return null;
|
||||||
|
let matches = rows;
|
||||||
|
if (rows.length > 1) {
|
||||||
|
const text = replyElements?.length && replyElements.every(e => e.type === 'text')
|
||||||
|
? replyElements.map(e => e.text ?? '').join('')
|
||||||
|
: null;
|
||||||
|
matches = text ? rows.filter(row => cachedPlainText(row.data) === text) : [];
|
||||||
|
if (matches.length !== 1) {
|
||||||
|
log.debug('private quote time is ambiguous: peer=%d time=%d candidates=%d contentMatches=%d',
|
||||||
|
sessionId, timestamp, rows.length, matches.length);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const row = matches[0]!;
|
||||||
if (!isValidMessageId(row.message_hash)) {
|
if (!isValidMessageId(row.message_hash)) {
|
||||||
throw new Error(`private message lookup matched invalid message id ${String(row.message_hash)}`);
|
throw new Error(`private message lookup matched invalid message id ${String(row.message_hash)}`);
|
||||||
}
|
}
|
||||||
@@ -822,6 +837,20 @@ function eventPrivateDirection(isGroup: boolean, event: JsonObject): number {
|
|||||||
|
|
||||||
const PRIVATE_REPLY_TIME_WINDOWS_SECONDS = [5, 30] as const;
|
const PRIVATE_REPLY_TIME_WINDOWS_SECONDS = [5, 30] as const;
|
||||||
|
|
||||||
|
/** Only compare complete plain text; media labels and truncated previews are ambiguous. */
|
||||||
|
function cachedPlainText(data: string | null): string | null {
|
||||||
|
if (!data) return null;
|
||||||
|
const event = JSON.parse(data) as JsonObject;
|
||||||
|
if (typeof event.message === 'string') {
|
||||||
|
return event.message.includes('[CQ:') ? null : cqUnescape(event.message);
|
||||||
|
}
|
||||||
|
if (!Array.isArray(event.message) || event.message.length === 0) return null;
|
||||||
|
const segments = event.message as JsonObject[];
|
||||||
|
if (!segments.every(segment => segment?.type === 'text'
|
||||||
|
&& typeof (segment.data as JsonObject | undefined)?.text === 'string')) return null;
|
||||||
|
return segments.map(segment => (segment.data as JsonObject).text).join('');
|
||||||
|
}
|
||||||
|
|
||||||
function isUsablePrivateQuoteTime(timestamp: number | undefined): timestamp is number {
|
function isUsablePrivateQuoteTime(timestamp: number | undefined): timestamp is number {
|
||||||
return timestamp !== undefined
|
return timestamp !== undefined
|
||||||
&& Number.isSafeInteger(timestamp)
|
&& Number.isSafeInteger(timestamp)
|
||||||
|
|||||||
@@ -926,6 +926,27 @@ describe('MessageStore', () => {
|
|||||||
});
|
});
|
||||||
expect(store.resolvePrivateReplyMessageId(peerId, 27_892, true, sentAt + 2)).toBeNull();
|
expect(store.resolvePrivateReplyMessageId(peerId, 27_892, true, sentAt + 2)).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('does not choose the latest same-second message without unique quoted content', () => {
|
||||||
|
for (const id of [101, 102]) {
|
||||||
|
store.storeMeta(id, {
|
||||||
|
isGroup: false, targetId: peerId, sequence: id, sequenceAuthoritative: true,
|
||||||
|
eventName: PRIVATE_MESSAGE_EVENT, clientSequence: id + 1000,
|
||||||
|
privateDirection: 'outgoing', random: id, timestamp: sentAt,
|
||||||
|
});
|
||||||
|
store.storeEvent(id, false, peerId, id, PRIVATE_MESSAGE_EVENT, {
|
||||||
|
time: sentAt, post_type: 'message_sent', message_type: 'private', sub_type: 'friend',
|
||||||
|
message: [{ type: 'text', data: { text: 'same text' } }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
expect(store.resolvePrivateReplyMessageId(peerId, 999, true, sentAt)).toBeNull();
|
||||||
|
expect(store.resolvePrivateReplyMessageId(peerId, 999, true, sentAt,
|
||||||
|
[{ type: 'text', text: 'same text' }])).toBeNull();
|
||||||
|
expect(store.resolvePrivateReplyMessageId(peerId, 999, true, sentAt,
|
||||||
|
[{ type: 'text', text: 'same' }])).toBeNull();
|
||||||
|
expect(store.resolvePrivateReplyMessageId(peerId, 1101, true, sentAt,
|
||||||
|
[{ type: 'text', text: 'same text' }])).toBe(101);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('lets a real group event replace an older non-authoritative placeholder', () => {
|
it('lets a real group event replace an older non-authoritative placeholder', () => {
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ const SELF_ID = 3961840894;
|
|||||||
const PEER_ID = 2705892349;
|
const PEER_ID = 2705892349;
|
||||||
|
|
||||||
function productionResolver(store: MessageStore): ConverterContext['messageIdResolver'] {
|
function productionResolver(store: MessageStore): ConverterContext['messageIdResolver'] {
|
||||||
return (isGroup, sessionId, sequence, eventName, timestamp) => {
|
return (isGroup, sessionId, sequence, eventName, timestamp, replyElements) => {
|
||||||
const resolvedEventName = eventName
|
const resolvedEventName = eventName
|
||||||
|| (isGroup ? 'group_message' : PRIVATE_MESSAGE_EVENT);
|
|| (isGroup ? 'group_message' : PRIVATE_MESSAGE_EVENT);
|
||||||
if (!isGroup
|
if (!isGroup
|
||||||
@@ -29,6 +29,7 @@ function productionResolver(store: MessageStore): ConverterContext['messageIdRes
|
|||||||
sequence,
|
sequence,
|
||||||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
|
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
|
||||||
timestamp,
|
timestamp,
|
||||||
|
replyElements,
|
||||||
);
|
);
|
||||||
if (storedId !== null) return storedId;
|
if (storedId !== null) return storedId;
|
||||||
}
|
}
|
||||||
@@ -56,6 +57,39 @@ describe('private reply id matches send receipt (#417, #433)', () => {
|
|||||||
fs.rmSync(dir, { recursive: true, force: true });
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('matches quoted text instead of a later voice message in the same second (#502)', async () => {
|
||||||
|
const sentAt = 1_790_000_000;
|
||||||
|
for (const [id, message] of [
|
||||||
|
[101, [{ type: 'text', data: { text: 'the quoted text' } }]],
|
||||||
|
[102, [{ type: 'record', data: { file: 'voice.amr' } }]],
|
||||||
|
] as const) {
|
||||||
|
store.storeMeta(id, {
|
||||||
|
isGroup: false, targetId: PEER_ID, sequence: id, sequenceAuthoritative: true,
|
||||||
|
eventName: PRIVATE_NT_MESSAGE_EVENT, clientSequence: id + 1000,
|
||||||
|
privateDirection: 'outgoing', random: id, timestamp: sentAt,
|
||||||
|
});
|
||||||
|
store.storeEvent(id, false, PEER_ID, id, PRIVATE_NT_MESSAGE_EVENT, {
|
||||||
|
time: sentAt, post_type: 'message_sent', message_type: 'private', sub_type: 'friend',
|
||||||
|
message: JSON.parse(JSON.stringify(message)),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
store.close();
|
||||||
|
store = new MessageStore(path.join(dir, 'messages.db'));
|
||||||
|
const ctx: ConverterContext = {
|
||||||
|
selfId: SELF_ID, imageUrlResolver: null, mediaUrlResolver: null, mediaSegmentSink: null,
|
||||||
|
messageIdResolver: productionResolver(store),
|
||||||
|
};
|
||||||
|
const event: FriendMessage = {
|
||||||
|
kind: 'friend_message', time: sentAt + 2, selfUin: SELF_ID,
|
||||||
|
senderUin: PEER_ID, peerUin: PEER_ID, senderUid: 'u_peer', senderNick: 'peer',
|
||||||
|
msgSeq: 2773, ntMsgSeq: 103, clientSeq: 2773, sequenceAuthoritative: true, msgId: 2,
|
||||||
|
elements: [{ type: 'reply', replySeq: 9999, replySenderUin: SELF_ID, replyTime: sentAt,
|
||||||
|
replyElements: [{ type: 'text', text: 'the quoted text' }] }],
|
||||||
|
};
|
||||||
|
const json = await convertFriendMessage(ctx, event);
|
||||||
|
expect(json.message).toEqual([{ type: 'reply', data: { id: '101' } }]);
|
||||||
|
});
|
||||||
|
|
||||||
it.each([
|
it.each([
|
||||||
{
|
{
|
||||||
name: '#433',
|
name: '#433',
|
||||||
|
|||||||
Reference in new issue
Block a user