feat(onebot): fetch real private (c2c) history from server (#99)

Mirror the group-history fetch for private chats via SsoGetC2cMsg
(trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg, fields per Lagrange:
flat friendUid/start/end request, messages@7 response). get_friend_msg_history
now resolves the anchor sequence + the friend's UID, fetches real history from
the server, converts + persists each message, and falls back to the local
store on unknown anchor / no uid / empty / error.

- protocol: fetchC2cMessageRange (decodes via the friend decoder).
- core: the group + c2c fetch now share a generic walkBackHistory loop
  (same throttle gate + caps); added MessageApi.getC2cHistory.
- onebot: getFriendHistory + a generalized persistHistoryEvent (keys private
  by sender uin, exactly like the live path — so reply to old private
  messages resolves too).

Tests: SsoGetC2cMsg request/response round-trip + friend-decode reuse.
This commit is contained in:
DrSmoothl committed 2026-06-14 20:15:38 +08:00
1 parent 987ac09896
commit 58c02d415f
9 files changed
+288 -41

No files matched your search

+58 -31
View File
@@ -10,7 +10,7 @@ import type {
} from '@snowluma/proto-defs/oidb-actions/base';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import { fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
// `Bridge` is imported as a type only so we can narrow `ctx` back to
@@ -26,6 +26,7 @@ import type { Bridge, SendMessageReceipt } from '../bridge';
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
// ── Group-history fetch guards (the server frequency-limits / kicks abusive
// pulls, so keep each request small, bound the loop, and space the sends). ──
@@ -50,6 +51,47 @@ function throttleHistory(): Promise<void> {
return run;
}
/**
* Shared walk-back loop for group + c2c history: pull HISTORY_CHUNK_SEQ-wide
* windows ending at `endSeq`, throttled, walking strictly backward (handling a
* server-side short cap via the oldest sequence actually returned), dedup by
* sequence, until `count` (capped) is gathered or the floor is reached. Returns
* the newest `want` items oldest→newest.
*/
async function walkBackHistory<T extends { msgSeq: number }>(
endSeq: number,
count: number,
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
): Promise<T[]> {
if (!(endSeq > 0)) return [];
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
const collected = new Map<number, T>(); // dedup by sequence
let curEnd = endSeq;
for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want && curEnd >= 1; i++) {
const start = Math.max(1, curEnd - HISTORY_CHUNK_SEQ + 1);
await throttleHistory();
let batch: T[];
try {
batch = await fetchWindow(start, curEnd);
} catch {
break; // network/decode error — return whatever we have so far
}
if (batch.length > 0) {
let minSeq = curEnd;
for (const ev of batch) {
collected.set(ev.msgSeq, ev);
if (ev.msgSeq < minSeq) minSeq = ev.msgSeq;
}
curEnd = minSeq - 1; // strictly below the oldest returned (covers short caps)
} else {
curEnd = start - 1; // empty window (recalled/absent seqs) — skip past it
}
}
const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq);
return all.slice(-want); // newest `want`, oldest→newest
}
export class MessageApi {
constructor(private readonly ctx: BridgeContext) { }
@@ -363,37 +405,22 @@ export class MessageApi {
* kicked). Returns decoded `group_message` events oldest→newest.
*/
async getGroupHistory(groupUin: number, endSeq: number, count: number, selfUin = 0): Promise<GroupMessage[]> {
if (!(groupUin > 0) || !(endSeq > 0)) return [];
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
if (!(groupUin > 0)) return [];
return walkBackHistory(endSeq, count, (start, end) =>
fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, start, end));
}
const collected = new Map<number, GroupMessage>(); // dedup by sequence
let curEnd = endSeq;
for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want && curEnd >= 1; i++) {
const start = Math.max(1, curEnd - HISTORY_CHUNK_SEQ + 1);
await throttleHistory();
let batch: GroupMessage[];
try {
batch = await fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, start, curEnd);
} catch {
break; // network/decode error — return whatever we have so far
}
if (batch.length > 0) {
let minSeq = curEnd;
for (const ev of batch) {
collected.set(ev.msgSeq, ev);
if (ev.msgSeq < minSeq) minSeq = ev.msgSeq;
}
// Continue strictly below the OLDEST sequence the server actually
// returned — covers the case where the server caps a window short.
curEnd = minSeq - 1;
} else {
// Empty window (a gap of recalled/absent seqs) — skip past it.
curEnd = start - 1;
}
}
const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq);
return all.slice(-want); // newest `want`, oldest→newest
/**
* Fetch real private (c2c) history from the server (`SsoGetC2cMsg`), ending
* at and including `endSeq`. Same rate-limit + data-volume guards as the
* group variant (they share the throttle gate). `friendUid` is the
* conversation peer's UID. Returns decoded `friend_message` events
* oldest→newest.
*/
async getC2cHistory(friendUid: string, endSeq: number, count: number, selfUin = 0): Promise<FriendMessage[]> {
if (!friendUid) return [];
return walkBackHistory(endSeq, count, (start, end) =>
fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end));
}
}
+2 -2
View File
@@ -26,7 +26,7 @@ import {
deleteMessage,
forwardSingleMessage,
getForwardMessage,
getFriendMsgHistory,
getFriendHistory,
getGroupHistory,
sendGroupForwardMessage,
sendGroupMessage,
@@ -77,7 +77,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId),
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
getGroupMsgHistory: (groupId, messageId, count) => getGroupHistory(ref, groupId, messageId, count),
getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count),
getFriendMsgHistory: (userId, messageId, count) => getFriendHistory(ref, userId, messageId, count),
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
getDownloadRKeys: () => getDownloadRKeys(bridge),
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
+73 -8
View File
@@ -65,7 +65,7 @@ export async function getFriendMsgHistory(
}
// Deps the server-backed history fetch needs from the instance context.
interface GroupHistoryRef {
interface HistoryRef {
bridge: BridgeInterface;
messageStore: MessageStore;
converterCtx: ConverterContext;
@@ -82,7 +82,7 @@ interface GroupHistoryRef {
* fetch is unavailable or empty.
*/
export async function getGroupHistory(
ref: GroupHistoryRef,
ref: HistoryRef,
groupId: number,
messageId: number | undefined,
count: number | undefined,
@@ -110,8 +110,8 @@ export async function getGroupHistory(
for (const ev of events) {
const json = await convertEvent(ref.converterCtx, ev);
if (!json || json.message_type !== 'group') continue;
persistGroupHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing
out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path)
persistHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing
out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path)
}
if (out.length > 0) return out;
} catch (err) {
@@ -122,12 +122,77 @@ export async function getGroupHistory(
return getGroupMsgHistory(ref.messageStore, groupId, messageId, count);
}
function persistGroupHistoryEvent(store: MessageStore, event: JsonObject): void {
/**
* 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. Falls back to the
* local store on unknown anchor / no uid / empty / error.
*/
export async function getFriendHistory(
ref: HistoryRef,
userId: number,
messageId: number | undefined,
count: number | undefined,
): Promise<JsonObject[]> {
if (!Number.isInteger(userId) || userId <= 0) return [];
const want = normalizeHistoryCount(count);
let anchorSeq = 0;
if (Number.isInteger(messageId) && messageId !== 0) {
const meta = ref.messageStore.findMeta(messageId as number);
// A c2c conversation seq is shared across both directions, but self-sent
// messages are keyed under our own uin — so accept any private anchor by
// sequence rather than requiring targetId === userId.
if (!meta || meta.isGroup || meta.sequence <= 0) {
return getFriendMsgHistory(ref.messageStore, userId, messageId, count);
}
anchorSeq = meta.sequence;
} else {
// Latest observed *inbound* message from this friend (self-sent messages
// are keyed under our own uin, not the recipient, so the store can't give
// "latest sent to this friend"). The c2c sequence is shared across both
// directions, so the fetch window around this anchor still includes recent
// self-sent messages — only ones strictly newer than the last inbound are
// missed on the unparameterized first page (a paged client catches up).
const latest = ref.messageStore.listSessionEvents(false, userId, 1);
anchorSeq = latest.length ? toHistInt(latest[latest.length - 1].message_seq) : 0;
}
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);
const out: JsonObject[] = [];
for (const ev of events) {
const json = await convertEvent(ref.converterCtx, ev);
if (!json || json.message_type !== 'private') continue;
persistHistoryEvent(ref.messageStore, json);
out.push(sanitizeMessageEventForApi(json));
}
if (out.length > 0) return out;
}
} catch (err) {
log.warn('friend history server fetch failed (%s); using local store', err instanceof Error ? err.message : String(err));
}
}
return getFriendMsgHistory(ref.messageStore, userId, messageId, count);
}
// Persist a converted history event so reply / get_msg / future listing resolve
// it — keyed exactly like the live pipeline (group → group_id, private → the
// sender uin carried in user_id).
function persistHistoryEvent(store: MessageStore, event: JsonObject): void {
const messageId = toHistInt(event.message_id);
const sessionId = toHistInt(event.group_id);
if (messageId === 0) return;
const isGroup = event.message_type === 'group';
const sessionId = isGroup ? toHistInt(event.group_id) : toHistInt(event.user_id);
const sequence = toHistInt(event.message_seq);
if (messageId === 0 || sessionId === 0) return;
store.storeEvent(messageId, true, sessionId, sequence, GROUP_MESSAGE_EVENT, event);
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
if (sessionId === 0) return;
store.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
}
function toHistInt(value: unknown): number {
+4
View File
@@ -35,6 +35,10 @@
"types": "./src/get-group-msg.ts",
"default": "./src/get-group-msg.ts"
},
"./get-c2c-msg": {
"types": "./src/get-c2c-msg.ts",
"default": "./src/get-c2c-msg.ts"
},
"./notify": {
"types": "./src/notify.ts",
"default": "./src/notify.ts"
+19
View File
@@ -0,0 +1,19 @@
import type { pb, pb_repeated, uint_32 } from '@snowluma/proton';
import type { PushMsgBody } from './message';
// trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg — fetch private (c2c)
// message history from the server by sequence range. Reference: Lagrange.Core
// Internal/Service/Message/GetC2cMessageService.cs + Packets/Message/Action/
// SsoGetC2cMsg(.Response).cs. The peer is the friend's UID (not uin); the
// response carries the same `PushMsgBody` shape as a live message.
export interface SsoGetC2cMsg {
friendUid?: pb<2, string>;
startSequence?: pb<3, uint_32>;
endSequence?: pb<4, uint_32>;
}
export interface SsoGetC2cMsgResponse {
friendUid?: pb<4, string>;
messages?: pb_repeated<7, PushMsgBody>;
}
+1
View File
@@ -26,6 +26,7 @@ export type * from './element.js';
export type * from './longmsg.js';
export type * from './message.js';
export type * from './get-group-msg.js';
export type * from './get-c2c-msg.js';
export type * from './notify.js';
export type * from './oidb.js';
export type * from './oidb-action.js';
@@ -0,0 +1,56 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SsoGetC2cMsg, SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import type { QQEventVariant } from '../events';
import type { IdentityService } from '../identity-service';
import { buildContextFromMessage } from './context';
import { decodeFriendMessage } from './decoders/friend-message';
export const SSO_GET_C2C_MSG_CMD = 'trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg';
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
interface RawSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
}
/**
* Fetch one [startSeq, endSeq] window of private (c2c) history from the server
* via `SsoGetC2cMsg`, decoding each returned message with the regular friend
* decoder. `friendUid` is the conversation peer's UID. Returns `friend_message`
* events sorted oldest→newest by sequence. One packet per call — the caller
* owns chunking/throttling.
*/
export async function fetchC2cMessageRange(
sender: RawSender,
identity: IdentityService,
selfUin: number,
friendUid: string,
startSeq: number,
endSeq: number,
): Promise<FriendMessage[]> {
if (!friendUid || !(endSeq > 0) || startSeq > endSeq) return [];
const req = protobuf_encode<SsoGetC2cMsg>({
friendUid,
startSequence: startSeq,
endSequence: endSeq,
});
const res = await sender.sendRawPacket(SSO_GET_C2C_MSG_CMD, req);
if (!res.success || !res.gotResponse || !res.responseData) return [];
const decoded = protobuf_decode<SsoGetC2cMsgResponse>(res.responseData);
const messages = decoded?.messages ?? [];
const out: FriendMessage[] = [];
for (const msg of messages) {
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) continue;
for (const ev of decodeFriendMessage(ctx)) {
if (ev.kind === 'friend_message' && ev.msgSeq > 0) out.push(ev);
}
}
out.sort((a, b) => a.msgSeq - b.msgSeq);
return out;
}
+1
View File
@@ -19,6 +19,7 @@ import { PkgType } from './enums';
import { MsgPushRegistry } from './registry';
export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history';
export { SSO_GET_C2C_MSG_CMD, fetchC2cMessageRange } from './fetch-c2c-history';
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
@@ -0,0 +1,74 @@
// Round-trips the SsoGetC2cMsg request/response protos (proton codegen + field
// tags) and the fetched private-history decode path (each returned PushMsgBody
// re-uses the regular friend decoder).
import { describe, expect, it } from 'vitest';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SsoGetC2cMsg, SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import type { IdentityService } from '../../src/identity-service';
import { SSO_GET_C2C_MSG_CMD, fetchC2cMessageRange } from '../../src/msg-push';
const identity = { findFriend: () => undefined } as unknown as IdentityService;
function okResult(data: Uint8Array): SendPacketResult {
return { success: true, gotResponse: true, responseData: data } as SendPacketResult;
}
describe('fetchC2cMessageRange / SsoGetC2cMsg', () => {
it('sends the right command and request field tags', async () => {
let captured: { cmd: string; body: Uint8Array } | null = null;
const sender = {
sendRawPacket: async (cmd: string, body: Uint8Array) => {
captured = { cmd, body };
return okResult(protobuf_encode<SsoGetC2cMsgResponse>({ friendUid: 'u_friend', messages: [] }));
},
};
await fetchC2cMessageRange(sender, identity, 10001, 'u_friend', 100, 120);
expect(captured!.cmd).toBe(SSO_GET_C2C_MSG_CMD);
const req = protobuf_decode<SsoGetC2cMsg>(captured!.body);
expect(req.friendUid).toBe('u_friend');
expect(req.startSequence).toBe(100);
expect(req.endSequence).toBe(120);
});
it('decodes returned friend messages (seq/sender/self uin), oldest→newest', async () => {
const resp = protobuf_encode<SsoGetC2cMsgResponse>({
friendUid: 'u_friend',
messages: [
{
responseHead: { fromUin: 222, forward: { friendName: 'Bob' } },
contentHead: { msgType: 166, sequence: 120, timestamp: 1700000120, msgId: 7120 },
body: { richText: { elems: [] } },
},
{
responseHead: { fromUin: 111, forward: { friendName: 'Alice' } },
contentHead: { msgType: 166, sequence: 110, timestamp: 1700000110, msgId: 7110 },
body: { richText: { elems: [] } },
},
],
});
const sender = { sendRawPacket: async () => okResult(resp) };
const out = await fetchC2cMessageRange(sender, identity, 10001, 'u_friend', 100, 120);
expect(out.map((m) => m.msgSeq)).toEqual([110, 120]); // sorted ascending
expect(out.every((m) => m.kind === 'friend_message')).toBe(true);
expect(out.every((m) => m.selfUin === 10001)).toBe(true);
expect(out[0]).toMatchObject({ msgSeq: 110, senderUin: 111, senderNick: 'Alice' });
expect(out[1]).toMatchObject({ msgSeq: 120, senderUin: 222, senderNick: 'Bob' });
});
it('returns [] on a failed packet, empty uid, or out-of-range request', async () => {
const failSender = { sendRawPacket: async () => ({ success: false, gotResponse: false } as SendPacketResult) };
expect(await fetchC2cMessageRange(failSender, identity, 10001, 'u_x', 100, 120)).toEqual([]);
let sent = false;
const guardSender = { sendRawPacket: async () => { sent = true; return okResult(new Uint8Array()); } };
expect(await fetchC2cMessageRange(guardSender, identity, 10001, '', 100, 120)).toEqual([]); // empty uid
expect(await fetchC2cMessageRange(guardSender, identity, 10001, 'u_x', 200, 100)).toEqual([]); // start > end
expect(sent).toBe(false);
});
});