fix(onebot): correct private message history (#256)
Use the C2C roam cursor and canonical NT sequence for bidirectional history. Persist direction-aware recall tombstones so recalled messages cannot reappear.
This commit is contained in:
37 files changed
+1853
-242
No files matched your search
@@ -339,7 +339,7 @@ export const actions = [
|
||||
|
||||
defineAction({
|
||||
name: 'get_friend_msg_history',
|
||||
summary: '获取好友消息历史',
|
||||
summary: '获取好友消息历史(无锚点时从服务器获取最新双向记录)',
|
||||
readOnly: true,
|
||||
returns: '{ messages }:好友消息事件对象数组(每项为 OneBot 消息事件,内部字段不固定)。',
|
||||
returnsSchema: {
|
||||
@@ -353,7 +353,7 @@ export const actions = [
|
||||
user_id: f.userId(),
|
||||
// Signed int32 hash, frequently negative — see get_group_msg_history.
|
||||
message_id: f.int().default(0).role('message_id'),
|
||||
count: f.int({ min: 0 }).default(20),
|
||||
count: f.int({ min: 0 }).default(20).describe('无锚点时从 QQ 服务器获取最新双向历史;服务器或身份解析失败时动作失败,不返回不完整的本地缓存'),
|
||||
reverse_order: f.bool().default(true).describe('仅在 message_id 非 0 时生效;true 返回锚点及更旧消息,false 返回锚点及更新消息'),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
MessageIdResolver,
|
||||
MediaSegmentSink,
|
||||
} from './index';
|
||||
import { GROUP_MESSAGE_EVENT, privateMessageEventName } from '../message-id';
|
||||
import { resolveReplyId } from './utils';
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
@@ -36,6 +37,7 @@ const log = createLogger('MsgParser');
|
||||
export interface ToSegmentContext {
|
||||
isGroup: boolean;
|
||||
sessionId: number;
|
||||
selfId: number;
|
||||
imageUrlResolver?: ImageUrlResolver | null;
|
||||
mediaUrlResolver?: MediaUrlResolver | null;
|
||||
messageIdResolver?: MessageIdResolver | null;
|
||||
@@ -182,7 +184,22 @@ export const ELEMENT_CODECS = {
|
||||
|
||||
reply: {
|
||||
async toSegment(element, ctx) {
|
||||
const id = resolveReplyId(ctx.isGroup, ctx.sessionId, element.replySeq ?? 0, ctx.messageIdResolver);
|
||||
const sentBySelf = !ctx.isGroup
|
||||
&& ctx.selfId > 0
|
||||
&& element.replySenderUin === ctx.selfId;
|
||||
const eventName = ctx.isGroup
|
||||
? GROUP_MESSAGE_EVENT
|
||||
: privateMessageEventName(sentBySelf, false);
|
||||
const id = resolveReplyId(
|
||||
ctx.isGroup,
|
||||
ctx.sessionId,
|
||||
element.replySeq ?? 0,
|
||||
ctx.messageIdResolver,
|
||||
eventName,
|
||||
element.replyTime && element.replyTime > 0
|
||||
? element.replyTime
|
||||
: Number.MAX_SAFE_INTEGER,
|
||||
);
|
||||
return { type: 'reply', data: { id: String(id) } };
|
||||
},
|
||||
async fromSegment(data, options) {
|
||||
|
||||
@@ -33,7 +33,13 @@ import { elementsToJson } from './to-segment';
|
||||
|
||||
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string | Promise<string>;
|
||||
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
|
||||
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
|
||||
export type MessageIdResolver = (
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
sequence: number,
|
||||
eventName: string,
|
||||
timestamp?: number,
|
||||
) => number;
|
||||
|
||||
export type MediaSegmentSink = (
|
||||
mediaType: 'image' | 'record' | 'video',
|
||||
@@ -120,9 +126,10 @@ export async function elementsToOneBotSegments(
|
||||
mediaUrlResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
mediaSegmentSink?: MediaSegmentSink | null,
|
||||
selfId = 0,
|
||||
) {
|
||||
return elementsToJson(
|
||||
elements, isGroup, sessionId,
|
||||
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
|
||||
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink, selfId,
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { segmentsToRawMessage } from '../helper/cq';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
|
||||
import {
|
||||
GROUP_MESSAGE_EVENT,
|
||||
PRIVATE_MESSAGE_EVENT,
|
||||
privateMessageEventName,
|
||||
} from '../message-id';
|
||||
import type { JsonObject } from '../types';
|
||||
import type { ConverterContext } from './index';
|
||||
import { elementsToJson } from './to-segment';
|
||||
@@ -16,6 +20,7 @@ function toSegments(ctx: ConverterContext, elements: MessageElement[], isGroup:
|
||||
return elementsToJson(
|
||||
elements, isGroup, sessionId,
|
||||
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
|
||||
ctx.selfId,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -34,8 +39,18 @@ async function convertPrivateMessage(
|
||||
const sessionId = event.kind === 'friend_message' && event.peerUin && event.peerUin > 0
|
||||
? event.peerUin
|
||||
: event.senderUin;
|
||||
// ContentHead field 5 (`msgSeq`) is sender-local in C2C and can collide in
|
||||
// both directions. Friend history/pushes expose field 11 (`ntMsgSeq`), which
|
||||
// is conversation-wide and therefore the canonical OneBot id input.
|
||||
const ntSequence = event.kind === 'friend_message' ? (event.ntMsgSeq ?? 0) : 0;
|
||||
const hasCanonicalNtSequence = ntSequence > 0
|
||||
&& event.sequenceAuthoritative !== false;
|
||||
const messageIdSequence = hasCanonicalNtSequence ? ntSequence : event.msgSeq;
|
||||
const eventName = event.kind === 'friend_message'
|
||||
? privateMessageEventName(isSelf, hasCanonicalNtSequence)
|
||||
: PRIVATE_MESSAGE_EVENT;
|
||||
const messageId = applyMessageIdResolver(
|
||||
ctx.messageIdResolver, false, sessionId, event.msgSeq, PRIVATE_MESSAGE_EVENT,
|
||||
ctx.messageIdResolver, false, sessionId, messageIdSequence, eventName,
|
||||
);
|
||||
const segments = await toSegments(ctx, event.elements, false, sessionId);
|
||||
const sender: JsonObject = {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
|
||||
import { GROUP_MESSAGE_EVENT, privateMessageEventName } from '../message-id';
|
||||
import type { JsonObject } from '../types';
|
||||
import type { ConverterContext } from './index';
|
||||
import { applyMessageIdResolver, isSameActor } from './utils';
|
||||
@@ -80,7 +80,12 @@ export function convertGroupAdmin(ctx: ConverterContext, event: GroupAdmin): Jso
|
||||
|
||||
export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall): JsonObject {
|
||||
const messageId = applyMessageIdResolver(
|
||||
ctx.messageIdResolver, false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
|
||||
ctx.messageIdResolver,
|
||||
false,
|
||||
event.userUin,
|
||||
event.msgSeq,
|
||||
privateMessageEventName(event.recalledBySelf === true, false),
|
||||
event.time,
|
||||
);
|
||||
return notice(ctx, event, {
|
||||
notice_type: 'friend_recall',
|
||||
|
||||
@@ -19,6 +19,7 @@ export async function elementsToJson(
|
||||
mediaUrlResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
mediaSegmentSink?: MediaSegmentSink | null,
|
||||
selfId = 0,
|
||||
): Promise<JsonArray> {
|
||||
const result: JsonArray = [];
|
||||
for (const element of elements) {
|
||||
@@ -27,7 +28,7 @@ export async function elementsToJson(
|
||||
try {
|
||||
result.push(await elementToSegment(
|
||||
element, isGroup, sessionId,
|
||||
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
|
||||
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink, selfId,
|
||||
));
|
||||
} catch (err) {
|
||||
log.warn('segment convert skipped type=%s (%s)', element.type,
|
||||
@@ -45,6 +46,7 @@ async function elementToSegment(
|
||||
mediaUrlResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
mediaSegmentSink?: MediaSegmentSink | null,
|
||||
selfId = 0,
|
||||
): Promise<JsonObject> {
|
||||
// S 收·转:按 element.type 查 codec 表;缺条目则走 default 透传(保持原兜底)。
|
||||
const codec = getElementCodec(element.type);
|
||||
@@ -56,6 +58,7 @@ async function elementToSegment(
|
||||
mediaUrlResolver,
|
||||
messageIdResolver,
|
||||
mediaSegmentSink,
|
||||
selfId,
|
||||
});
|
||||
}
|
||||
log.warn('segment convert fallback type=%s reason=no receive-side codec', element.type);
|
||||
|
||||
@@ -22,9 +22,10 @@ export function applyMessageIdResolver(
|
||||
sessionId: number,
|
||||
sequence: number,
|
||||
eventName: string,
|
||||
timestamp?: number,
|
||||
): number {
|
||||
if (resolver) {
|
||||
const resolved = resolver(isGroup, sessionId, sequence, eventName);
|
||||
const resolved = resolver(isGroup, sessionId, sequence, eventName, timestamp);
|
||||
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
|
||||
}
|
||||
const seq = Math.trunc(sequence);
|
||||
@@ -36,13 +37,14 @@ export function resolveReplyId(
|
||||
sessionId: number,
|
||||
sequence: number,
|
||||
resolver?: MessageIdResolver | null,
|
||||
eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT,
|
||||
timestamp?: number,
|
||||
): number {
|
||||
const seq = Math.trunc(sequence);
|
||||
if (seq === 0) return 0;
|
||||
|
||||
if (resolver) {
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
const resolved = resolver(isGroup, sessionId, seq, eventName);
|
||||
const resolved = resolver(isGroup, sessionId, seq, eventName, timestamp);
|
||||
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,15 @@ import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import type { QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { convertEvent } from './event-converter';
|
||||
import type { OneBotInstanceContext } from './instance-context';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import {
|
||||
GROUP_MESSAGE_EVENT,
|
||||
PRIVATE_MESSAGE_EVENT,
|
||||
hashMessageIdInt32,
|
||||
privateMessageEventName,
|
||||
} from './message-id';
|
||||
import { backfillReplyTarget } from './modules/message-actions';
|
||||
import { deliverPttTransText, pttTransKey } from './modules/ptt-trans-waiter';
|
||||
import type { MessageMeta } from './types';
|
||||
|
||||
const moduleLog = createLogger('Event');
|
||||
|
||||
@@ -61,13 +67,33 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): EventPipeline
|
||||
);
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('friend_message', (event) => track(event.kind, async () => {
|
||||
cachePrivateMessageMeta(ctx, event.peerUin ?? event.senderUin, event.msgSeq, event.time, event.msgId);
|
||||
cachePrivateMessageMeta(
|
||||
ctx,
|
||||
event.peerUin ?? event.senderUin,
|
||||
event.msgSeq,
|
||||
event.ntMsgSeq ?? 0,
|
||||
event.clientSeq ?? event.msgSeq,
|
||||
event.time,
|
||||
event.msgId,
|
||||
event.sequenceAuthoritative !== false,
|
||||
event.senderUin === ctx.selfId ? 'outgoing' : 'incoming',
|
||||
);
|
||||
await convertAndDispatch(ctx, log, event);
|
||||
})),
|
||||
);
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('temp_message', (event) => track(event.kind, async () => {
|
||||
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0);
|
||||
cachePrivateMessageMeta(
|
||||
ctx,
|
||||
event.senderUin,
|
||||
event.msgSeq,
|
||||
event.ntMsgSeq ?? 0,
|
||||
event.clientSeq ?? 0,
|
||||
event.time,
|
||||
0,
|
||||
event.sequenceAuthoritative !== false,
|
||||
undefined,
|
||||
);
|
||||
// Record this group temp session so a later reply is limited to sessions
|
||||
// the peer opened.
|
||||
ctx.tempSessions.record(event.senderUin, event.groupId);
|
||||
@@ -80,7 +106,26 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): EventPipeline
|
||||
if (event.kind === 'group_msg_emoji_like') {
|
||||
cacheReaction(ctx, event);
|
||||
}
|
||||
await convertAndDispatch(ctx, log, event);
|
||||
let messageIdOverride: number | undefined;
|
||||
if (event.kind === 'friend_recall') {
|
||||
const clientSequence = event.clientSeq ?? event.msgSeq;
|
||||
const recalled = ctx.messageStore.recordPrivateRecall(
|
||||
event.userUin,
|
||||
clientSequence,
|
||||
event.recalledBySelf === true,
|
||||
event.time,
|
||||
);
|
||||
if (recalled !== null) {
|
||||
messageIdOverride = recalled;
|
||||
} else {
|
||||
log.debug(
|
||||
'friend recall cache miss peer=%d clientSeq=%d',
|
||||
event.userUin,
|
||||
clientSequence,
|
||||
);
|
||||
}
|
||||
}
|
||||
await convertAndDispatch(ctx, log, event, messageIdOverride);
|
||||
})),
|
||||
);
|
||||
}
|
||||
@@ -143,19 +188,31 @@ const NOTICE_KINDS = [
|
||||
'group_msg_emoji_like',
|
||||
] as const satisfies readonly QQEventVariant['kind'][];
|
||||
|
||||
async function convertAndDispatch(ctx: OneBotInstanceContext, log: Logger, event: QQEventVariant): Promise<void> {
|
||||
async function convertAndDispatch(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: QQEventVariant,
|
||||
messageIdOverride?: number,
|
||||
): Promise<void> {
|
||||
// Inbound choke point — the receive-side mirror of the outbound api-handler.
|
||||
// Correlate the whole receive chain (decode → convert, incl. any rkey-fetch
|
||||
// packets the conversion triggers, → dispatch) under one [req#N]. Only pay
|
||||
// the AsyncLocalStorage wrap + id when trace is actually live.
|
||||
if (getLogLevel() !== 'trace') {
|
||||
await runConvertAndDispatch(ctx, log, event);
|
||||
await runConvertAndDispatch(ctx, log, event, messageIdOverride);
|
||||
return;
|
||||
}
|
||||
await runWithRequestId(nextRequestId(), () => runConvertAndDispatch(ctx, log, event));
|
||||
await runWithRequestId(nextRequestId(), () => (
|
||||
runConvertAndDispatch(ctx, log, event, messageIdOverride)
|
||||
));
|
||||
}
|
||||
|
||||
async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, event: QQEventVariant): Promise<void> {
|
||||
async function runConvertAndDispatch(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: QQEventVariant,
|
||||
messageIdOverride?: number,
|
||||
): Promise<void> {
|
||||
// Raw inbound event, memory-only (trace). Lazy → the deep render runs only
|
||||
// when trace is live.
|
||||
log.trace(() => [`recv ${event.kind} ⇐ %s`, renderParamsVerbose(event)]);
|
||||
@@ -165,6 +222,10 @@ async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, ev
|
||||
log.trace(() => [`recv ${event.kind} ⇒ dropped (${Date.now() - startedAt}ms)`]);
|
||||
return;
|
||||
}
|
||||
if (messageIdOverride !== undefined && event.kind === 'friend_recall') {
|
||||
converted.message_id = messageIdOverride;
|
||||
}
|
||||
if (event.kind === 'friend_message' && isFriendMessageRecalled(ctx, log, event)) return;
|
||||
// If this message quotes one we don't have, fetch + persist it first (gated +
|
||||
// throttled) so a consumer's get_msg on the quote resolves. No-op for the
|
||||
// common case (no reply, or the quoted message is already stored). Never let a
|
||||
@@ -180,6 +241,9 @@ async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, ev
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
// Backfill can await several network/media operations. Re-check immediately
|
||||
// before dispatch so a recall that arrived during that gap wins the race.
|
||||
if (event.kind === 'friend_message' && isFriendMessageRecalled(ctx, log, event)) return;
|
||||
ctx.dispatchEvent(converted, 'bridge');
|
||||
log.trace(() => [`recv ${event.kind} ⇒ ${String(converted.post_type ?? '?')} (${Date.now() - startedAt}ms)`]);
|
||||
}
|
||||
@@ -201,23 +265,64 @@ function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEven
|
||||
function cachePrivateMessageMeta(
|
||||
ctx: OneBotInstanceContext,
|
||||
sessionId: number,
|
||||
msgSeq: number,
|
||||
messageSequence: number,
|
||||
serverSequence: number,
|
||||
clientSequence: number,
|
||||
timestamp: number,
|
||||
random: number,
|
||||
sequenceAuthoritative: boolean,
|
||||
privateDirection: MessageMeta['privateDirection'],
|
||||
): void {
|
||||
const messageId = hashMessageIdInt32(msgSeq, sessionId, PRIVATE_MESSAGE_EVENT);
|
||||
const isFriendMessage = privateDirection !== undefined;
|
||||
const hasNtSequence = isFriendMessage
|
||||
&& sequenceAuthoritative
|
||||
&& serverSequence > 0;
|
||||
const eventName = isFriendMessage
|
||||
? privateMessageEventName(privateDirection === 'outgoing', hasNtSequence)
|
||||
: PRIVATE_MESSAGE_EVENT;
|
||||
const messageId = hashMessageIdInt32(
|
||||
hasNtSequence ? serverSequence : messageSequence,
|
||||
sessionId,
|
||||
eventName,
|
||||
);
|
||||
ctx.cacheMessageMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: sessionId,
|
||||
sequence: msgSeq,
|
||||
sequenceAuthoritative: true,
|
||||
eventName: PRIVATE_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
sequence: serverSequence,
|
||||
sequenceAuthoritative: sequenceAuthoritative && serverSequence > 0,
|
||||
eventName,
|
||||
clientSequence,
|
||||
privateDirection,
|
||||
random,
|
||||
timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
function isFriendMessageRecalled(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'friend_message' }>,
|
||||
): boolean {
|
||||
const peerUin = event.peerUin ?? event.senderUin;
|
||||
const clientSequence = event.clientSeq ?? event.msgSeq;
|
||||
const sentBySelf = event.senderUin === ctx.selfId;
|
||||
const recalled = ctx.messageStore.isPrivateMessageRecalled(
|
||||
peerUin,
|
||||
clientSequence,
|
||||
sentBySelf,
|
||||
event.time,
|
||||
);
|
||||
if (recalled) {
|
||||
log.debug(
|
||||
'friend message suppressed by recall tombstone peer=%d clientSeq=%d self=%s',
|
||||
peerUin,
|
||||
clientSequence,
|
||||
String(sentBySelf),
|
||||
);
|
||||
}
|
||||
return recalled;
|
||||
}
|
||||
|
||||
function cacheReaction(
|
||||
ctx: OneBotInstanceContext,
|
||||
event: Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>,
|
||||
|
||||
@@ -12,7 +12,13 @@ import type { GlobalSettings } from './global-config';
|
||||
import { MediaIndexer } from './media-indexer';
|
||||
import { MediaStore } from './media-store';
|
||||
import { MediaUrlResolver } from './media-url-resolver';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import {
|
||||
GROUP_MESSAGE_EVENT,
|
||||
PRIVATE_MESSAGE_EVENT,
|
||||
PRIVATE_SENT_MESSAGE_EVENT,
|
||||
hashMessageIdInt32,
|
||||
privateMessageEventName,
|
||||
} from './message-id';
|
||||
import { MessageStore } from './message-store';
|
||||
import { sendGroupMessage, sendPrivateMessage } from './modules/message-actions';
|
||||
import { buildStatusText, matchesStatusCommand, statusCooldownElapsed } from './modules/status-command';
|
||||
@@ -127,8 +133,23 @@ export class OneBotInstance {
|
||||
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
|
||||
mediaUrlResolver: (element, isGroup, sessionId) =>
|
||||
mediaUrlResolver.resolve(element, isGroup, sessionId),
|
||||
messageIdResolver: (isGroup, sessionId, sequence, eventName) =>
|
||||
hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT)),
|
||||
messageIdResolver: (isGroup, sessionId, sequence, eventName, timestamp) => {
|
||||
const resolvedEventName = eventName
|
||||
|| (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT);
|
||||
if (!isGroup
|
||||
&& timestamp !== undefined
|
||||
&& (resolvedEventName === PRIVATE_MESSAGE_EVENT
|
||||
|| resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT)) {
|
||||
const storedId = this.messageStore.findPrivateMessageId(
|
||||
sessionId,
|
||||
sequence,
|
||||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
|
||||
timestamp,
|
||||
);
|
||||
if (storedId !== null) return storedId;
|
||||
}
|
||||
return hashMessageIdInt32(sequence, sessionId, resolvedEventName);
|
||||
},
|
||||
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) =>
|
||||
mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
|
||||
};
|
||||
@@ -495,7 +516,11 @@ export class OneBotInstance {
|
||||
? (toInt(event.target_id) || toInt(event.user_id))
|
||||
: toInt(event.user_id);
|
||||
const sequence = toInt(event.message_seq);
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
const eventName = isGroup
|
||||
? GROUP_MESSAGE_EVENT
|
||||
: event.sub_type === 'friend'
|
||||
? privateMessageEventName(event.post_type === 'message_sent', false)
|
||||
: PRIVATE_MESSAGE_EVENT;
|
||||
|
||||
if (sessionId === 0) return;
|
||||
this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
|
||||
|
||||
@@ -2,6 +2,15 @@ import { createHash } from 'node:crypto';
|
||||
|
||||
export const GROUP_MESSAGE_EVENT = 'group_message';
|
||||
export const PRIVATE_MESSAGE_EVENT = 'private_message';
|
||||
/** Legacy/fallback namespace for private messages sent by the current account. */
|
||||
export const PRIVATE_SENT_MESSAGE_EVENT = 'private_message_sent';
|
||||
/** Namespace for private messages keyed by QQ's conversation-wide NT sequence. */
|
||||
export const PRIVATE_NT_MESSAGE_EVENT = 'private_message_nt';
|
||||
|
||||
export function privateMessageEventName(sentBySelf: boolean, hasNtSequence: boolean): string {
|
||||
if (hasNtSequence) return PRIVATE_NT_MESSAGE_EVENT;
|
||||
return sentBySelf ? PRIVATE_SENT_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
}
|
||||
|
||||
export function hashMessageIdInt32(sequence: number, sessionId: number, eventName: string): number {
|
||||
const seq = Number.isFinite(sequence) ? Math.trunc(sequence) : 0;
|
||||
|
||||
@@ -28,6 +28,10 @@ export class MessageStore {
|
||||
private readonly stmtListEventsLatest: StatementSync;
|
||||
private readonly stmtFindLatestAuthoritativeSequence: StatementSync;
|
||||
private readonly stmtListIncomingC2CSessions: StatementSync;
|
||||
private readonly stmtFindPrivateRecall: StatementSync;
|
||||
private readonly stmtFindPrivateRecallTombstone: StatementSync;
|
||||
private readonly stmtUpsertPrivateRecallTombstone: StatementSync;
|
||||
private readonly stmtDeleteMessage: StatementSync;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
// Replace .json extension with .db if present
|
||||
@@ -39,22 +43,29 @@ export class MessageStore {
|
||||
// Database instance — `close()` finalizes them automatically.
|
||||
this.stmtStoreEvent = this.db.prepare(
|
||||
`INSERT INTO messages
|
||||
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 0, 0, ?, ?)
|
||||
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 0, ?, 0, ?, ?)
|
||||
ON CONFLICT(message_hash) DO UPDATE SET
|
||||
is_group = excluded.is_group,
|
||||
session_id = excluded.session_id,
|
||||
sequence = excluded.sequence,
|
||||
sequence_authoritative = excluded.sequence_authoritative,
|
||||
event_name = excluded.event_name,
|
||||
sequence = CASE WHEN excluded.is_group = 1 THEN excluded.sequence ELSE messages.sequence END,
|
||||
sequence_authoritative = CASE WHEN excluded.is_group = 1 THEN excluded.sequence_authoritative ELSE messages.sequence_authoritative END,
|
||||
event_name = CASE
|
||||
WHEN excluded.is_group = 1 THEN excluded.event_name
|
||||
ELSE messages.event_name
|
||||
END,
|
||||
private_direction = CASE
|
||||
WHEN excluded.private_direction >= 0 THEN excluded.private_direction
|
||||
ELSE messages.private_direction
|
||||
END,
|
||||
timestamp = excluded.timestamp,
|
||||
data = excluded.data`,
|
||||
);
|
||||
|
||||
this.stmtStoreMeta = this.db.prepare(
|
||||
`INSERT INTO messages
|
||||
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(message_hash) DO UPDATE SET
|
||||
is_group = excluded.is_group,
|
||||
session_id = excluded.session_id,
|
||||
@@ -62,6 +73,7 @@ export class MessageStore {
|
||||
sequence_authoritative = excluded.sequence_authoritative,
|
||||
event_name = excluded.event_name,
|
||||
client_sequence = excluded.client_sequence,
|
||||
private_direction = excluded.private_direction,
|
||||
random = excluded.random,
|
||||
timestamp = excluded.timestamp`,
|
||||
);
|
||||
@@ -71,7 +83,7 @@ export class MessageStore {
|
||||
);
|
||||
|
||||
this.stmtFindMeta = this.db.prepare(
|
||||
'SELECT is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?',
|
||||
'SELECT is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp FROM messages WHERE message_hash = ?',
|
||||
);
|
||||
|
||||
this.stmtResolveReplyGroup = this.db.prepare(
|
||||
@@ -82,9 +94,13 @@ export class MessageStore {
|
||||
);
|
||||
|
||||
this.stmtResolveReplyPrivate = this.db.prepare(
|
||||
`SELECT sequence
|
||||
`SELECT CASE
|
||||
WHEN client_sequence > 0 THEN client_sequence
|
||||
ELSE sequence
|
||||
END AS sequence
|
||||
FROM messages
|
||||
WHERE is_group = 0 AND message_hash = ? AND sequence_authoritative = 1
|
||||
WHERE is_group = 0 AND message_hash = ?
|
||||
AND (client_sequence > 0 OR sequence_authoritative = 1)
|
||||
LIMIT 1`,
|
||||
);
|
||||
|
||||
@@ -134,6 +150,33 @@ export class MessageStore {
|
||||
GROUP BY session_id
|
||||
ORDER BY session_id ASC`,
|
||||
);
|
||||
|
||||
this.stmtFindPrivateRecall = this.db.prepare(
|
||||
`SELECT message_hash
|
||||
FROM messages
|
||||
WHERE is_group = 0 AND session_id = ? AND client_sequence = ?
|
||||
AND private_direction = ? AND timestamp <= ?
|
||||
ORDER BY timestamp DESC, sequence DESC
|
||||
LIMIT 1`,
|
||||
);
|
||||
|
||||
this.stmtFindPrivateRecallTombstone = this.db.prepare(
|
||||
`SELECT recalled_at
|
||||
FROM private_recall_tombstones
|
||||
WHERE session_id = ? AND client_sequence = ? AND private_direction = ?`,
|
||||
);
|
||||
|
||||
this.stmtUpsertPrivateRecallTombstone = this.db.prepare(
|
||||
`INSERT INTO private_recall_tombstones
|
||||
(session_id, client_sequence, private_direction, recalled_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(session_id, client_sequence, private_direction) DO UPDATE SET
|
||||
recalled_at = MAX(private_recall_tombstones.recalled_at, excluded.recalled_at)`,
|
||||
);
|
||||
|
||||
this.stmtDeleteMessage = this.db.prepare(
|
||||
'DELETE FROM messages WHERE message_hash = ?',
|
||||
);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
@@ -152,6 +195,30 @@ export class MessageStore {
|
||||
if (!isValidMessageId(messageId)) return;
|
||||
const json = JSON.stringify(event);
|
||||
const timestamp = toInt(event.time);
|
||||
const privateDirection = eventPrivateDirection(isGroup, event);
|
||||
if (privateDirection >= 0) {
|
||||
const existing = this.stmtFindMeta.get(messageId) as { client_sequence: number } | undefined;
|
||||
const eventClientSequence = toInt(event.message_seq);
|
||||
const clientSequence = existing?.client_sequence && existing.client_sequence > 0
|
||||
? existing.client_sequence
|
||||
: eventClientSequence;
|
||||
if (clientSequence > 0 && this.isPrivateMessageRecalled(
|
||||
sessionId,
|
||||
clientSequence,
|
||||
privateDirection === 1,
|
||||
timestamp,
|
||||
)) {
|
||||
this.stmtDeleteMessage.run(messageId);
|
||||
log.debug(
|
||||
'suppressed recalled private event: peer=%d clientSeq=%d self=%s messageId=%d',
|
||||
sessionId,
|
||||
clientSequence,
|
||||
String(privateDirection === 1),
|
||||
messageId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this.stmtStoreEvent.run(
|
||||
messageId,
|
||||
@@ -160,6 +227,7 @@ export class MessageStore {
|
||||
sequence,
|
||||
options.sequenceAuthoritative === false ? 0 : 1,
|
||||
eventName,
|
||||
privateDirection,
|
||||
timestamp,
|
||||
json,
|
||||
);
|
||||
@@ -167,6 +235,26 @@ export class MessageStore {
|
||||
|
||||
storeMeta(messageId: number, meta: MessageMeta): void {
|
||||
if (!isValidMessageId(messageId)) return;
|
||||
const privateDirection = encodePrivateDirection(meta.privateDirection);
|
||||
if (!meta.isGroup
|
||||
&& privateDirection >= 0
|
||||
&& meta.clientSequence > 0
|
||||
&& this.isPrivateMessageRecalled(
|
||||
meta.targetId,
|
||||
meta.clientSequence,
|
||||
privateDirection === 1,
|
||||
meta.timestamp,
|
||||
)) {
|
||||
this.stmtDeleteMessage.run(messageId);
|
||||
log.debug(
|
||||
'suppressed recalled private meta: peer=%d clientSeq=%d self=%s messageId=%d',
|
||||
meta.targetId,
|
||||
meta.clientSequence,
|
||||
String(privateDirection === 1),
|
||||
messageId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.stmtStoreMeta.run(
|
||||
messageId,
|
||||
meta.isGroup ? 1 : 0,
|
||||
@@ -175,6 +263,7 @@ export class MessageStore {
|
||||
meta.sequenceAuthoritative === false ? 0 : 1,
|
||||
meta.eventName,
|
||||
meta.clientSequence,
|
||||
privateDirection,
|
||||
meta.random,
|
||||
meta.timestamp
|
||||
);
|
||||
@@ -202,6 +291,7 @@ export class MessageStore {
|
||||
sequence_authoritative: number;
|
||||
event_name: string;
|
||||
client_sequence: number;
|
||||
private_direction: number;
|
||||
random: number;
|
||||
timestamp: number;
|
||||
} | undefined;
|
||||
@@ -215,6 +305,11 @@ export class MessageStore {
|
||||
sequenceAuthoritative: row.sequence_authoritative === 1,
|
||||
eventName: row.event_name,
|
||||
clientSequence: row.client_sequence,
|
||||
...(row.private_direction === 0
|
||||
? { privateDirection: 'incoming' as const }
|
||||
: row.private_direction === 1
|
||||
? { privateDirection: 'outgoing' as const }
|
||||
: {}),
|
||||
random: row.random,
|
||||
timestamp: row.timestamp,
|
||||
};
|
||||
@@ -229,6 +324,8 @@ export class MessageStore {
|
||||
// - When receiving: session_id is the sender's UIN
|
||||
// - When sending reply: sessionId parameter is the recipient's UIN (who we're sending to)
|
||||
// So for private messages, we only match by message_hash and is_group flag.
|
||||
// Replies use ContentHead field 5 (sender-local client sequence), while
|
||||
// `sequence` stores field 11 for bidirectional history pagination.
|
||||
const row = isGroup
|
||||
? this.stmtResolveReplyGroup.get(sessionId, messageId) as { sequence: number } | undefined
|
||||
: this.stmtResolveReplyPrivate.get(messageId) as { sequence: number } | undefined;
|
||||
@@ -239,6 +336,39 @@ export class MessageStore {
|
||||
return row.sequence;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a sender-local C2C sequence to the stored OneBot id. Direction and
|
||||
* timestamp are part of the key because QQ can reuse the same client sequence
|
||||
* in the opposite direction and after a client restart.
|
||||
*/
|
||||
findPrivateMessageId(
|
||||
sessionId: number,
|
||||
clientSequence: number,
|
||||
sentBySelf: boolean,
|
||||
atOrBefore?: number,
|
||||
): number | null {
|
||||
const upperTimestamp = atOrBefore === undefined
|
||||
? Number.MAX_SAFE_INTEGER
|
||||
: atOrBefore;
|
||||
validatePrivateRecallKey(
|
||||
sessionId,
|
||||
clientSequence,
|
||||
upperTimestamp,
|
||||
'message lookup time',
|
||||
);
|
||||
const row = this.stmtFindPrivateRecall.get(
|
||||
sessionId,
|
||||
clientSequence,
|
||||
sentBySelf ? 1 : 0,
|
||||
upperTimestamp,
|
||||
) as { message_hash: number } | undefined;
|
||||
if (!row) return null;
|
||||
if (!isValidMessageId(row.message_hash)) {
|
||||
throw new Error(`private message lookup matched invalid message id ${String(row.message_hash)}`);
|
||||
}
|
||||
return row.message_hash;
|
||||
}
|
||||
|
||||
listSessionEvents(
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
@@ -285,6 +415,78 @@ export class MessageStore {
|
||||
return row.sequence;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a private recall's sender-local client sequence to the OneBot
|
||||
* message id and remove the cached row. The protocol recall notice does not
|
||||
* carry the bidirectional NT sequence, so this lookup must happen before the
|
||||
* notice is converted.
|
||||
*/
|
||||
recordPrivateRecall(
|
||||
sessionId: number,
|
||||
clientSequence: number,
|
||||
recalledBySelf: boolean,
|
||||
recalledAt: number,
|
||||
): number | null {
|
||||
validatePrivateRecallKey(sessionId, clientSequence, recalledAt);
|
||||
const direction = recalledBySelf ? 1 : 0;
|
||||
|
||||
this.db.exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
this.stmtUpsertPrivateRecallTombstone.run(
|
||||
sessionId,
|
||||
clientSequence,
|
||||
direction,
|
||||
recalledAt,
|
||||
);
|
||||
const row = this.stmtFindPrivateRecall.get(
|
||||
sessionId,
|
||||
clientSequence,
|
||||
direction,
|
||||
recalledAt,
|
||||
) as { message_hash: number } | undefined;
|
||||
if (!row) {
|
||||
this.db.exec('COMMIT');
|
||||
return null;
|
||||
}
|
||||
if (!isValidMessageId(row.message_hash)) {
|
||||
throw new Error(`private recall matched invalid message id ${String(row.message_hash)}`);
|
||||
}
|
||||
const deleted = this.stmtDeleteMessage.run(row.message_hash);
|
||||
if (Number(deleted.changes) !== 1) {
|
||||
throw new Error(
|
||||
`private recall cache deletion lost row message=${row.message_hash} peer=${sessionId} clientSeq=${clientSequence}`,
|
||||
);
|
||||
}
|
||||
this.db.exec('COMMIT');
|
||||
log.debug(
|
||||
'private recall removed cached message: peer=%d clientSeq=%d self=%s messageId=%d',
|
||||
sessionId,
|
||||
clientSequence,
|
||||
String(recalledBySelf),
|
||||
row.message_hash,
|
||||
);
|
||||
return row.message_hash;
|
||||
} catch (error) {
|
||||
this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
isPrivateMessageRecalled(
|
||||
sessionId: number,
|
||||
clientSequence: number,
|
||||
sentBySelf: boolean,
|
||||
messageTime: number,
|
||||
): boolean {
|
||||
validatePrivateRecallKey(sessionId, clientSequence, messageTime, 'message time');
|
||||
const row = this.stmtFindPrivateRecallTombstone.get(
|
||||
sessionId,
|
||||
clientSequence,
|
||||
sentBySelf ? 1 : 0,
|
||||
) as { recalled_at: number } | undefined;
|
||||
return row !== undefined && row.recalled_at >= messageTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build read-report targets from current groups plus genuine incoming C2C
|
||||
* sessions. `is_group = 0` alone is insufficient: group temp sessions use
|
||||
@@ -325,14 +527,103 @@ export class MessageStore {
|
||||
sequence_authoritative INTEGER NOT NULL DEFAULT 1,
|
||||
event_name TEXT NOT NULL,
|
||||
client_sequence INTEGER NOT NULL DEFAULT 0,
|
||||
private_direction INTEGER NOT NULL DEFAULT -1,
|
||||
random INTEGER NOT NULL DEFAULT 0,
|
||||
timestamp INTEGER NOT NULL DEFAULT 0,
|
||||
data TEXT
|
||||
)
|
||||
`);
|
||||
this.migrateSequenceAuthority();
|
||||
this.migratePrivateDirection();
|
||||
this.migratePrivateNtSequences();
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS private_recall_tombstones (
|
||||
session_id INTEGER NOT NULL,
|
||||
client_sequence INTEGER NOT NULL,
|
||||
private_direction INTEGER NOT NULL CHECK(private_direction IN (0, 1)),
|
||||
recalled_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (session_id, client_sequence, private_direction)
|
||||
)
|
||||
`);
|
||||
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)');
|
||||
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_authoritative_seq ON messages(is_group, session_id, sequence_authoritative, sequence)');
|
||||
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_private_client_seq ON messages(is_group, session_id, client_sequence)');
|
||||
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_private_client_direction ON messages(is_group, session_id, client_sequence, private_direction)');
|
||||
}
|
||||
|
||||
private migratePrivateDirection(): void {
|
||||
const columns = this.db.prepare('PRAGMA table_info(messages)').all() as Array<{ name: string }>;
|
||||
if (columns.some((column) => column.name === 'private_direction')) return;
|
||||
|
||||
this.db.exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
this.db.exec(
|
||||
'ALTER TABLE messages ADD COLUMN private_direction INTEGER NOT NULL DEFAULT -1',
|
||||
);
|
||||
this.db.exec(`
|
||||
UPDATE messages
|
||||
SET private_direction = CASE json_extract(data, '$.post_type')
|
||||
WHEN 'message' THEN 0
|
||||
WHEN 'message_sent' THEN 1
|
||||
ELSE -1
|
||||
END
|
||||
WHERE is_group = 0
|
||||
AND data IS NOT NULL
|
||||
AND json_valid(data)
|
||||
AND json_extract(data, '$.message_type') = 'private'
|
||||
AND json_extract(data, '$.sub_type') = 'friend'
|
||||
`);
|
||||
this.db.exec('COMMIT');
|
||||
} catch (error) {
|
||||
this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private migratePrivateNtSequences(): void {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS message_store_migrations (
|
||||
name TEXT PRIMARY KEY,
|
||||
applied_at INTEGER NOT NULL
|
||||
)
|
||||
`);
|
||||
|
||||
const migration = 'private-nt-sequence-v1';
|
||||
this.db.exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
const applied = this.db.prepare(
|
||||
'SELECT 1 AS applied FROM message_store_migrations WHERE name = ?',
|
||||
).get(migration) as { applied: number } | undefined;
|
||||
if (applied) {
|
||||
this.db.exec('COMMIT');
|
||||
return;
|
||||
}
|
||||
|
||||
// Pre-fix observed/fetched private rows did not retain client_sequence;
|
||||
// their `sequence` came from ContentHead field 5 and is sender-local.
|
||||
// Action-sent rows do retain client_sequence and their send receipt
|
||||
// carries QQ's private server sequence, so those remain usable.
|
||||
const result = this.db.prepare(`
|
||||
UPDATE messages
|
||||
SET sequence_authoritative = 0
|
||||
WHERE is_group = 0
|
||||
AND sequence_authoritative = 1
|
||||
AND client_sequence = 0
|
||||
`).run();
|
||||
this.db.prepare(
|
||||
'INSERT INTO message_store_migrations (name, applied_at) VALUES (?, ?)',
|
||||
).run(migration, Math.floor(Date.now() / 1000));
|
||||
this.db.exec('COMMIT');
|
||||
if (Number(result.changes) > 0) {
|
||||
log.info(
|
||||
'message-store schema migrated: legacy private sequences invalidated=%d',
|
||||
Number(result.changes),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private migrateSequenceAuthority(): void {
|
||||
@@ -423,6 +714,40 @@ function isValidMessageId(messageId: number): boolean {
|
||||
return Number.isInteger(messageId) && messageId !== 0;
|
||||
}
|
||||
|
||||
function encodePrivateDirection(direction: MessageMeta['privateDirection']): number {
|
||||
if (direction === 'incoming') return 0;
|
||||
if (direction === 'outgoing') return 1;
|
||||
return -1;
|
||||
}
|
||||
|
||||
function eventPrivateDirection(isGroup: boolean, event: JsonObject): number {
|
||||
if (isGroup
|
||||
|| event.message_type !== 'private'
|
||||
|| event.sub_type !== 'friend') {
|
||||
return -1;
|
||||
}
|
||||
if (event.post_type === 'message') return 0;
|
||||
if (event.post_type === 'message_sent') return 1;
|
||||
return -1;
|
||||
}
|
||||
|
||||
function validatePrivateRecallKey(
|
||||
sessionId: number,
|
||||
clientSequence: number,
|
||||
timestamp: number,
|
||||
timestampLabel = 'recall time',
|
||||
): void {
|
||||
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) {
|
||||
throw new Error(`invalid private recall peer ${String(sessionId)}`);
|
||||
}
|
||||
if (!Number.isSafeInteger(clientSequence) || clientSequence <= 0) {
|
||||
throw new Error(`invalid private recall client sequence ${String(clientSequence)}`);
|
||||
}
|
||||
if (!Number.isSafeInteger(timestamp) || timestamp < 0) {
|
||||
throw new Error(`invalid private recall ${timestampLabel} ${String(timestamp)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function toInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
|
||||
@@ -6,7 +6,11 @@ import type { MessageSendResult } from '../api-handler';
|
||||
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../event-converter';
|
||||
import { segmentsToRawMessage } from '../helper/cq';
|
||||
import type { OneBotInstanceContext } from '../instance-context';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
|
||||
import {
|
||||
GROUP_MESSAGE_EVENT,
|
||||
hashMessageIdInt32,
|
||||
privateMessageEventName,
|
||||
} from '../message-id';
|
||||
import { MessageElementValidationError, parseMessage } from '../message-parser';
|
||||
import type { MessageStore } from '../message-store';
|
||||
import { sameSelfSentMessage } from '../self-sent-event';
|
||||
@@ -219,11 +223,12 @@ export async function getGroupHistory(
|
||||
|
||||
/**
|
||||
* Private (c2c) history — the same server-fetch + persist pattern as
|
||||
* {@link getGroupHistory}, but via `SsoGetC2cMsg` (peer = the friend's UID,
|
||||
* resolved from the uin). The anchor is the message_id's sequence (any side of
|
||||
* the conversation) or the latest observed inbound message. Direction applies
|
||||
* only to an explicit anchor; an unanchored request keeps latest-page behavior.
|
||||
* Falls back to the local store on unknown anchor / no uid / empty / error.
|
||||
* {@link getGroupHistory}. Explicit anchors use `SsoGetC2cMsg`; unanchored
|
||||
* latest-page requests use `SsoGetRoamMsg`, because C2C field-5 sequences are
|
||||
* sender-local and cannot safely bootstrap a conversation. Falls back to the
|
||||
* local store only when an explicit message id cannot supply a safe server
|
||||
* anchor. Server and UID failures are surfaced instead of returning a partial
|
||||
* local conversation as a successful response.
|
||||
*/
|
||||
export async function getFriendHistory(
|
||||
ref: HistoryRef,
|
||||
@@ -253,77 +258,81 @@ export async function getFriendHistory(
|
||||
return getFriendMsgHistory(ref.messageStore, userId, messageId, count, reverseOrder);
|
||||
}
|
||||
anchorSeq = meta.sequence;
|
||||
} else {
|
||||
// Current rows are keyed by conversation peer, so the latest local anchor
|
||||
// covers both incoming and self-sent messages. Legacy sender-keyed rows are
|
||||
// repaired when they are fetched through an explicit anchor.
|
||||
anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(false, userId) ?? 0;
|
||||
}
|
||||
log.debug(
|
||||
'friend history anchor selected: user=%d source=%s anchorSeq=%d',
|
||||
'friend history source selected: user=%d source=%s anchorSeq=%d',
|
||||
userId,
|
||||
hasAnchor ? 'message_id' : 'latest_authoritative',
|
||||
hasAnchor ? 'message_id' : 'roam',
|
||||
anchorSeq,
|
||||
);
|
||||
|
||||
if (anchorSeq > 0) {
|
||||
try {
|
||||
const friendUid = await ref.bridge.resolveUserUid(userId);
|
||||
if (friendUid) {
|
||||
const events = await ref.bridge.apis.message.getC2cHistory(
|
||||
friendUid,
|
||||
anchorSeq,
|
||||
want,
|
||||
ref.selfId,
|
||||
effectiveReverseOrder,
|
||||
);
|
||||
const out: JsonObject[] = [];
|
||||
for (const ev of events) {
|
||||
// The action itself identifies the conversation even when an older
|
||||
// QQ response omits ResponseHead.toUin on a self-sent row.
|
||||
if (!ev.peerUin || ev.peerUin <= 0) ev.peerUin = userId;
|
||||
const json = await convertEvent(ref.converterCtx, ev);
|
||||
if (!json || json.message_type !== 'private') continue;
|
||||
// Private history is scoped by the requested peer, while user_id is
|
||||
// the sender and therefore equals selfId for outgoing messages.
|
||||
// Preserve the peer explicitly so later local pagination can keep
|
||||
// both sides of the conversation together.
|
||||
if (json.post_type === 'message_sent' && toHistInt(json.target_id) === 0) {
|
||||
json.target_id = userId;
|
||||
}
|
||||
persistHistoryEvent(ref.messageStore, json, userId);
|
||||
out.push(sanitizeMessageEventForApi(json));
|
||||
}
|
||||
if (out.length > 0) return out;
|
||||
log.debug(
|
||||
'friend history server fetch returned no usable messages: user=%d anchorSeq=%d count=%d; using local store',
|
||||
userId,
|
||||
anchorSeq,
|
||||
want,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'friend history server fetch failed: user=%d anchorSeq=%d count=%d reverseOrder=%s error=%s; using local store',
|
||||
userId,
|
||||
anchorSeq,
|
||||
want,
|
||||
String(effectiveReverseOrder),
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
const friendUid = await ref.bridge.resolveUserUid(userId);
|
||||
if (!friendUid) {
|
||||
throw new Error(`friend history cannot resolve uid for user ${userId}`);
|
||||
}
|
||||
|
||||
return getFriendMsgHistory(ref.messageStore, userId, messageId, count, reverseOrder);
|
||||
const events = hasAnchor
|
||||
? await ref.bridge.apis.message.getC2cHistory(
|
||||
friendUid,
|
||||
anchorSeq,
|
||||
want,
|
||||
ref.selfId,
|
||||
effectiveReverseOrder,
|
||||
)
|
||||
: await ref.bridge.apis.message.getC2cLatestHistory(friendUid, want, ref.selfId);
|
||||
const out: JsonObject[] = [];
|
||||
for (const ev of events) {
|
||||
// The action itself identifies the conversation even when an older
|
||||
// QQ response omits ResponseHead.toUin on a self-sent row.
|
||||
if (!ev.peerUin || ev.peerUin <= 0) ev.peerUin = userId;
|
||||
const clientSequence = ev.clientSeq ?? ev.msgSeq;
|
||||
const sentBySelf = ev.senderUin === ref.selfId;
|
||||
const json = await convertEvent(ref.converterCtx, ev);
|
||||
if (!json || json.message_type !== 'private') continue;
|
||||
// Conversion can await media resolution, so consult the tombstone only
|
||||
// after it settles. From this check through persistence/return there is no
|
||||
// async gap in which a recall could race past us.
|
||||
if (ref.messageStore.isPrivateMessageRecalled(
|
||||
userId,
|
||||
clientSequence,
|
||||
sentBySelf,
|
||||
ev.time,
|
||||
)) {
|
||||
log.debug(
|
||||
'friend history omitted recalled message: user=%d clientSeq=%d self=%s',
|
||||
userId,
|
||||
clientSequence,
|
||||
String(sentBySelf),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
// Private history is scoped by the requested peer, while user_id is
|
||||
// the sender and therefore equals selfId for outgoing messages.
|
||||
if (json.post_type === 'message_sent' && toHistInt(json.target_id) === 0) {
|
||||
json.target_id = userId;
|
||||
}
|
||||
persistHistoryEvent(ref.messageStore, json, userId, ev);
|
||||
out.push(sanitizeMessageEventForApi(json));
|
||||
}
|
||||
log.debug(
|
||||
'friend history server fetch complete: user=%d source=%s anchorSeq=%d requested=%d returned=%d',
|
||||
userId,
|
||||
hasAnchor ? 'message_id' : 'roam',
|
||||
anchorSeq,
|
||||
want,
|
||||
out.length,
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Back-fill the message a freshly-received reply points to, when the local store
|
||||
* doesn't have the full event (e.g. a message from before SnowLuma was running,
|
||||
* or one it never observed). Fetches just the quoted message from the server —
|
||||
* group via `SsoGetGroupMsg`, c2c via `SsoGetC2cMsg`, both through the shared
|
||||
* or one it never observed). Fetches the quoted message from the server —
|
||||
* group via `SsoGetGroupMsg`, C2C via timestamp roaming, both through the shared
|
||||
* history throttle gate — and persists it under the SAME id the reply resolves
|
||||
* to, so a subsequent `get_msg` (or quote lookup) hits.
|
||||
* to, so a subsequent `get_msg` (or quote lookup) hits. Private replies carry
|
||||
* the quoted sender's local sequence, so they are matched through a timestamp
|
||||
* roam page rather than incorrectly used as an NT-sequence range anchor.
|
||||
*
|
||||
* No-op when: the event isn't a group/friend message, has no reply, the target
|
||||
* is already stored, the uid can't be resolved, the fetch returns nothing, or
|
||||
@@ -347,15 +356,29 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
const replySeq = reply?.replySeq ?? 0;
|
||||
if (replySeq <= 0) return;
|
||||
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
const targetId = hashMessageIdInt32(replySeq, session, eventName);
|
||||
const quotedSender = reply?.replySenderUin ?? (isGroup ? 0 : session);
|
||||
const eventName = isGroup
|
||||
? GROUP_MESSAGE_EVENT
|
||||
: privateMessageEventName(quotedSender === ref.selfId, false);
|
||||
const resolvedId = ref.converterCtx.messageIdResolver?.(
|
||||
isGroup,
|
||||
session,
|
||||
replySeq,
|
||||
eventName,
|
||||
reply?.replyTime && reply.replyTime > 0
|
||||
? reply.replyTime
|
||||
: Number.MAX_SAFE_INTEGER,
|
||||
);
|
||||
const targetId = Number.isInteger(resolvedId) && resolvedId !== 0
|
||||
? resolvedId as number
|
||||
: hashMessageIdInt32(replySeq, session, eventName);
|
||||
if (ref.messageStore.findEvent(targetId)) return; // Tier 0: already have the full event
|
||||
|
||||
// Tier 1: fetch the quoted message from the server, keyed under the exact id
|
||||
// the reply resolves to (replySeq is origSeqs[0] == the quoted message's own
|
||||
// head.sequence, so this matches how it was/would be stored). A c2c message
|
||||
// the bot itself sent converts with user_id=self but is still keyed under the
|
||||
// reply's session (the peer), so get_msg(targetId) hits.
|
||||
// the reply resolves to. Groups can query `replySeq` directly. C2C replies
|
||||
// carry a sender-local client sequence, while SsoGetC2cMsg ranges use the
|
||||
// conversation-wide NT sequence; use the quote time as a roam cursor and
|
||||
// match both direction and client sequence instead.
|
||||
try {
|
||||
let fetched: GroupMessage | FriendMessage | null = null;
|
||||
if (isGroup) {
|
||||
@@ -363,14 +386,57 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
} else {
|
||||
const friendUid = await ref.bridge.resolveUserUid(session);
|
||||
if (friendUid) {
|
||||
fetched = await ref.bridge.apis.message.getC2cMessageBySeq(friendUid, replySeq, ref.selfId);
|
||||
const quoteTime = reply?.replyTime && reply.replyTime > 0
|
||||
? reply.replyTime
|
||||
: event.time;
|
||||
const beforeTime = Math.min(0xffff_ffff, Math.max(1, quoteTime + 1));
|
||||
const candidates = await ref.bridge.apis.message.getC2cLatestHistory(
|
||||
friendUid,
|
||||
20,
|
||||
ref.selfId,
|
||||
beforeTime,
|
||||
);
|
||||
const quotedSentBySelf = quotedSender === ref.selfId;
|
||||
fetched = [...candidates].reverse().find((candidate) => (
|
||||
(candidate.clientSeq ?? candidate.msgSeq) === replySeq
|
||||
&& (candidate.senderUin === ref.selfId) === quotedSentBySelf
|
||||
&& (!reply?.replyTime || candidate.time <= reply.replyTime)
|
||||
)) ?? null;
|
||||
}
|
||||
}
|
||||
if (fetched) {
|
||||
const json = await convertEvent(ref.converterCtx, fetched);
|
||||
if (json) {
|
||||
json.message_id = targetId;
|
||||
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, json);
|
||||
if (fetched.kind === 'group_message') {
|
||||
ref.messageStore.storeEvent(targetId, true, session, replySeq, eventName, json);
|
||||
} else {
|
||||
const serverSequence = fetched.ntMsgSeq ?? 0;
|
||||
const sequenceAuthoritative = fetched.sequenceAuthoritative !== false
|
||||
&& serverSequence > 0;
|
||||
ref.messageStore.storeMeta(targetId, {
|
||||
isGroup: false,
|
||||
targetId: session,
|
||||
sequence: serverSequence,
|
||||
sequenceAuthoritative,
|
||||
eventName,
|
||||
clientSequence: fetched.clientSeq ?? fetched.msgSeq,
|
||||
privateDirection: fetched.senderUin === ref.selfId
|
||||
? 'outgoing'
|
||||
: 'incoming',
|
||||
random: fetched.msgId,
|
||||
timestamp: fetched.time,
|
||||
});
|
||||
ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
false,
|
||||
session,
|
||||
serverSequence,
|
||||
eventName,
|
||||
json,
|
||||
{ sequenceAuthoritative },
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -381,13 +447,13 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
// Tier 2: reconstruct from the quoted message's own elements, which the push
|
||||
// embeds in SrcMsg.elems — no server round-trip. Covers messages the server
|
||||
// won't return (expired, self-c2c, file-only) but whose content rode along.
|
||||
const quotedSender = reply?.replySenderUin ?? (isGroup ? 0 : session);
|
||||
if (reply?.replyElements?.length) {
|
||||
try {
|
||||
const segments = await elementsToOneBotSegments(
|
||||
reply.replyElements, isGroup, session,
|
||||
ref.converterCtx.imageUrlResolver, ref.converterCtx.mediaUrlResolver,
|
||||
ref.converterCtx.messageIdResolver, ref.converterCtx.mediaSegmentSink,
|
||||
ref.selfId,
|
||||
) as JsonArray;
|
||||
const fallback = buildBackfillEvent(targetId, replySeq, quotedSender,
|
||||
reply.replyTime ?? 0, segments, ref.selfId, isGroup, session);
|
||||
@@ -437,10 +503,11 @@ function buildBackfillEvent(
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
): JsonObject {
|
||||
const sentBySelf = senderUin === selfId;
|
||||
const common = {
|
||||
time: timestamp || Math.floor(Date.now() / 1000),
|
||||
self_id: selfId,
|
||||
post_type: 'message' as const,
|
||||
post_type: sentBySelf ? 'message_sent' as const : 'message' as const,
|
||||
message_id: messageId,
|
||||
message_seq: msgSeq,
|
||||
message: segments,
|
||||
@@ -458,29 +525,66 @@ function buildBackfillEvent(
|
||||
anonymous: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
const privateEvent: JsonObject = {
|
||||
...common,
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
user_id: senderUin,
|
||||
sender: { user_id: senderUin, nickname: '', sex: 'unknown', age: 0 },
|
||||
};
|
||||
if (sentBySelf) privateEvent.target_id = sessionId;
|
||||
return privateEvent;
|
||||
}
|
||||
|
||||
// Persist a converted history event so reply / get_msg / future listing resolve
|
||||
// it. Private history callers provide the conversation peer because `user_id`
|
||||
// identifies the sender and equals the bot account on outgoing messages.
|
||||
function persistHistoryEvent(store: MessageStore, event: JsonObject, privatePeerId?: number): void {
|
||||
function persistHistoryEvent(
|
||||
store: MessageStore,
|
||||
event: JsonObject,
|
||||
privatePeerId?: number,
|
||||
source?: FriendMessage,
|
||||
): void {
|
||||
const messageId = toHistInt(event.message_id);
|
||||
if (messageId === 0) return;
|
||||
const isGroup = event.message_type === 'group';
|
||||
const sessionId = isGroup
|
||||
? toHistInt(event.group_id)
|
||||
: (privatePeerId && privatePeerId > 0 ? privatePeerId : toHistInt(event.user_id));
|
||||
const sequence = toHistInt(event.message_seq);
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
const messageSequence = toHistInt(event.message_seq);
|
||||
const sequence = source?.ntMsgSeq ?? messageSequence;
|
||||
const sequenceAuthoritative = source?.sequenceAuthoritative !== false && sequence > 0;
|
||||
const isOutgoingPrivate = !isGroup && source?.senderUin === source?.selfUin;
|
||||
const eventName = isGroup
|
||||
? GROUP_MESSAGE_EVENT
|
||||
: source
|
||||
? privateMessageEventName(isOutgoingPrivate, sequenceAuthoritative)
|
||||
: privateMessageEventName(event.post_type === 'message_sent', false);
|
||||
if (sessionId === 0) return;
|
||||
store.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
|
||||
if (!isGroup && source) {
|
||||
store.storeMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: sessionId,
|
||||
sequence,
|
||||
sequenceAuthoritative,
|
||||
eventName,
|
||||
clientSequence: source.clientSeq ?? source.msgSeq,
|
||||
privateDirection: source.senderUin === source.selfUin
|
||||
? 'outgoing'
|
||||
: 'incoming',
|
||||
random: source.msgId,
|
||||
timestamp: source.time,
|
||||
});
|
||||
}
|
||||
store.storeEvent(
|
||||
messageId,
|
||||
isGroup,
|
||||
sessionId,
|
||||
sequence,
|
||||
eventName,
|
||||
event,
|
||||
{ sequenceAuthoritative },
|
||||
);
|
||||
}
|
||||
|
||||
function toHistInt(value: unknown): number {
|
||||
@@ -563,8 +667,10 @@ async function finalizeSend(
|
||||
elements: MessageElement[],
|
||||
reportEcho = false,
|
||||
): Promise<MessageSendResult> {
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
const sequenceAuthoritative = Number.isInteger(receipt.sequence) && receipt.sequence > 0;
|
||||
const eventName = isGroup
|
||||
? GROUP_MESSAGE_EVENT
|
||||
: privateMessageEventName(true, sequenceAuthoritative);
|
||||
const opaqueMessageId = receipt.messageId ?? 0;
|
||||
// Ordinary sends use QQ's real sequence so receive/send paths derive the same
|
||||
// OneBot id. OIDB-only sends (notably group files) have no QQ sequence: keep
|
||||
@@ -574,7 +680,11 @@ async function finalizeSend(
|
||||
? hashMessageIdInt32(receipt.sequence, targetId, eventName)
|
||||
: Number.isInteger(opaqueMessageId) && opaqueMessageId !== 0
|
||||
? opaqueMessageId
|
||||
: hashMessageIdInt32(0, targetId, eventName);
|
||||
: hashMessageIdInt32(
|
||||
isGroup ? 0 : receipt.clientSequence,
|
||||
targetId,
|
||||
eventName,
|
||||
);
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
isGroup,
|
||||
targetId,
|
||||
@@ -582,6 +692,7 @@ async function finalizeSend(
|
||||
sequenceAuthoritative,
|
||||
eventName,
|
||||
clientSequence: receipt.clientSequence,
|
||||
...(isGroup ? {} : { privateDirection: 'outgoing' as const }),
|
||||
random: receipt.random,
|
||||
timestamp: receipt.timestamp,
|
||||
});
|
||||
@@ -590,7 +701,9 @@ async function finalizeSend(
|
||||
sessionId: targetId,
|
||||
messageId,
|
||||
sequence: receipt.sequence,
|
||||
messageSequence: isGroup ? receipt.sequence : receipt.clientSequence,
|
||||
sequenceAuthoritative,
|
||||
eventName,
|
||||
timestamp: receipt.timestamp,
|
||||
elements,
|
||||
});
|
||||
@@ -605,8 +718,12 @@ async function cacheSelfSentMessage(
|
||||
isGroup: boolean;
|
||||
sessionId: number; // groupId or peer userId
|
||||
messageId: number;
|
||||
/** QQ server/NT sequence used for protocol operations and history ordering. */
|
||||
sequence: number;
|
||||
/** Public OneBot message_seq (sender-local client sequence for C2C). */
|
||||
messageSequence: number;
|
||||
sequenceAuthoritative: boolean;
|
||||
eventName: string;
|
||||
timestamp: number;
|
||||
elements: MessageElement[];
|
||||
},
|
||||
@@ -616,7 +733,9 @@ async function cacheSelfSentMessage(
|
||||
sessionId,
|
||||
messageId,
|
||||
sequence,
|
||||
messageSequence,
|
||||
sequenceAuthoritative,
|
||||
eventName,
|
||||
timestamp,
|
||||
elements,
|
||||
} = options;
|
||||
@@ -636,9 +755,17 @@ async function cacheSelfSentMessage(
|
||||
// resolver is async and bound to the receive pipeline; skipping it
|
||||
// means /get_msg returns the segment with the original `file` path
|
||||
// and an empty `url`, which is what Lagrange does too.
|
||||
const segments = await elementsToOneBotSegments(elements, isGroup, sessionId) as JsonArray;
|
||||
const segments = await elementsToOneBotSegments(
|
||||
elements,
|
||||
isGroup,
|
||||
sessionId,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
ref.selfId,
|
||||
) as JsonArray;
|
||||
const raw = segmentsToRawMessage(segments);
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
const selfId = ref.selfId;
|
||||
|
||||
const event: JsonObject = {
|
||||
@@ -648,7 +775,7 @@ async function cacheSelfSentMessage(
|
||||
message_type: isGroup ? 'group' : 'private',
|
||||
sub_type: isGroup ? 'normal' : 'friend',
|
||||
message_id: messageId,
|
||||
message_seq: sequence,
|
||||
message_seq: messageSequence,
|
||||
user_id: selfId, // sender = self
|
||||
message: segments,
|
||||
raw_message: raw,
|
||||
|
||||
@@ -126,6 +126,8 @@ export interface MessageMeta {
|
||||
sequenceAuthoritative: boolean;
|
||||
eventName: string;
|
||||
clientSequence: number;
|
||||
/** Sender direction for friend messages; absent for groups/temp/legacy rows. */
|
||||
privateDirection?: 'incoming' | 'outgoing';
|
||||
random: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user