feat(onebot): tiered reply backfill + quoted-file recovery for get_msg (#128)
Harvests the sound ideas from PR #128 while KEEPING origSeqs[0] as the c2c reply sequence (on-target capture in #114/#124 proved origSeqs[0] == the quoted message's head.sequence; pbReserve.friendSequence is a small unrelated counter that makes reply.id miss). The PR's friendSequence override is intentionally NOT taken. - rich-body-decoder: enrich the reply element with replySenderUin/replyTime and the quoted message's own decoded elements (SrcMsg.elems, field 5); recover a c2c quoted FILE from sourceMsg (field 9 -> RichText.notOnlineFile) when elems carried none, so a quoted file survives into get_msg (#124). - backfillReplyTarget: tiered fallback — Tier 0 local store, Tier 1 server fetch (correct seq = origSeqs[0]), Tier 2 reconstruct from the embedded quoted elements (no round-trip), Tier 3 minimal '[引用消息]' placeholder so get_msg never returns 'message not found'. - to-segment: per-element try/catch (logged, not silent) so one bad element doesn't drop the whole message. - actions/message: log get_msg misses. - tests: fix request-actions getGroupInviteCardSequence mock (gap from #125); cover backfill Tier 2 (reconstruct) + Tier 3 (placeholder); flip the stale c2c reply test to assert origSeqs[0] (was asserting the disproven friendSequence). Validated on-target (Docker): get_msg on group reply, private text reply, and a private quoted FILE all return correct content (file with name/size/id); full onebot + protocol suites green.
This commit is contained in:
8 files changed
+189
-34
No files matched your search
@@ -1,8 +1,11 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { defineAction, groupAction, registerActions, f } from '../action-kit';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
/**
|
||||
* Re-sign image URLs in a stored message event at read time. `get_msg`
|
||||
* returns a copy persisted when the message first arrived, and image rkeys
|
||||
@@ -89,7 +92,10 @@ export const actions = [
|
||||
params: { message_id: f.messageId() },
|
||||
run: async (p, ctx) => {
|
||||
const data = ctx.getMessage(p.message_id);
|
||||
if (!data) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
if (!data) {
|
||||
log.warn('[get_msg] miss message_id=%d', p.message_id);
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
}
|
||||
const result: JsonObject = { ...data };
|
||||
delete result.post_type;
|
||||
delete result.self_id;
|
||||
|
||||
@@ -7,6 +7,9 @@ import type {
|
||||
MessageIdResolver,
|
||||
} from './index';
|
||||
import { resolveReplyId } from './utils';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
export async function elementsToJson(
|
||||
elements: MessageElement[],
|
||||
@@ -19,10 +22,17 @@ export async function elementsToJson(
|
||||
): Promise<JsonArray> {
|
||||
const result: JsonArray = [];
|
||||
for (const element of elements) {
|
||||
result.push(await elementToSegment(
|
||||
element, isGroup, sessionId,
|
||||
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
|
||||
));
|
||||
// One malformed element shouldn't drop the whole message — skip it (with a
|
||||
// breadcrumb) and keep converting the rest.
|
||||
try {
|
||||
result.push(await elementToSegment(
|
||||
element, isGroup, sessionId,
|
||||
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
|
||||
));
|
||||
} catch (err) {
|
||||
log.warn('segment convert skipped type=%s (%s)', element.type,
|
||||
err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -210,30 +210,103 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
const targetId = hashMessageIdInt32(replySeq, session, eventName);
|
||||
if (ref.messageStore.findEvent(targetId)) return; // already have the full event
|
||||
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.
|
||||
try {
|
||||
let fetched: GroupMessage | FriendMessage | null;
|
||||
let fetched: GroupMessage | FriendMessage | null = null;
|
||||
if (isGroup) {
|
||||
fetched = await ref.bridge.apis.message.getGroupMessageBySeq(session, replySeq, ref.selfId);
|
||||
} else {
|
||||
const friendUid = await ref.bridge.resolveUserUid(session);
|
||||
if (!friendUid) return;
|
||||
fetched = await ref.bridge.apis.message.getC2cMessageBySeq(friendUid, replySeq, ref.selfId);
|
||||
if (friendUid) {
|
||||
fetched = await ref.bridge.apis.message.getC2cMessageBySeq(friendUid, replySeq, ref.selfId);
|
||||
}
|
||||
}
|
||||
if (fetched) {
|
||||
const json = await convertEvent(ref.converterCtx, fetched);
|
||||
if (json) {
|
||||
json.message_id = targetId;
|
||||
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, json);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!fetched) return;
|
||||
|
||||
const json = await convertEvent(ref.converterCtx, fetched);
|
||||
if (!json) return;
|
||||
// Key under the exact id the reply resolves to (and the reply's session) so
|
||||
// get_msg(targetId) hits regardless of who sent the quoted message: a c2c
|
||||
// message the bot itself sent converts with user_id=self and would
|
||||
// otherwise key under a different session than the reply's peer.
|
||||
json.message_id = targetId;
|
||||
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, json);
|
||||
} catch (err) {
|
||||
log.warn('reply-target backfill failed (%s)', err instanceof Error ? err.message : String(err));
|
||||
log.warn('reply-target backfill tier-1 failed (%s)', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
|
||||
// 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,
|
||||
) as JsonArray;
|
||||
const fallback = buildBackfillEvent(targetId, replySeq, quotedSender,
|
||||
reply.replyTime ?? 0, segments, ref.selfId, isGroup, session);
|
||||
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, fallback);
|
||||
return;
|
||||
} catch (err) {
|
||||
log.warn('reply-target backfill tier-2 failed (%s)', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
// Tier 3: minimal `[引用消息]` placeholder so get_msg(reply_id) never returns
|
||||
// "message not found" — an approval bot that fires get_msg right after seeing
|
||||
// the reply gets a well-formed (if sparse) event instead of an error.
|
||||
const placeholder = buildBackfillEvent(targetId, replySeq, quotedSender,
|
||||
reply?.replyTime ?? 0, [{ type: 'text', data: { text: '[引用消息]' } }],
|
||||
ref.selfId, isGroup, session);
|
||||
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, placeholder);
|
||||
}
|
||||
|
||||
// Build a stored-message event for a backfilled reply target (Tier 2/3).
|
||||
function buildBackfillEvent(
|
||||
messageId: number,
|
||||
msgSeq: number,
|
||||
senderUin: number,
|
||||
timestamp: number,
|
||||
segments: JsonArray,
|
||||
selfId: number,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
): JsonObject {
|
||||
const common = {
|
||||
time: timestamp || Math.floor(Date.now() / 1000),
|
||||
self_id: selfId,
|
||||
post_type: 'message' as const,
|
||||
message_id: messageId,
|
||||
message_seq: msgSeq,
|
||||
message: segments,
|
||||
raw_message: segmentsToRawMessage(segments),
|
||||
font: 0,
|
||||
};
|
||||
if (isGroup) {
|
||||
return {
|
||||
...common,
|
||||
message_type: 'group',
|
||||
sub_type: 'normal',
|
||||
group_id: sessionId,
|
||||
user_id: senderUin,
|
||||
sender: { user_id: senderUin, nickname: '', card: '', role: 'member', sex: 'unknown', age: 0 },
|
||||
anonymous: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...common,
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
user_id: senderUin,
|
||||
sender: { user_id: senderUin, nickname: '', sex: 'unknown', age: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
// Persist a converted history event so reply / get_msg / future listing resolve
|
||||
|
||||
@@ -145,7 +145,30 @@ describe('backfillReplyTarget', () => {
|
||||
expect(store.storeEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not store when the server has nothing at that sequence', async () => {
|
||||
it('reconstructs from replyElements when the server has nothing (tier 2)', async () => {
|
||||
const store = fakeStore(false);
|
||||
const getGroupMessageBySeq = vi.fn(async () => null);
|
||||
const ref = {
|
||||
selfId: SELF, converterCtx, messageStore: store,
|
||||
bridge: { apis: { message: { getGroupMessageBySeq } }, resolveUserUid: vi.fn() },
|
||||
} as any;
|
||||
const event = {
|
||||
kind: 'group_message', time: 1, selfUin: SELF, groupId: 700, senderUin: 900,
|
||||
senderNick: '', senderCard: '', senderRole: 'member', msgSeq: 999, msgId: 2,
|
||||
elements: [{ type: 'reply', replySeq: 123, replySenderUin: 800, replyElements: [{ type: 'text', text: 'quoted' }] }],
|
||||
} as any;
|
||||
|
||||
await backfillReplyTarget(ref, event);
|
||||
|
||||
const targetId = hashMessageIdInt32(123, 700, GROUP_MESSAGE_EVENT);
|
||||
expect(store.storeEvent).toHaveBeenCalledOnce();
|
||||
expect(store.storeEvent).toHaveBeenCalledWith(
|
||||
targetId, true, 700, 123, GROUP_MESSAGE_EVENT,
|
||||
expect.objectContaining({ message_id: targetId, message_type: 'group', user_id: 800 }),
|
||||
);
|
||||
});
|
||||
|
||||
it('stores a [引用消息] placeholder when server fetch and replyElements both miss (tier 3)', async () => {
|
||||
const store = fakeStore(false);
|
||||
const getGroupMessageBySeq = vi.fn(async () => null);
|
||||
const ref = {
|
||||
@@ -156,6 +179,11 @@ describe('backfillReplyTarget', () => {
|
||||
await backfillReplyTarget(ref, groupEvent(123));
|
||||
|
||||
expect(getGroupMessageBySeq).toHaveBeenCalledOnce();
|
||||
expect(store.storeEvent).not.toHaveBeenCalled();
|
||||
const targetId = hashMessageIdInt32(123, 700, GROUP_MESSAGE_EVENT);
|
||||
expect(store.storeEvent).toHaveBeenCalledOnce();
|
||||
expect(store.storeEvent).toHaveBeenCalledWith(
|
||||
targetId, true, 700, 123, GROUP_MESSAGE_EVENT,
|
||||
expect.objectContaining({ message_id: targetId, message_type: 'group' }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ const APIS_ROUTING: Record<string, string> = {
|
||||
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
|
||||
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
|
||||
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
|
||||
getGroupInviteCardSequence: 'contacts',
|
||||
};
|
||||
|
||||
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
|
||||
@@ -72,6 +73,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
|
||||
fetchGroupRequests: vi.fn(async () => [
|
||||
fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 97, eventType: 8, filtered: false }),
|
||||
]),
|
||||
getGroupInviteCardSequence: vi.fn(() => null),
|
||||
apis: { groupAdmin: { setAddRequest } } as any,
|
||||
});
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ export interface MessageElement {
|
||||
replySenderUin?: number; // For reply: original sender's UIN
|
||||
replyTime?: number; // For reply: original message timestamp
|
||||
replyRandom?: number; // For reply: original message random/msgId
|
||||
replyElements?: MessageElement[]; // Decoded elements of the quoted message (SrcMsg.elems) — lets a backfill reconstruct it for get_msg without a server round-trip
|
||||
url?: string;
|
||||
thumbUrl?: string;
|
||||
subType?: number;
|
||||
|
||||
@@ -10,7 +10,7 @@ import type {
|
||||
QFaceExtra,
|
||||
QSmallFaceExtra,
|
||||
} from '@snowluma/proto-defs/element';
|
||||
import type { FileExtra, MessageBody, RichText } from '@snowluma/proto-defs/message';
|
||||
import type { FileExtra, MessageBody, PushMsgBody as PushMsgBodyFull, RichText } from '@snowluma/proto-defs/message';
|
||||
import { decompressData, makeImageUrl } from './helpers';
|
||||
|
||||
type ElemDecoded = Elem;
|
||||
@@ -60,8 +60,40 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
// the earlier `friendSequence` override made reply.id != the quoted
|
||||
// message_id: get_msg(reply_id) missed and a quoted File's content came
|
||||
// back empty.
|
||||
const replySeq = elem.srcMsg.origSeqs?.[0] ?? 0;
|
||||
if (replySeq > 0) result.push({ type: 'reply', replySeq });
|
||||
const src = elem.srcMsg;
|
||||
const replySeq = src.origSeqs?.[0] ?? 0;
|
||||
if (replySeq > 0) {
|
||||
const reply: MessageElement = { type: 'reply', replySeq };
|
||||
if (src.senderUin) reply.replySenderUin = Number(src.senderUin);
|
||||
if (src.time) reply.replyTime = src.time;
|
||||
// Decode the quoted message's own elements (SrcMsg.elems, field 5) so a
|
||||
// backfill can reconstruct it locally if it isn't in the store / server.
|
||||
if (src.elemsRaw?.length) {
|
||||
const decoded: ElemDecoded[] = [];
|
||||
for (const raw of src.elemsRaw) {
|
||||
try { decoded.push(protobuf_decode<Elem>(raw)); } catch { /* skip corrupt elem */ }
|
||||
}
|
||||
if (decoded.length) reply.replyElements = convertElements(decoded);
|
||||
}
|
||||
// A C2C quoted FILE lives in RichText.notOnlineFile (message level), not
|
||||
// in elems[] — recover it from sourceMsg (field 9) when elems carried no
|
||||
// file, so a quoted file's content survives into get_msg (#124).
|
||||
if (src.sourceMsg?.length && !reply.replyElements?.some((e) => e.type === 'file')) {
|
||||
try {
|
||||
const pmsg = protobuf_decode<PushMsgBodyFull>(src.sourceMsg);
|
||||
const nof = pmsg?.body?.richText?.notOnlineFile;
|
||||
if (nof?.fileName) {
|
||||
(reply.replyElements ??= []).push({
|
||||
type: 'file',
|
||||
fileName: nof.fileName,
|
||||
fileSize: nof.fileSize !== undefined ? Number(nof.fileSize) : 0,
|
||||
fileId: nof.fileUuid ?? '',
|
||||
});
|
||||
}
|
||||
} catch { /* sourceMsg decode is best-effort */ }
|
||||
}
|
||||
result.push(reply);
|
||||
}
|
||||
sawReply = true;
|
||||
}
|
||||
|
||||
|
||||
@@ -165,13 +165,15 @@ describe('decodeRichBody / market face', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// Reply identity for c2c: a friend's reply carries the per-sender
|
||||
// clientSequence in srcMsg.origSeqs[0], but the *canonical* replied-to sequence
|
||||
// (the one the original message is keyed by) is srcMsg.pbReserve.friendSequence.
|
||||
// Reading origSeqs[0] made get_msg on the quoted message miss ("无法解析申请信息").
|
||||
describe('decodeRichBody / reply uses friendSequence for c2c', () => {
|
||||
const CLIENT_SEQ = 23188; // origSeqs[0] — per-sender clientSequence
|
||||
const FRIEND_SEQ = 888; // pbReserve.friendSequence — canonical replied-to seq
|
||||
// Reply identity for c2c: the replied-to sequence is srcMsg.origSeqs[0] for BOTH
|
||||
// group and c2c. On-target capture (#114 / #124) proved origSeqs[0] equals the
|
||||
// quoted message's head.sequence — i.e. the seq its message_id is hashed from —
|
||||
// while pbReserve.friendSequence is a small friend-relationship counter that does
|
||||
// NOT match (e.g. 25 vs a head.sequence of 12707). Reading friendSequence made
|
||||
// reply.id != the quoted message_id, so get_msg(reply_id) missed.
|
||||
describe('decodeRichBody / reply uses origSeqs[0] for c2c', () => {
|
||||
const CLIENT_SEQ = 23188; // origSeqs[0] — the quoted message's head.sequence
|
||||
const FRIEND_SEQ = 888; // pbReserve.friendSequence — a small unrelated counter, ignored
|
||||
|
||||
function replyBody(): MessageBody {
|
||||
return {
|
||||
@@ -188,8 +190,9 @@ describe('decodeRichBody / reply uses friendSequence for c2c', () => {
|
||||
};
|
||||
}
|
||||
|
||||
it('c2c: replySeq = friendSequence, not origSeqs[0]', () => {
|
||||
expect(decodeRichBody(replyBody(), false)).toContainEqual({ type: 'reply', replySeq: FRIEND_SEQ });
|
||||
it('c2c: replySeq = origSeqs[0], not friendSequence (#114/#124)', () => {
|
||||
expect(decodeRichBody(replyBody(), false)).toContainEqual({ type: 'reply', replySeq: CLIENT_SEQ });
|
||||
expect(FRIEND_SEQ).not.toBe(CLIENT_SEQ); // guard: the two must differ for this to mean anything
|
||||
});
|
||||
|
||||
it('group: replySeq = origSeqs[0] (friendSequence ignored)', () => {
|
||||
|
||||
Reference in new issue
Block a user