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
@@ -235,7 +235,14 @@ export interface FriendMessage extends QQEvent {
|
||||
* index can preserve the exact C2C peer instead of re-resolving its UIN. */
|
||||
senderUid?: string;
|
||||
senderNick: string;
|
||||
/** Sender-local sequence exposed as OneBot message_seq and used by replies. */
|
||||
msgSeq: number;
|
||||
/** Bidirectional C2C sequence used for history/actions and canonical message ids. */
|
||||
ntMsgSeq?: number;
|
||||
/** Sender-local sequence used by private recall requests. */
|
||||
clientSeq?: number;
|
||||
/** False only when an older packet omitted ContentHead field 11. */
|
||||
sequenceAuthoritative?: boolean;
|
||||
msgId: number;
|
||||
elements: MessageElement[];
|
||||
}
|
||||
@@ -263,6 +270,9 @@ export interface TempMessage extends QQEvent {
|
||||
groupId: number;
|
||||
senderNick: string;
|
||||
msgSeq: number;
|
||||
ntMsgSeq?: number;
|
||||
clientSeq?: number;
|
||||
sequenceAuthoritative?: boolean;
|
||||
elements: MessageElement[];
|
||||
}
|
||||
|
||||
@@ -314,7 +324,12 @@ export interface GroupAdminEvent extends QQEvent {
|
||||
export interface FriendRecall extends QQEvent {
|
||||
kind: 'friend_recall';
|
||||
userUin: number;
|
||||
/** Legacy alias retained for converters; this is the sender-local sequence. */
|
||||
msgSeq: number;
|
||||
/** Sender-local sequence carried by the recall protocol. */
|
||||
clientSeq?: number;
|
||||
/** True for subtype 139, where the logged-in account recalled its own send. */
|
||||
recalledBySelf?: boolean;
|
||||
}
|
||||
|
||||
export interface GroupRecallEvent extends QQEvent {
|
||||
|
||||
@@ -13,7 +13,10 @@ export interface MsgPushHead {
|
||||
/** C2C command (`contentHead` field 3). Discriminates control pushes — see
|
||||
* `isC2cControlPush` in ./blank-filter. */
|
||||
readonly c2cCmd: number;
|
||||
/** Sender-local C2C client sequence (field 5), or the group sequence. */
|
||||
readonly sequence: number;
|
||||
/** Bidirectional C2C sequence (field 11); zero on groups/legacy packets. */
|
||||
readonly ntMsgSeq: number;
|
||||
readonly timestamp: number;
|
||||
readonly msgId: number;
|
||||
}
|
||||
@@ -68,6 +71,7 @@ export function buildContextFromMessage(
|
||||
subType: msg.contentHead.subType ?? 0,
|
||||
c2cCmd: msg.contentHead.c2cCmd ?? 0,
|
||||
sequence: msg.contentHead.sequence ?? 0,
|
||||
ntMsgSeq: msg.contentHead.ntMsgSeq ?? 0,
|
||||
timestamp: msg.contentHead.timestamp ?? 0,
|
||||
msgId: msg.contentHead.msgId ?? 0,
|
||||
};
|
||||
|
||||
@@ -173,6 +173,8 @@ function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] {
|
||||
selfUin: ctx.selfUin,
|
||||
userUin: resolveUidToUin(ctx.identity, 0, peerUid, ctx.fromUin),
|
||||
msgSeq: recall.info.clientSequence ?? 0,
|
||||
clientSeq: recall.info.clientSequence ?? 0,
|
||||
recalledBySelf: isSelfRecall,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
|
||||
const elements = decodeRichBody(ctx.body, false);
|
||||
const sentBySelf = ctx.fromUin > 0 && ctx.fromUin === ctx.selfUin;
|
||||
const peerUin = sentBySelf ? (ctx.responseHead?.toUin ?? 0) : ctx.fromUin;
|
||||
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
|
||||
// Stash the approval msgseq from a private group-invite card so a later
|
||||
// `set_group_add_request` can approve a bot self-invite (issue #125).
|
||||
for (const el of elements) {
|
||||
@@ -43,6 +44,9 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
|
||||
senderUid: ctx.fromUid,
|
||||
...(peerUin > 0 ? { peerUin } : {}),
|
||||
msgSeq: ctx.head.sequence,
|
||||
ntMsgSeq: ctx.head.ntMsgSeq,
|
||||
clientSeq: ctx.head.sequence,
|
||||
sequenceAuthoritative,
|
||||
msgId: ctx.head.msgId & 0x7FFFFFFF,
|
||||
elements,
|
||||
senderNick: '',
|
||||
|
||||
@@ -3,12 +3,16 @@ import type { MsgPushDecoder } from '../registry';
|
||||
import { decodeRichBody } from '../rich-body-decoder';
|
||||
|
||||
export const decodeTempMessage: MsgPushDecoder = (ctx) => {
|
||||
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
|
||||
const ev: TempMessage = {
|
||||
kind: 'temp_message',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
senderUin: ctx.fromUin,
|
||||
msgSeq: ctx.head.sequence,
|
||||
ntMsgSeq: ctx.head.ntMsgSeq,
|
||||
clientSeq: ctx.head.sequence,
|
||||
sequenceAuthoritative,
|
||||
elements: decodeRichBody(ctx.body, false),
|
||||
groupId: 0,
|
||||
senderNick: '',
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { SsoGetC2cMsg, SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
|
||||
import type {
|
||||
SsoGetC2cMsg,
|
||||
SsoGetC2cMsgResponse,
|
||||
SsoGetRoamMsg,
|
||||
SsoGetRoamMsgResponse,
|
||||
} from '@snowluma/proto-defs/get-c2c-msg';
|
||||
import type { PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import type { QQEventVariant } from '../events';
|
||||
import type { IdentityService } from '../identity-service';
|
||||
import { isBlankMessage, isC2cControlPush } from './blank-filter';
|
||||
@@ -8,6 +15,9 @@ import { buildContextFromMessage } from './context';
|
||||
import { decodeFriendMessage } from './decoders/friend-message';
|
||||
|
||||
export const SSO_GET_C2C_MSG_CMD = 'trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg';
|
||||
export const SSO_GET_ROAM_MSG_CMD = 'trpc.msg.register_proxy.RegisterProxy.SsoGetRoamMsg';
|
||||
|
||||
const log = createLogger('MsgPush.C2CHistory');
|
||||
|
||||
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
|
||||
|
||||
@@ -15,9 +25,52 @@ interface RawSender {
|
||||
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
|
||||
}
|
||||
|
||||
export interface C2cRoamPage {
|
||||
messages: FriendMessage[];
|
||||
cursor: { time: number; random: number };
|
||||
}
|
||||
|
||||
function requirePacketResponse(result: SendPacketResult, command: string): Uint8Array {
|
||||
if (!result.success) {
|
||||
throw new Error(`${command} transport failed: ${result.errorMessage || 'unknown transport error'}`);
|
||||
}
|
||||
if (!result.gotResponse || !result.responseData || result.responseData.length === 0) {
|
||||
throw new Error(`${command} response is empty`);
|
||||
}
|
||||
return result.responseData;
|
||||
}
|
||||
|
||||
function decodeC2cMessages(
|
||||
messages: readonly PushMsgBody[],
|
||||
identity: IdentityService,
|
||||
selfUin: number,
|
||||
source: string,
|
||||
): FriendMessage[] {
|
||||
const out: FriendMessage[] = [];
|
||||
for (const msg of messages) {
|
||||
const ctx = buildContextFromMessage(msg, selfUin, identity);
|
||||
if (!ctx) {
|
||||
throw new Error(`${source} response contains a message without a content head`);
|
||||
}
|
||||
if (isC2cControlPush(ctx.head)) continue;
|
||||
for (const ev of decodeFriendMessage(ctx)) {
|
||||
if (ev.kind !== 'friend_message') continue;
|
||||
if (isBlankMessage(ev.elements, ctx.body)) continue;
|
||||
if (ev.sequenceAuthoritative === false || !ev.ntMsgSeq || ev.ntMsgSeq <= 0) {
|
||||
throw new Error(
|
||||
`${source} message is missing the canonical NT sequence `
|
||||
+ `(clientSeq=${ev.clientSeq ?? ev.msgSeq} from=${ev.senderUin} time=${ev.time})`,
|
||||
);
|
||||
}
|
||||
out.push(ev);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch one [startSeq, endSeq] window of private (c2c) history from the server
|
||||
* via `SsoGetC2cMsg`, decoding each returned message with the regular friend
|
||||
* Fetch one [startSeq, endSeq] NT-sequence 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.
|
||||
@@ -39,24 +92,76 @@ export async function fetchC2cMessageRange(
|
||||
});
|
||||
|
||||
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 decoded = protobuf_decode<SsoGetC2cMsgResponse>(
|
||||
requirePacketResponse(res, 'SsoGetC2cMsg'),
|
||||
);
|
||||
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) continue;
|
||||
// Drop C2C control/system signals and content-less pushes (the "[空消息]"
|
||||
// phantom, #102) just as QQ NT does on its roam/history fetch — keep
|
||||
// history parity with live (parseMsgPush).
|
||||
if (isC2cControlPush(ctx.head) || isBlankMessage(ev.elements, ctx.body)) continue;
|
||||
out.push(ev);
|
||||
}
|
||||
}
|
||||
out.sort((a, b) => a.msgSeq - b.msgSeq);
|
||||
const out = decodeC2cMessages(messages, identity, selfUin, 'SsoGetC2cMsg');
|
||||
out.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0));
|
||||
log.debug(
|
||||
'SsoGetC2cMsg decoded friend=%s range=%d-%d wire=%d usable=%d',
|
||||
friendUid,
|
||||
startSeq,
|
||||
endSeq,
|
||||
messages.length,
|
||||
out.length,
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch one timestamp-cursor page of C2C roaming history. QQ uses this endpoint
|
||||
* for an unanchored latest page; it returns messages from both participants.
|
||||
*/
|
||||
export async function fetchC2cRoamMessagePage(
|
||||
sender: RawSender,
|
||||
identity: IdentityService,
|
||||
selfUin: number,
|
||||
friendUid: string,
|
||||
beforeTime: number,
|
||||
count: number,
|
||||
beforeRandom = 0,
|
||||
): Promise<C2cRoamPage> {
|
||||
if (!friendUid) throw new Error('SsoGetRoamMsg friend uid is required');
|
||||
if (!Number.isSafeInteger(beforeTime) || beforeTime < 0 || beforeTime > 0xffff_ffff) {
|
||||
throw new Error(`SsoGetRoamMsg cursor time is invalid: ${String(beforeTime)}`);
|
||||
}
|
||||
if (!Number.isSafeInteger(beforeRandom) || beforeRandom < 0 || beforeRandom > 0xffff_ffff) {
|
||||
throw new Error(`SsoGetRoamMsg cursor random is invalid: ${String(beforeRandom)}`);
|
||||
}
|
||||
if (!Number.isSafeInteger(count) || count < 1 || count > 200) {
|
||||
throw new Error(`SsoGetRoamMsg count is invalid: ${String(count)}`);
|
||||
}
|
||||
|
||||
const req = protobuf_encode<SsoGetRoamMsg>({
|
||||
friendUid,
|
||||
time: beforeTime,
|
||||
random: beforeRandom,
|
||||
count,
|
||||
direction: true,
|
||||
});
|
||||
const result = await sender.sendRawPacket(SSO_GET_ROAM_MSG_CMD, req);
|
||||
const response = protobuf_decode<SsoGetRoamMsgResponse>(
|
||||
requirePacketResponse(result, 'SsoGetRoamMsg'),
|
||||
);
|
||||
if (response.friendUid && response.friendUid !== friendUid) {
|
||||
throw new Error(`SsoGetRoamMsg response friend uid mismatch: ${response.friendUid}`);
|
||||
}
|
||||
|
||||
const wireMessages = response.messages ?? [];
|
||||
const messages = decodeC2cMessages(wireMessages, identity, selfUin, 'SsoGetRoamMsg');
|
||||
messages.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time);
|
||||
const cursor = { time: response.timestamp ?? 0, random: response.random ?? 0 };
|
||||
log.debug(
|
||||
'SsoGetRoamMsg decoded friend=%s before=%d/%d count=%d wire=%d usable=%d next=%d/%d',
|
||||
friendUid,
|
||||
beforeTime,
|
||||
beforeRandom,
|
||||
count,
|
||||
wireMessages.length,
|
||||
messages.length,
|
||||
cursor.time,
|
||||
cursor.random,
|
||||
);
|
||||
return { messages, cursor };
|
||||
}
|
||||
@@ -26,7 +26,13 @@ import { SysMsgDedup } from './sysmsg-dedup';
|
||||
export { SysMsgDedup } from './sysmsg-dedup';
|
||||
|
||||
export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history';
|
||||
export { SSO_GET_C2C_MSG_CMD, fetchC2cMessageRange } from './fetch-c2c-history';
|
||||
export {
|
||||
SSO_GET_C2C_MSG_CMD,
|
||||
SSO_GET_ROAM_MSG_CMD,
|
||||
fetchC2cMessageRange,
|
||||
fetchC2cRoamMessagePage,
|
||||
type C2cRoamPage,
|
||||
} from './fetch-c2c-history';
|
||||
|
||||
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
|
||||
|
||||
@@ -90,6 +96,21 @@ function describeUndecodedBody(body: PushMsgBody | undefined): string {
|
||||
return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`;
|
||||
}
|
||||
|
||||
function warnMissingC2cSequence(ev: QQEventVariant, fromUin: number): void {
|
||||
if (
|
||||
(ev.kind === 'friend_message' || ev.kind === 'temp_message')
|
||||
&& ev.sequenceAuthoritative === false
|
||||
) {
|
||||
log.warn(
|
||||
'c2c message omitted NT sequence; keeping non-authoritative client sequence (kind=%s from=%d clientSeq=%d time=%d)',
|
||||
ev.kind,
|
||||
fromUin,
|
||||
ev.clientSeq ?? ev.msgSeq,
|
||||
ev.time,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function parseMsgPush(
|
||||
pkt: PacketInfo,
|
||||
identity: IdentityService,
|
||||
@@ -111,7 +132,10 @@ export function parseMsgPush(
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if ((ev as { elements?: unknown[] }).elements?.length !== 0) return true;
|
||||
if ((ev as { elements?: unknown[] }).elements?.length !== 0) {
|
||||
warnMissingC2cSequence(ev, ctx.fromUin);
|
||||
return true;
|
||||
}
|
||||
// Empty-element message that's NOT a known control cmd. Drop it when the body
|
||||
// is genuinely empty (a content-less push we don't yet classify by c2cCmd).
|
||||
// If instead the body *had* content we just couldn't decode, keep the
|
||||
@@ -121,6 +145,7 @@ export function parseMsgPush(
|
||||
log.warn('message had content but decoded to 0 elements — missing decoder? (kind=%s seq=%d from=%d msgType=%d/%d): %s',
|
||||
ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.subType,
|
||||
describeUndecodedBody(ctx.body));
|
||||
warnMissingC2cSequence(ev, ctx.fromUin);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -395,22 +395,13 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
);
|
||||
}
|
||||
|
||||
// Reply / quote. For a c2c (friend) reply the canonical replied-to sequence
|
||||
// is the srcMsg reserve's `friendSequence`, NOT `origSeqs[0]` — origSeqs
|
||||
// carries the per-sender clientSequence, which doesn't match how the
|
||||
// original message is keyed (by its server/private sequence), so resolving
|
||||
// the reply (and get_msg on the quoted message) would miss. Mirrors
|
||||
// Lagrange's `Sequence = reserve.FriendSequence ?? OrigSeqs[0]`
|
||||
// (ForwardEntity.cs). Group replies keep origSeqs[0] (the shared group seq).
|
||||
// Reply / quote. `origSeqs[0]` is the shared group sequence for groups and
|
||||
// the quoted sender's local client sequence for C2C. The latter is not the
|
||||
// conversation-wide NT sequence used by private history/message ids, so the
|
||||
// OneBot layer resolves it with peer + sender direction + quote time.
|
||||
if (elem.srcMsg) {
|
||||
// The reply resolves to srcMsg.origSeqs[0] — for BOTH group (shared group
|
||||
// seq) 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. reserve.friendSequence is a small friend-relationship
|
||||
// counter that does NOT match (e.g. 25 vs a head.sequence of 12707), so
|
||||
// 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.
|
||||
// On-target capture (#114 / #124) also proved reserve.friendSequence is a
|
||||
// small friend-relationship counter, not either usable message sequence.
|
||||
const src = elem.srcMsg;
|
||||
const replySeq = src.origSeqs?.[0] ?? 0;
|
||||
if (replySeq > 0) {
|
||||
|
||||
@@ -39,12 +39,13 @@ describe('parseMsgPush — empty message drop (#102)', () => {
|
||||
it('keeps a friend message that actually has content', () => {
|
||||
const out = parseMsgPush(pushPacket({
|
||||
responseHead: { fromUin: 10001, fromUid: 'u_x' },
|
||||
contentHead: { msgType: 166, subType: 0, sequence: 100, timestamp: 1781540572, msgId: 1 },
|
||||
contentHead: { msgType: 166, subType: 0, sequence: 32743, ntMsgSeq: 63214, timestamp: 1781540572, msgId: 1 },
|
||||
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
|
||||
}), identity);
|
||||
expect(out).toHaveLength(1);
|
||||
expect(out[0]).toMatchObject({
|
||||
kind: 'friend_message', senderUid: 'u_x', elements: [{ type: 'text', text: 'hi' }],
|
||||
kind: 'friend_message', senderUid: 'u_x', msgSeq: 32743, ntMsgSeq: 63214, clientSeq: 32743,
|
||||
elements: [{ type: 'text', text: 'hi' }],
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -5,9 +5,19 @@
|
||||
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 {
|
||||
SsoGetC2cMsg,
|
||||
SsoGetC2cMsgResponse,
|
||||
SsoGetRoamMsg,
|
||||
SsoGetRoamMsgResponse,
|
||||
} 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';
|
||||
import {
|
||||
SSO_GET_C2C_MSG_CMD,
|
||||
SSO_GET_ROAM_MSG_CMD,
|
||||
fetchC2cMessageRange,
|
||||
fetchC2cRoamMessagePage,
|
||||
} from '../../src/msg-push';
|
||||
|
||||
const identity = { findFriend: () => undefined } as unknown as IdentityService;
|
||||
|
||||
@@ -40,17 +50,17 @@ describe('fetchC2cMessageRange / SsoGetC2cMsg', () => {
|
||||
messages: [
|
||||
{
|
||||
responseHead: { fromUin: 222, forward: { friendName: 'Bob' } },
|
||||
contentHead: { msgType: 166, sequence: 120, timestamp: 1700000120, msgId: 7120 },
|
||||
contentHead: { msgType: 166, sequence: 9120, ntMsgSeq: 120, timestamp: 1700000120, msgId: 7120 },
|
||||
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
|
||||
},
|
||||
{
|
||||
responseHead: { fromUin: 111, forward: { friendName: 'Alice' } },
|
||||
contentHead: { msgType: 166, sequence: 110, timestamp: 1700000110, msgId: 7110 },
|
||||
contentHead: { msgType: 166, sequence: 9110, ntMsgSeq: 110, timestamp: 1700000110, msgId: 7110 },
|
||||
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
|
||||
},
|
||||
{
|
||||
responseHead: { fromUin: 10001, toUin: 333, forward: { friendName: 'Self' } },
|
||||
contentHead: { msgType: 166, sequence: 115, timestamp: 1700000115, msgId: 7115 },
|
||||
contentHead: { msgType: 166, sequence: 9115, ntMsgSeq: 115, timestamp: 1700000115, msgId: 7115 },
|
||||
body: { richText: { elems: [{ text: { str: 'sent' } }] } },
|
||||
},
|
||||
],
|
||||
@@ -59,12 +69,12 @@ describe('fetchC2cMessageRange / SsoGetC2cMsg', () => {
|
||||
|
||||
const out = await fetchC2cMessageRange(sender, identity, 10001, 'u_friend', 100, 120);
|
||||
|
||||
expect(out.map((m) => m.msgSeq)).toEqual([110, 115, 120]); // sorted ascending
|
||||
expect(out.map((m) => m.ntMsgSeq)).toEqual([110, 115, 120]); // sorted by server sequence
|
||||
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: 115, senderUin: 10001, peerUin: 333, senderNick: 'Self' });
|
||||
expect(out[2]).toMatchObject({ msgSeq: 120, senderUin: 222, senderNick: 'Bob' });
|
||||
expect(out[0]).toMatchObject({ msgSeq: 9110, ntMsgSeq: 110, clientSeq: 9110, senderUin: 111, senderNick: 'Alice' });
|
||||
expect(out[1]).toMatchObject({ msgSeq: 9115, ntMsgSeq: 115, clientSeq: 9115, senderUin: 10001, peerUin: 333, senderNick: 'Self' });
|
||||
expect(out[2]).toMatchObject({ msgSeq: 9120, ntMsgSeq: 120, clientSeq: 9120, senderUin: 222, senderNick: 'Bob' });
|
||||
});
|
||||
|
||||
it('drops content-less blank messages, keeps real ones (#102 parity)', async () => {
|
||||
@@ -73,24 +83,45 @@ describe('fetchC2cMessageRange / SsoGetC2cMsg', () => {
|
||||
messages: [
|
||||
{ // genuinely-blank control push (the invite phantom) → dropped
|
||||
responseHead: { fromUin: 111, forward: { friendName: 'Alice' } },
|
||||
contentHead: { msgType: 166, sequence: 110, timestamp: 1700000110, msgId: 7110 },
|
||||
contentHead: { msgType: 166, sequence: 9110, ntMsgSeq: 110, timestamp: 1700000110, msgId: 7110 },
|
||||
body: { richText: { elems: [] } },
|
||||
},
|
||||
{ // real message → kept
|
||||
responseHead: { fromUin: 222, forward: { friendName: 'Bob' } },
|
||||
contentHead: { msgType: 166, sequence: 120, timestamp: 1700000120, msgId: 7120 },
|
||||
contentHead: { msgType: 166, sequence: 9120, ntMsgSeq: 120, timestamp: 1700000120, msgId: 7120 },
|
||||
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
|
||||
},
|
||||
],
|
||||
});
|
||||
const out = await fetchC2cMessageRange({ sendRawPacket: async () => okResult(resp) }, identity, 10001, 'u_friend', 100, 120);
|
||||
expect(out.map((m) => m.msgSeq)).toEqual([120]);
|
||||
expect(out.map((m) => m.ntMsgSeq)).toEqual([120]);
|
||||
expect(out[0]).toMatchObject({ senderUin: 222, elements: [{ type: 'text', text: 'hi' }] });
|
||||
});
|
||||
|
||||
it('returns [] on a failed packet, empty uid, or out-of-range request', async () => {
|
||||
it('rejects a visible message without the canonical NT sequence', async () => {
|
||||
const resp = protobuf_encode<SsoGetC2cMsgResponse>({
|
||||
friendUid: 'u_friend',
|
||||
messages: [{
|
||||
responseHead: { fromUin: 222, forward: { friendName: 'Bob' } },
|
||||
contentHead: { msgType: 166, sequence: 9120, timestamp: 1700000120, msgId: 7120 },
|
||||
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
|
||||
}],
|
||||
});
|
||||
|
||||
await expect(fetchC2cMessageRange(
|
||||
{ sendRawPacket: async () => okResult(resp) },
|
||||
identity,
|
||||
10001,
|
||||
'u_friend',
|
||||
100,
|
||||
120,
|
||||
)).rejects.toThrow('canonical NT sequence');
|
||||
});
|
||||
|
||||
it('surfaces a failed packet, while invalid input is rejected before sending', async () => {
|
||||
const failSender = { sendRawPacket: async () => ({ success: false, gotResponse: false } as SendPacketResult) };
|
||||
expect(await fetchC2cMessageRange(failSender, identity, 10001, 'u_x', 100, 120)).toEqual([]);
|
||||
await expect(fetchC2cMessageRange(failSender, identity, 10001, 'u_x', 100, 120))
|
||||
.rejects.toThrow('SsoGetC2cMsg');
|
||||
|
||||
let sent = false;
|
||||
const guardSender = { sendRawPacket: async () => { sent = true; return okResult(new Uint8Array()); } };
|
||||
@@ -99,3 +130,56 @@ describe('fetchC2cMessageRange / SsoGetC2cMsg', () => {
|
||||
expect(sent).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchC2cRoamMessagePage / SsoGetRoamMsg', () => {
|
||||
it('encodes the timestamp cursor and orders both sides by canonical NT sequence', async () => {
|
||||
let captured: { cmd: string; body: Uint8Array } | null = null;
|
||||
const response = protobuf_encode<SsoGetRoamMsgResponse>({
|
||||
friendUid: 'u_friend',
|
||||
timestamp: 1700000000,
|
||||
random: 77,
|
||||
messages: [
|
||||
{
|
||||
responseHead: { fromUin: 10001, toUin: 222, forward: { friendName: 'Self' } },
|
||||
contentHead: { msgType: 166, sequence: 32743, ntMsgSeq: 63214, timestamp: 1700000001, msgId: 20 },
|
||||
body: { richText: { elems: [{ text: { str: 'out' } }] } },
|
||||
},
|
||||
{
|
||||
responseHead: { fromUin: 222, forward: { friendName: 'Bob' } },
|
||||
contentHead: { msgType: 166, sequence: 32742, ntMsgSeq: 63213, timestamp: 1700000002, msgId: 10 },
|
||||
body: { richText: { elems: [{ text: { str: 'in' } }] } },
|
||||
},
|
||||
],
|
||||
});
|
||||
const sender = {
|
||||
sendRawPacket: async (cmd: string, body: Uint8Array) => {
|
||||
captured = { cmd, body };
|
||||
return okResult(response);
|
||||
},
|
||||
};
|
||||
|
||||
const page = await fetchC2cRoamMessagePage(
|
||||
sender, identity, 10001, 'u_friend', 1700000100, 20, 9,
|
||||
);
|
||||
|
||||
expect(captured!.cmd).toBe(SSO_GET_ROAM_MSG_CMD);
|
||||
const request = protobuf_decode<SsoGetRoamMsg>(captured!.body);
|
||||
expect(request).toMatchObject({
|
||||
friendUid: 'u_friend',
|
||||
time: 1700000100,
|
||||
random: 9,
|
||||
count: 20,
|
||||
direction: true,
|
||||
});
|
||||
expect(page.cursor).toEqual({ time: 1700000000, random: 77 });
|
||||
expect(page.messages.map((message) => ({
|
||||
sender: message.senderUin,
|
||||
sequence: message.ntMsgSeq,
|
||||
messageSequence: message.msgSeq,
|
||||
clientSequence: message.clientSeq,
|
||||
}))).toEqual([
|
||||
{ sender: 222, sequence: 63213, messageSequence: 32742, clientSequence: 32742 },
|
||||
{ sender: 10001, sequence: 63214, messageSequence: 32743, clientSequence: 32743 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user