refactor(protocol): keep custom-face list encoding with delete

Profile still turns ids into image URLs and slices the count. Asking
for ids no longer round-trips through those URLs.
This commit is contained in:
DrSmoothl committed 2026-08-29 23:58:56 +08:00
1 parent 9cdbcb0299
commit 117335166f
7 files changed
+280 -37

No files matched your search

+7 -28
View File
@@ -1,6 +1,4 @@
import type {
FaceroamOpReq,
FaceroamOpResp,
GroupAvatarExtra,
SetStatusReq,
SetStatusResp,
@@ -8,6 +6,7 @@ import type {
import { AddCustomFace } from '@snowluma/protocol/oidb-services/custom-face/add-custom-face';
import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/delete-custom-face';
import { FetchCustomFaceDetail } from '@snowluma/protocol/oidb-services/custom-face/fetch-custom-face-detail';
import { FetchCustomFaceList } from '@snowluma/protocol/oidb-services/custom-face/fetch-custom-face-list';
import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face';
import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face';
import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face';
@@ -167,28 +166,13 @@ export class ProfileApi {
}));
}
private async fetchCustomFaceIds(count: number): Promise<string[]> {
async fetchCustomFaceIds(count = 10): Promise<string[]> {
if (!Number.isInteger(count) || count < 0) {
throw new Error('custom face count must be a non-negative integer');
}
if (count === 0) return [];
const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(this.ctx.identity.uin),
field3: 1,
field6: 1,
};
const request = protobuf_encode<FaceroamOpReq>(req);
const result = await this.ctx.sendRawPacket('Faceroam.OpReq', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'fetch custom face failed');
}
const resp = protobuf_decode<FaceroamOpResp>(result.responseData);
if (!resp || (resp.retCode ?? 0) !== 0) {
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
}
const faceIds = resp.item?.faceIds || [];
const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
return faceIds.slice(0, count);
}
@@ -196,7 +180,7 @@ export class ProfileApi {
return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`;
}
/** 删除一个收藏表情(custom face)。emoji_id 来自 fetchCustomFace 返回的 URL 路径段。 */
/** 删除一个收藏表情(custom face)。emoji_id 来自收藏列表。 */
deleteCustomFace(emojiId: string): Promise<void> {
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
}
@@ -211,9 +195,8 @@ export class ProfileApi {
}
/**
* 修改收藏表情(custom face)备注。emoji_id 来自 fetchCustomFace 返回的
* URL 路径段;md5 从 emoji_id 中段解析,无需调用方单独提供。desc 为空串
* 则清空备注。
* 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id
* 中段解析,无需调用方单独提供。desc 为空串则清空备注。
*/
modifyCustomFace(emojiId: string, desc: string): Promise<void> {
return ModifyCustomFace.invoke(this.ctx, {
@@ -231,11 +214,7 @@ export class ProfileApi {
*/
async moveCustomFaceToFront(emojiId: string): Promise<void> {
// 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序)
const urls = await this.fetchCustomFace(1000);
const ids = urls.map((url) => {
const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url);
return m ? m[1] : '';
}).filter(Boolean);
const ids = await this.fetchCustomFaceIds(1000);
const idx = ids.indexOf(emojiId);
if (idx < 0) throw new Error(`emoji_id not in list: ${emojiId}`);
// 新顺序:目标挪到第一,其余按原顺序
@@ -300,6 +300,94 @@ describe('apis/profile', () => {
expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]);
});
it('fetchCustomFaceIds slices the Faceroam list and skips the packet for count=0', async () => {
const bridge = mockBridge();
const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
const emojiB = '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0';
bridge.sendRawPacket.mockResolvedValueOnce({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({
retCode: 0,
item: { faceIds: [emojiA, emojiB] },
})),
} as any);
const api = new ProfileApi(bridge as any);
await expect(api.fetchCustomFaceIds(1)).resolves.toEqual([emojiA]);
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('Faceroam.OpReq');
await expect(api.fetchCustomFaceIds(0)).resolves.toEqual([]);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
});
it('fetchCustomFace maps ids to image urls', async () => {
const bridge = mockBridge();
const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
bridge.sendRawPacket.mockResolvedValueOnce({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({
retCode: 0,
item: { faceIds: [emojiA] },
})),
} as any);
await expect(new ProfileApi(bridge as any).fetchCustomFace(1)).resolves.toEqual([
`https://p.qpic.cn/qq_expression/10001/${emojiA}/0`,
]);
});
it('rejects a negative custom-face count before sending', async () => {
const bridge = mockBridge();
await expect(new ProfileApi(bridge as any).fetchCustomFaceIds(-1)).rejects.toThrow(
/non-negative integer/,
);
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('moveCustomFaceToFront reorders from the id list without parsing urls', async () => {
const bridge = mockBridge();
const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
const emojiB = '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0';
bridge.sendRawPacket
.mockResolvedValueOnce({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({
retCode: 0,
item: { faceIds: [emojiA, emojiB] },
})),
} as any)
.mockResolvedValue({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<CustomFaceModifyResp>>({
body: { retCode: 0 },
})),
} as any);
await new ProfileApi(bridge as any).moveCustomFaceToFront(emojiB);
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
'Faceroam.OpReq',
'OidbSvcTrpcTcp.0x902f_1',
'OidbSvcTrpcTcp.0x902e_1',
]);
const moveBody = protobuf_decode<OidbBase<CustomFaceMoveBody>>(
bridge.sendRawPacket.mock.calls[2]![1],
);
expect(moveBody.body?.emojis?.map((emoji) => emoji.emojiId)).toEqual([emojiB, emojiA]);
});
it('fetchCustomFaceDetails supplements the Faceroam ids with server descriptions (#333)', async () => {
const bridge = mockBridge();
const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
+2 -7
View File
@@ -1266,15 +1266,10 @@ export const actions = [
return_type: f.string().default('url'),
},
run: async (p, ctx) => {
const urls = await ctx.bridge.apis.profile.fetchCustomFace(p.count);
if (p.return_type === 'id') {
const emojiIds = urls.map((url) => {
const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url);
return m ? m[1] : '';
}).filter(Boolean);
return okResponse(emojiIds);
return okResponse(await ctx.bridge.apis.profile.fetchCustomFaceIds(p.count));
}
return okResponse(urls);
return okResponse(await ctx.bridge.apis.profile.fetchCustomFace(p.count));
},
}),
@@ -61,6 +61,7 @@ const APIS_ROUTING: Record<string, [string, string]> = {
setAvatar: ['profile', 'setAvatar'],
setGroupAvatar: ['profile', 'setGroupAvatar'],
fetchCustomFace: ['profile', 'fetchCustomFace'],
fetchCustomFaceIds: ['profile', 'fetchCustomFaceIds'],
fetchCustomFaceDetails: ['profile', 'fetchCustomFaceDetails'],
getProfileLike: ['profile', 'getLike'],
getUnidirectionalFriendList: ['profile', 'getUnidirectionalFriendList'],
@@ -1486,6 +1487,45 @@ describe('extended-actions / set_group_portrait', () => {
});
});
describe('extended-actions / fetch_custom_face', () => {
it('return_type=id uses the id list directly', async () => {
const fetchCustomFaceIds = vi.fn(async () => [
'10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0',
'10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0',
]);
const fetchCustomFace = vi.fn();
const bridge = fakeBridge({ fetchCustomFaceIds, fetchCustomFace });
const response = await makeHandler(fakeCtx(bridge)).handle('fetch_custom_face', {
count: '2',
return_type: 'id',
});
expect(fetchCustomFaceIds).toHaveBeenCalledWith(2);
expect(fetchCustomFace).not.toHaveBeenCalled();
expect(response).toMatchObject({
status: 'ok',
data: [
'10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0',
'10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0',
],
});
});
it('default return_type uses image urls', async () => {
const url = 'https://p.qpic.cn/qq_expression/10001/id/0';
const fetchCustomFace = vi.fn(async () => [url]);
const fetchCustomFaceIds = vi.fn();
const bridge = fakeBridge({ fetchCustomFace, fetchCustomFaceIds });
const response = await makeHandler(fakeCtx(bridge)).handle('fetch_custom_face', { count: '1' });
expect(fetchCustomFace).toHaveBeenCalledWith(1);
expect(fetchCustomFaceIds).not.toHaveBeenCalled();
expect(response).toMatchObject({ status: 'ok', data: [url] });
});
});
describe('extended-actions / fetch_custom_face_detail', () => {
it('returns real packet-backed fields with SnowLuma and NapCat resource aliases', async () => {
const fetchCustomFaceDetails = vi.fn(async () => [{
@@ -0,0 +1,44 @@
// Faceroam.OpReq opType=1 — 拉取当前账号的收藏表情 id 列表。
//
// 和 delete 同一个 trpc service,区别在 field3=1、inner 带 qqVersion、
// 并置 field6=1。响应 item.faceIds 是完整列表;截条数由调用方做。
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { FaceroamOpReq, FaceroamOpResp } from '@snowluma/proto-defs/oidb-actions/base';
import type { OidbSender } from '../../oidb-service';
import { FACEROAM_SERVICE, makeInner } from './shared';
export namespace FetchCustomFaceList {
export interface Params {
/** 当前账号 UIN,写入 field2。 */
uin: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): FaceroamOpReq => ({
inner: makeInner(true),
uin: BigInt(p.uin),
field3: 1,
field6: 1,
});
export const encode = (req: FaceroamOpReq): Uint8Array =>
protobuf_encode<FaceroamOpReq>(req);
export const decode = (bytes: Uint8Array): FaceroamOpResp =>
protobuf_decode<FaceroamOpResp>(bytes);
export async function invoke(deps: Deps, params: Params): Promise<string[]> {
const body = encode(serialize(deps, params));
const result = await deps.sendRawPacket(FACEROAM_SERVICE, body);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'fetch custom face failed');
}
const resp = decode(result.responseData);
if (!resp || (resp.retCode ?? 0) !== 0) {
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
}
return resp.item?.faceIds || [];
}
}
@@ -15,7 +15,8 @@ export const FACEROAM_SERVICE = 'Faceroam.OpReq';
// 真出问题再从 identity 里取。
/** osVersion 字符串,Faceroam inner 与 0x902e 业务体 f2 共用。 */
export const CLIENT_VERSION = '10.0.26200';
const CLIENT_BUILD = '9.9.26-44343';
/** qqVersion on the Faceroam list inner. Keep the value list already sends. Delete omits this field. */
const LIST_QQ_VERSION = '9.9.28-46928';
/**
* 构造请求 inner(field1 客户端环境)。fetch 带 qqVersion,delete 不带——
@@ -23,6 +24,6 @@ const CLIENT_BUILD = '9.9.26-44343';
*/
export function makeInner(withQqVersion: boolean): FaceroamOpReqInner {
const inner: FaceroamOpReqInner = { field1: 1, osVersion: CLIENT_VERSION };
if (withQqVersion) inner.qqVersion = CLIENT_BUILD;
if (withQqVersion) inner.qqVersion = LIST_QQ_VERSION;
return inner;
}
@@ -0,0 +1,96 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { FaceroamOpReq, FaceroamOpResp } from '@snowluma/proto-defs/oidb-actions/base';
import { FetchCustomFaceList } from '../../../src/oidb-services/custom-face/fetch-custom-face-list';
const SAMPLE_UIN = '10001';
const EMOJI_A = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
const EMOJI_B = '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0';
function encodeLegacyList(uin: string): Uint8Array {
return protobuf_encode<FaceroamOpReq>({
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(uin),
field3: 1,
field6: 1,
});
}
function makeSender(opts: {
faces?: FaceroamOpResp;
success?: boolean;
gotResponse?: boolean;
errorMessage?: string;
responseData?: Uint8Array | null;
} = {}) {
const result: SendPacketResult = {
success: opts.success ?? true,
gotResponse: opts.gotResponse ?? true,
errorCode: 0,
errorMessage: opts.errorMessage ?? '',
responseData: opts.responseData !== undefined
? opts.responseData
: Buffer.from(protobuf_encode<FaceroamOpResp>(
opts.faces ?? { retCode: 0, item: { faceIds: [EMOJI_A, EMOJI_B] } },
)),
};
return { sendRawPacket: vi.fn(async () => result) };
}
describe('FetchCustomFaceList namespace', () => {
describe('serialize + encode', () => {
it('keeps the list request bytes the ProfileApi fetch already sent', () => {
const req = FetchCustomFaceList.serialize({} as any, { uin: SAMPLE_UIN });
const hex = Buffer.from(FetchCustomFaceList.encode(req)).toString('hex');
expect(hex).toBe(Buffer.from(encodeLegacyList(SAMPLE_UIN)).toString('hex'));
});
it('sends qqVersion on inner and sets field3=1 / field6=1', () => {
const req = FetchCustomFaceList.serialize({} as any, { uin: SAMPLE_UIN });
expect(req.inner?.qqVersion).toBe('9.9.28-46928');
expect(req.inner?.osVersion).toBe('10.0.26200');
expect(req.field3).toBe(1);
expect(req.field6).toBe(1);
expect(req.body).toBeUndefined();
});
});
describe('invoke', () => {
it('routes through "Faceroam.OpReq" and returns the id list', async () => {
const sender = makeSender();
await expect(FetchCustomFaceList.invoke(sender, { uin: SAMPLE_UIN })).resolves.toEqual([
EMOJI_A,
EMOJI_B,
]);
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('Faceroam.OpReq');
const [, body] = sender.sendRawPacket.mock.calls[0]!;
expect(Buffer.from(body as Uint8Array).toString('hex')).toBe(
Buffer.from(encodeLegacyList(SAMPLE_UIN)).toString('hex'),
);
});
it('returns an empty list when the item is missing', async () => {
const sender = makeSender({ faces: { retCode: 0 } });
await expect(FetchCustomFaceList.invoke(sender, { uin: SAMPLE_UIN })).resolves.toEqual([]);
});
it('throws when the sender reports no response', async () => {
const sender = makeSender({
success: false,
gotResponse: false,
errorMessage: 'timeout',
responseData: null,
});
await expect(FetchCustomFaceList.invoke(sender, { uin: SAMPLE_UIN })).rejects.toThrow(/timeout/);
});
it('throws when the Faceroam retCode is non-zero', async () => {
const sender = makeSender({ faces: { retCode: 1, message: 'denied' } });
await expect(FetchCustomFaceList.invoke(sender, { uin: SAMPLE_UIN })).rejects.toThrow(
/fetch custom face error: denied/,
);
});
});
});