fix(protocol): preserve friend category metadata

This commit is contained in:
DrSmoothl committed 2026-07-13 18:51:11 +08:00
1 parent 2ae9a47249
commit 8cd7d51d80
7 files changed
+347 -51

No files matched your search

+95 -14
View File
@@ -8,8 +8,11 @@ import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetc
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark';
import { toHex } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache';
import type {
FriendCategoryInfo,
FriendInfo,
GroupMemberInfo,
GroupRequestInfo,
@@ -19,6 +22,8 @@ import type {
import type { DownloadRKeyInfo } from '../bridge';
import type { BridgeContext } from '../bridge-context';
const log = createLogger('Bridge.Contacts');
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
type FriendPropertySource = {
@@ -33,6 +38,23 @@ type FriendPropertySource = {
}>;
};
interface FriendRosterEntry {
friend: FriendInfo;
categoryId: number;
}
interface FriendCategoryMeta {
categoryId: number;
categoryName: string;
memberCount: number;
sortId: number;
}
interface FriendRoster {
entries: FriendRosterEntry[];
categories: FriendCategoryMeta[];
}
export function buildFriendProperties(raw: FriendPropertySource): Map<number, string> {
const props = new Map<number, string>();
for (const additional of raw.additional ?? []) {
@@ -82,26 +104,85 @@ export class ContactsApi {
return GetGroupRecommendArk.invoke(this.ctx, { groupId });
}
async fetchFriendList(): Promise<FriendInfo[]> {
const friends: FriendInfo[] = [];
let nextUin: number | null = null;
do {
const resp = await FetchFriendListPage.invoke(this.ctx, { nextUin });
private async fetchFriendRoster(): Promise<FriendRoster> {
const entries: FriendRosterEntry[] = [];
const categories = new Map<number, FriendCategoryMeta>();
const seenCookies = new Set<string>();
let cookie: Uint8Array | undefined;
for (;;) {
const resp = await FetchFriendListPage.invoke(this.ctx, { cookie });
for (const raw of resp.friends ?? []) {
const props = buildFriendProperties(raw);
friends.push({
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
entries.push({
categoryId: raw.customGroup ?? 0,
friend: {
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
},
});
}
for (const raw of resp.categories ?? []) {
const categoryId = raw.categoryId ?? 0;
categories.set(categoryId, {
categoryId,
categoryName: raw.categoryName ?? '',
memberCount: raw.memberCount ?? 0,
sortId: raw.sortId ?? 0,
});
}
nextUin = resp.next?.uin ?? null;
if (nextUin === 0) nextUin = null;
} while (nextUin !== null);
const next = resp.cookie;
if (!next?.length) break;
const key = toHex(next);
if (seenCookies.has(key)) {
throw new Error(`repeated friend-list cookie ${key}`);
}
seenCookies.add(key);
cookie = next;
}
const friends = entries.map(entry => entry.friend);
this.ctx.identity.rememberFriends(friends);
return friends;
return { entries, categories: [...categories.values()] };
}
async fetchFriendList(): Promise<FriendInfo[]> {
const roster = await this.fetchFriendRoster();
return roster.entries.map(entry => entry.friend);
}
async fetchFriendCategories(): Promise<FriendCategoryInfo[]> {
const roster = await this.fetchFriendRoster();
const buckets = new Map(
roster.categories.map(category => [category.categoryId, [] as FriendInfo[]]),
);
for (const entry of roster.entries) {
const bucket = buckets.get(entry.categoryId);
if (!bucket) {
throw new Error(
`friend roster references missing category ${entry.categoryId} `
+ `(${roster.entries.length} friends total)`,
);
}
bucket.push(entry.friend);
}
return roster.categories.map(category => {
const friends = buckets.get(category.categoryId)!;
if (friends.length !== category.memberCount) {
log.warn(
'friend category member count mismatch category=%d server=%d assembled=%d',
category.categoryId,
category.memberCount,
friends.length,
);
}
return { ...category, friends };
});
}
async fetchGroupList(): Promise<QQGroupInfo[]> {
@@ -0,0 +1,162 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type {
OidbBase,
OidbFriend,
OidbFriendCategory,
OidbSvcTrpcTcp0xFD4_1Response,
} from '@snowluma/proto-defs/oidb';
import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import { ContactsApi } from '../../src/bridge/apis/contacts';
function friend(
uin: number,
categoryId: number,
uid: string,
nickname: string,
remark = '',
): OidbFriend {
return {
uin,
uid,
customGroup: categoryId,
additional: [{
type: 1,
layer1: {
properties: [
{ code: 20002, value: nickname },
{ code: 103, value: remark },
],
},
}],
};
}
function category(
categoryId: number,
categoryName: string,
memberCount: number,
sortId: number,
): OidbFriendCategory {
return { categoryId, categoryName, memberCount, sortId };
}
function packet(body: OidbSvcTrpcTcp0xFD4_1Response): SendPacketResult {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(
protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>({ body }),
),
};
}
function apiForPages(pages: OidbSvcTrpcTcp0xFD4_1Response[]) {
let index = 0;
const sendRawPacket = vi.fn(async (
_cmd: string,
_body: Uint8Array,
): Promise<SendPacketResult> => {
const page = pages[index++];
if (!page) throw new Error(`unexpected friend-list page ${index}`);
return packet(page);
});
const rememberFriends = vi.fn();
const api = new ContactsApi({
sendRawPacket,
identity: { rememberFriends },
} as any);
return { api, sendRawPacket, rememberFriends };
}
describe('apis/contacts / categorized friend roster', () => {
it('keeps fetchFriendList flat while traversing cookie pages', async () => {
const cookie = Uint8Array.from([0x01]);
const { api, sendRawPacket } = apiForPages([
{ cookie, friends: [friend(10001, 0, 'u1', 'Default')] },
{ friends: [friend(10002, 7, 'u2', 'Alice', 'A')] },
]);
await expect(api.fetchFriendList()).resolves.toEqual([
{ uin: 10001, uid: 'u1', nickname: 'Default', remark: '' },
{ uin: 10002, uid: 'u2', nickname: 'Alice', remark: 'A' },
]);
expect(sendRawPacket).toHaveBeenCalledTimes(2);
});
it('groups a complete multi-page roster and preserves empty categories', async () => {
const cookie = Uint8Array.from([0xAA, 0xBB]);
const { api, sendRawPacket, rememberFriends } = apiForPages([
{
cookie,
friends: [friend(10001, 0, 'u1', 'Default')],
categories: [
category(0, '我的好友', 1, 0),
category(7, 'Work', 1, 1),
category(9, 'Empty', 0, 2),
],
},
{
friends: [friend(10002, 7, 'u2', 'Alice', 'A')],
categories: [category(7, 'Work', 1, 1)],
},
]);
await expect(api.fetchFriendCategories()).resolves.toEqual([
{
categoryId: 0,
categoryName: '我的好友',
memberCount: 1,
sortId: 0,
friends: [{ uin: 10001, uid: 'u1', nickname: 'Default', remark: '' }],
},
{
categoryId: 7,
categoryName: 'Work',
memberCount: 1,
sortId: 1,
friends: [{ uin: 10002, uid: 'u2', nickname: 'Alice', remark: 'A' }],
},
{
categoryId: 9,
categoryName: 'Empty',
memberCount: 0,
sortId: 2,
friends: [],
},
]);
expect(sendRawPacket).toHaveBeenCalledTimes(2);
const secondRequest = protobuf_decode<OidbBase<OidbFriendListRequest>>(
sendRawPacket.mock.calls[1]![1],
);
expect(secondRequest.body?.cookie).toEqual(cookie);
expect(rememberFriends).toHaveBeenCalledOnce();
expect(rememberFriends).toHaveBeenCalledWith([
{ uin: 10001, uid: 'u1', nickname: 'Default', remark: '' },
{ uin: 10002, uid: 'u2', nickname: 'Alice', remark: 'A' },
]);
});
it('rejects a friend whose category metadata never arrives', async () => {
const { api } = apiForPages([{
friends: [friend(10001, 99, 'u1', 'Orphan')],
categories: [],
}]);
await expect(api.fetchFriendCategories())
.rejects.toThrow('missing category 99');
});
it('rejects a repeated non-empty pagination cookie', async () => {
const cookie = Uint8Array.from([0xAA]);
const { api } = apiForPages([{ cookie }, { cookie }]);
await expect(api.fetchFriendCategories())
.rejects.toThrow('repeated friend-list cookie aa');
});
});
+1 -5
View File
@@ -215,13 +215,10 @@ export interface OidbFriendListBodyItem {
type?: pb<1, uint_32>;
number?: pb<2, OidbFriendListNumber>;
}
export interface OidbFriendListNextUin {
uin?: pb<1, uint_32>;
}
export interface OidbFriendListRequest {
friendCount?: pb<2, uint_32>;
field4?: pb<4, uint_32>;
nextUin?: pb<5, OidbFriendListNextUin>;
cookie?: pb<5, bytes>;
field6?: pb<6, uint_32>;
field7?: pb<7, uint_32>;
body?: pb_repeated<10001, OidbFriendListBodyItem>;
@@ -912,4 +909,3 @@ export interface Oidb0xcdeRespBodyInfo {
export interface Oidb0xcdeResp {
info?: pb<2, Oidb0xcdeRespBodyInfo>;
}
+13 -9
View File
@@ -1,4 +1,4 @@
import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton';
import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes, bool } from '@snowluma/proton';
export interface OidbProperty {
key?: pb<1, string>;
@@ -51,17 +51,21 @@ export interface OidbFriend {
additional?: pb_repeated<10001, OidbFriendAdditional>;
}
export interface OidbSvcTrpcTcp0xFD4_1ResponseUin {
uin?: pb<1, uint_32>;
export interface OidbFriendCategory {
categoryId?: pb<1, uint_32>;
categoryName?: pb<2, string>;
memberCount?: pb<3, uint_32>;
sortId?: pb<4, uint_32>;
}
export interface OidbSvcTrpcTcp0xFD4_1Response {
next?: pb<2, OidbSvcTrpcTcp0xFD4_1ResponseUin>;
displayFriendCount?: pb<3, uint_32>;
timestamp?: pb<6, uint_32>;
selfUin?: pb<7, uint_32>;
friends?: pb_repeated<101, OidbFriend>;
groups?: pb_repeated<102, OidbFriendProperty>;
cookie?: pb<2, bytes>;
isEnd?: pb<3, bool>;
timestamp?: pb<6, uint_64>;
selfUin?: pb<7, uint_64>;
smallSeq?: pb<8, uint_32>;
friends?: pb_repeated<101, OidbFriend>;
categories?: pb_repeated<102, OidbFriendCategory>;
}
// Oidb.0xFE5_2 Group list
@@ -1,8 +1,8 @@
// 0xFD4_1 — single-page friend-roster fetch.
//
// QQ paginates the friend list with a wire-level cursor (`nextUin`).
// QQ paginates the friend list with an opaque wire-level cookie.
// This namespace handles ONE round-trip — the facade drives the
// while-loop until the server stops emitting a next cursor and
// while-loop until the server stops emitting a cookie and
// concatenates results into the public FriendInfo[] shape.
import type { OidbBase, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb';
@@ -15,9 +15,8 @@ export namespace FetchFriendListPage {
export const subCommand = 1;
export interface Params {
/** Cursor: `null` for the first page, otherwise the previous
* page's `nextUin`. */
nextUin: number | null;
/** Opaque cookie returned by the previous page. Omit on page one. */
cookie?: Uint8Array;
}
export type Deps = OidbSender;
@@ -35,8 +34,8 @@ export namespace FetchFriendListPage {
field10002: [13578, 13579, 13573, 13572, 13568],
field10003: 4051,
};
if (p.nextUin !== null) {
body.nextUin = { uin: p.nextUin };
if (p.cookie?.length) {
body.cookie = p.cookie;
}
return body;
};
+8
View File
@@ -21,6 +21,14 @@ export interface FriendInfo {
remark: string;
}
export interface FriendCategoryInfo {
categoryId: number;
categoryName: string;
memberCount: number;
sortId: number;
friends: FriendInfo[];
}
export interface GroupMemberInfo {
uin: number;
uid: string;
@@ -1,11 +1,32 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import {
protobuf_decode,
protobuf_encode,
type bool,
type bytes,
type pb,
type pb_repeated,
type uint_32,
} from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb';
import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchFriendListPage } from '../../../src/oidb-services/contacts/fetch-friend-list-page';
interface TestFriendCategory {
categoryId?: pb<1, uint_32>;
categoryName?: pb<2, string>;
memberCount?: pb<3, uint_32>;
sortId?: pb<4, uint_32>;
}
interface TestFriendListResponse {
cookie?: pb<2, bytes>;
isEnd?: pb<3, bool>;
categories?: pb_repeated<102, TestFriendCategory>;
}
function makeSender(body?: OidbSvcTrpcTcp0xFD4_1Response) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>({ body }))
@@ -21,20 +42,22 @@ describe('FetchFriendListPage namespace', () => {
});
describe('serialize', () => {
it('omits nextUin on the first page', () => {
const out = FetchFriendListPage.serialize({} as any, { nextUin: null }) as any;
expect(out.nextUin).toBeUndefined();
it('omits the cookie on the first page', () => {
const out = FetchFriendListPage.serialize({} as any, {} as any) as any;
expect(out.cookie).toBeUndefined();
expect(out.friendCount).toBe(300);
expect(out.field4).toBe(0);
});
it('includes nextUin sub-message on follow-up pages', () => {
const out = FetchFriendListPage.serialize({} as any, { nextUin: 10001 }) as any;
expect(out.nextUin).toEqual({ uin: 10001 });
it('replays the opaque response cookie in request tag 5', () => {
const cookie = Uint8Array.from([0x08, 0x96, 0x01, 0xFF]);
const out = FetchFriendListPage.serialize({} as any, { cookie } as any) as any;
expect(out.cookie).toEqual(cookie);
expect(out.nextUin).toBeUndefined();
});
it('emits the verbatim property request list (codes 100/101/102/103/20002/27394)', () => {
const out = FetchFriendListPage.serialize({} as any, { nextUin: null }) as any;
const out = FetchFriendListPage.serialize({} as any, {}) as any;
expect(out.body).toEqual([
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
{ type: 4, number: { numbers: [100, 101, 102] } },
@@ -45,24 +68,47 @@ describe('FetchFriendListPage namespace', () => {
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0xfd4_1', async () => {
const sender = makeSender({ friends: [] });
await FetchFriendListPage.invoke(sender, { nextUin: null });
await FetchFriendListPage.invoke(sender, {});
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xfd4_1');
});
it('returns the wire body verbatim (facade does the FriendInfo mapping)', async () => {
const body = { friends: [{ uin: 10001, uid: 'u', additional: [] }], next: { uin: 0 } };
it('returns the wire body verbatim (facade does the roster mapping)', async () => {
const body = { friends: [{ uin: 10001, uid: 'u', additional: [] }] };
const sender = makeSender(body as any);
const out = await FetchFriendListPage.invoke(sender, { nextUin: null });
const out = await FetchFriendListPage.invoke(sender, {} as any);
expect(out.friends).toBeDefined();
expect(out.next?.uin ?? 0).toBe(0);
});
it('encodes envelope body correctly', async () => {
it('encodes a follow-up cookie in the envelope body', async () => {
const sender = makeSender({ friends: [] });
await FetchFriendListPage.invoke(sender, { nextUin: 10001 });
const cookie = Uint8Array.from([0xAA, 0xBB]);
await FetchFriendListPage.invoke(sender, { cookie } as any);
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendListRequest>>(bytes);
expect(env.body?.nextUin).toEqual({ uin: 10001 });
expect((env.body as any)?.cookie).toEqual(cookie);
});
it('decodes category metadata and the opaque response cookie', () => {
const bytes = protobuf_encode<OidbBase<TestFriendListResponse>>({
body: {
cookie: Uint8Array.from([0xAA, 0xBB]),
isEnd: false,
categories: [{
categoryId: 7,
categoryName: 'Work',
memberCount: 2,
sortId: 3,
}],
},
});
const body = FetchFriendListPage.decode(bytes).body as any;
expect(body.cookie).toEqual(Uint8Array.from([0xAA, 0xBB]));
expect(body.categories).toEqual([{
categoryId: 7,
categoryName: 'Work',
memberCount: 2,
sortId: 3,
}]);
});
});
});