feat(onebot): implement collection list retrieval

Replace the get_collection_list placeholder with authenticated, read-only collection retrieval through the existing bridge API.

Add strict binary envelope validation, bounded pagination, accurate category filtering, preserved 64-bit identifiers, and explicit ticket, transport, service, and malformed-response failures. Cap item counts, page traversal, response bytes, per-request waits, and the total operation time.

Expose the compatible response model through Core, OneBot, the SDK, and the generated MCP catalog. Cover protocol framing, cursor behavior, filtered hasMore semantics, cleanup failures, bridge ticket acquisition, and Action validation with regression tests.

Verified with the live test bot without changing native components or adding any collection write behavior.
This commit is contained in:
DrSmoothl committed 2026-07-19 20:22:16 +08:00
1 parent 4e62fdc80b
commit 810d72fa04
15 files changed
+1912 -20

No files matched your search

@@ -0,0 +1,28 @@
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import {
getCollectionList,
type CollectionListResult,
} from '@snowluma/protocol/web/collection';
import type { BridgeContext } from '../bridge-context';
const COLLECTION_DOMAIN = 'weiyun.com';
/** Read-only access to the account's QQ collection list. */
export class CollectionApi {
constructor(private readonly ctx: BridgeContext) {}
async list(category = 0, count = 50): Promise<CollectionListResult> {
const { domainPskeyMap } = await GetPskey.invoke(this.ctx, {
domainList: [COLLECTION_DOMAIN],
});
const pskey = domainPskeyMap.get(COLLECTION_DOMAIN);
if (!pskey) throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`);
return getCollectionList({
uin: this.ctx.identity.uin,
pskey,
category,
count,
});
}
}
+5 -1
View File
@@ -1,4 +1,5 @@
import type { BridgeContext } from '../bridge-context';
import { CollectionApi } from './collection';
import { ContactsApi } from './contacts';
import { ExtrasApi } from './extras';
import { FlashTransferApi } from './flash-transfer';
@@ -15,6 +16,8 @@ import { QzoneApi } from './qzone';
import { WebApi } from './web';
export interface ApiHub {
/** Personal QQ collections: authenticated list retrieval and pagination. */
readonly collection: CollectionApi;
/** Send/recall/markRead operations across c2c + group + c2c-file. */
readonly message: MessageApi;
/** Friend / group / member roster + user-profile + group-request-list + download-rkey. */
@@ -55,6 +58,7 @@ export interface ApiHub {
*/
export function buildApiHub(ctx: BridgeContext): ApiHub {
return {
collection: new CollectionApi(ctx),
message: new MessageApi(ctx),
contacts: new ContactsApi(ctx),
groupAdmin: new GroupAdminApi(ctx),
@@ -76,6 +80,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub {
// `import type { MessageApi } from '@snowluma/core/.../apis'` for
// signature use. Concrete instances always come from `bridge.apis.*`.
export { ContactsApi } from './contacts';
export { CollectionApi } from './collection';
export { ExtrasApi } from './extras';
export { ForwardApi } from './forward';
export { FriendApi } from './friend';
@@ -89,4 +94,3 @@ export { ProfileApi } from './profile';
export { QzoneApi } from './qzone';
export { FlashTransferApi, type FlashFileInfo } from './flash-transfer';
export { WebApi } from './web';
@@ -0,0 +1,47 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import * as collectionWeb from '@snowluma/protocol/web/collection';
import { CollectionApi } from '../../src/bridge/apis/collection';
import { mockBridge } from './_helpers';
describe('apis/collection', () => {
afterEach(() => vi.restoreAllMocks());
it('obtains a Weiyun p_skey and fetches the collection list', async () => {
const bridge = mockBridge();
const expected = {
errCode: 0 as const,
errMsg: '',
collectionSearchList: {
collectionItemList: [],
hasMore: false,
bottomTimeStamp: '0',
},
};
const ticketSpy = vi.spyOn(GetPskey, 'invoke').mockResolvedValue({
domainPskeyMap: new Map([['weiyun.com', 'weiyun-ticket']]),
});
const listSpy = vi.spyOn(collectionWeb, 'getCollectionList').mockResolvedValue(expected);
const result = await new CollectionApi(bridge as never).list(4, 25);
expect(ticketSpy).toHaveBeenCalledWith(bridge, { domainList: ['weiyun.com'] });
expect(listSpy).toHaveBeenCalledWith({
uin: '10001',
pskey: 'weiyun-ticket',
category: 4,
count: 25,
});
expect(result).toBe(expected);
});
it('fails explicitly when QQ does not return a Weiyun p_skey', async () => {
const bridge = mockBridge();
vi.spyOn(GetPskey, 'invoke').mockResolvedValue({ domainPskeyMap: new Map() });
const listSpy = vi.spyOn(collectionWeb, 'getCollectionList');
await expect(new CollectionApi(bridge as never).list(0, 50))
.rejects.toThrow('QQ did not return a p_skey for weiyun.com');
expect(listSpy).not.toHaveBeenCalled();
});
});
+226 -6
View File
@@ -2410,18 +2410,238 @@
{
"name": "get_collection_list",
"aliases": [],
"summary": "获取收藏列表(占位)",
"returns": "占位实现,恒返回空数组。",
"summary": "获取收藏列表",
"returns": "返回收藏条目、是否还有更多数据及底部时间游标。",
"returnsSchema": {
"type": "array",
"description": "收藏列表(占位,恒空)"
"type": "object",
"properties": {
"errCode": {
"type": "integer"
},
"errMsg": {
"type": "string"
},
"collectionSearchList": {
"type": "object",
"properties": {
"collectionItemList": {
"type": "array",
"items": {
"type": "object",
"properties": {
"cid": {
"type": "string"
},
"type": {
"type": "integer"
},
"status": {
"type": "integer"
},
"author": {
"type": "object",
"properties": {
"type": {
"type": "integer"
},
"numId": {
"type": "string"
},
"strId": {
"type": "string"
},
"groupId": {
"type": "string"
},
"groupName": {
"type": "string"
},
"uid": {
"type": "string"
}
},
"required": [
"type",
"numId",
"strId",
"groupId",
"groupName",
"uid"
]
},
"bid": {
"type": "integer"
},
"category": {
"type": "integer"
},
"createTime": {
"type": "string"
},
"collectTime": {
"type": "string"
},
"modifyTime": {
"type": "string"
},
"sequence": {
"type": "string"
},
"shareUrl": {
"type": "string"
},
"customGroupId": {
"type": "integer"
},
"securityBeat": {
"type": "boolean"
},
"summary": {
"type": "object",
"properties": {
"textSummary": {
"type": [
"object",
"null"
]
},
"linkSummary": {
"type": [
"object",
"null"
]
},
"gallerySummary": {
"type": [
"object",
"null"
]
},
"audioSummary": {
"type": [
"object",
"null"
]
},
"videoSummary": {
"type": [
"object",
"null"
]
},
"fileSummary": {
"type": [
"object",
"null"
]
},
"locationSummary": {
"type": [
"object",
"null"
]
},
"richMediaSummary": {
"type": [
"object",
"null"
]
}
},
"required": [
"textSummary",
"linkSummary",
"gallerySummary",
"audioSummary",
"videoSummary",
"fileSummary",
"locationSummary",
"richMediaSummary"
]
}
},
"required": [
"cid",
"type",
"status",
"author",
"bid",
"category",
"createTime",
"collectTime",
"modifyTime",
"sequence",
"shareUrl",
"customGroupId",
"securityBeat",
"summary"
]
}
},
"hasMore": {
"type": "boolean"
},
"bottomTimeStamp": {
"type": "string"
}
},
"required": [
"collectionItemList",
"hasMore",
"bottomTimeStamp"
]
}
},
"required": [
"errCode",
"errMsg",
"collectionSearchList"
]
},
"readOnly": true,
"params": [],
"params": [
{
"name": "category",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0
},
"desc": "收藏分类 ID;0 表示全部分类",
"default": 0
},
{
"name": "count",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 500
},
"desc": "最多返回的收藏数量",
"default": 50
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {},
"properties": {
"category": {
"type": "integer",
"minimum": 0,
"description": "收藏分类 ID;0 表示全部分类",
"default": 0
},
"count": {
"type": "integer",
"minimum": 1,
"maximum": 500,
"description": "最多返回的收藏数量",
"default": 50
}
},
"additionalProperties": true
},
"category": "扩展"
+226 -6
View File
@@ -2413,18 +2413,238 @@ export const ACTIONS: CatalogAction[] = [
{
"name": "get_collection_list",
"aliases": [],
"summary": "获取收藏列表(占位)",
"returns": "占位实现,恒返回空数组。",
"summary": "获取收藏列表",
"returns": "返回收藏条目、是否还有更多数据及底部时间游标。",
"returnsSchema": {
"type": "array",
"description": "收藏列表(占位,恒空)"
"type": "object",
"properties": {
"errCode": {
"type": "integer"
},
"errMsg": {
"type": "string"
},
"collectionSearchList": {
"type": "object",
"properties": {
"collectionItemList": {
"type": "array",
"items": {
"type": "object",
"properties": {
"cid": {
"type": "string"
},
"type": {
"type": "integer"
},
"status": {
"type": "integer"
},
"author": {
"type": "object",
"properties": {
"type": {
"type": "integer"
},
"numId": {
"type": "string"
},
"strId": {
"type": "string"
},
"groupId": {
"type": "string"
},
"groupName": {
"type": "string"
},
"uid": {
"type": "string"
}
},
"required": [
"type",
"numId",
"strId",
"groupId",
"groupName",
"uid"
]
},
"bid": {
"type": "integer"
},
"category": {
"type": "integer"
},
"createTime": {
"type": "string"
},
"collectTime": {
"type": "string"
},
"modifyTime": {
"type": "string"
},
"sequence": {
"type": "string"
},
"shareUrl": {
"type": "string"
},
"customGroupId": {
"type": "integer"
},
"securityBeat": {
"type": "boolean"
},
"summary": {
"type": "object",
"properties": {
"textSummary": {
"type": [
"object",
"null"
]
},
"linkSummary": {
"type": [
"object",
"null"
]
},
"gallerySummary": {
"type": [
"object",
"null"
]
},
"audioSummary": {
"type": [
"object",
"null"
]
},
"videoSummary": {
"type": [
"object",
"null"
]
},
"fileSummary": {
"type": [
"object",
"null"
]
},
"locationSummary": {
"type": [
"object",
"null"
]
},
"richMediaSummary": {
"type": [
"object",
"null"
]
}
},
"required": [
"textSummary",
"linkSummary",
"gallerySummary",
"audioSummary",
"videoSummary",
"fileSummary",
"locationSummary",
"richMediaSummary"
]
}
},
"required": [
"cid",
"type",
"status",
"author",
"bid",
"category",
"createTime",
"collectTime",
"modifyTime",
"sequence",
"shareUrl",
"customGroupId",
"securityBeat",
"summary"
]
}
},
"hasMore": {
"type": "boolean"
},
"bottomTimeStamp": {
"type": "string"
}
},
"required": [
"collectionItemList",
"hasMore",
"bottomTimeStamp"
]
}
},
"required": [
"errCode",
"errMsg",
"collectionSearchList"
]
},
"readOnly": true,
"params": [],
"params": [
{
"name": "category",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0
},
"desc": "收藏分类 ID;0 表示全部分类",
"default": 0
},
{
"name": "count",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 500
},
"desc": "最多返回的收藏数量",
"default": 50
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {},
"properties": {
"category": {
"type": "integer",
"minimum": 0,
"description": "收藏分类 ID;0 表示全部分类",
"default": 0
},
"count": {
"type": "integer",
"minimum": 1,
"maximum": 500,
"description": "最多返回的收藏数量",
"default": 50
}
},
"additionalProperties": true
},
"category": "扩展"
+95 -6
View File
@@ -1515,13 +1515,102 @@ export const actions = [
defineAction({
name: 'get_collection_list',
summary: '获取收藏列表(占位)',
summary: '获取收藏列表',
readOnly: true,
returns: '占位实现,恒返回空数组。',
returnsSchema: { type: 'array', description: '收藏列表(占位,恒空)' },
params: {},
run: async () => {
return okResponse([]);
returns: '返回收藏条目、是否还有更多数据及底部时间游标。',
returnsSchema: {
type: 'object',
properties: {
errCode: { type: 'integer' },
errMsg: { type: 'string' },
collectionSearchList: {
type: 'object',
properties: {
collectionItemList: {
type: 'array',
items: {
type: 'object',
properties: {
cid: { type: 'string' },
type: { type: 'integer' },
status: { type: 'integer' },
author: {
type: 'object',
properties: {
type: { type: 'integer' },
numId: { type: 'string' },
strId: { type: 'string' },
groupId: { type: 'string' },
groupName: { type: 'string' },
uid: { type: 'string' },
},
required: ['type', 'numId', 'strId', 'groupId', 'groupName', 'uid'],
},
bid: { type: 'integer' },
category: { type: 'integer' },
createTime: { type: 'string' },
collectTime: { type: 'string' },
modifyTime: { type: 'string' },
sequence: { type: 'string' },
shareUrl: { type: 'string' },
customGroupId: { type: 'integer' },
securityBeat: { type: 'boolean' },
summary: {
type: 'object',
properties: {
textSummary: { type: ['object', 'null'] },
linkSummary: { type: ['object', 'null'] },
gallerySummary: { type: ['object', 'null'] },
audioSummary: { type: ['object', 'null'] },
videoSummary: { type: ['object', 'null'] },
fileSummary: { type: ['object', 'null'] },
locationSummary: { type: ['object', 'null'] },
richMediaSummary: { type: ['object', 'null'] },
},
required: [
'textSummary',
'linkSummary',
'gallerySummary',
'audioSummary',
'videoSummary',
'fileSummary',
'locationSummary',
'richMediaSummary',
],
},
},
required: [
'cid',
'type',
'status',
'author',
'bid',
'category',
'createTime',
'collectTime',
'modifyTime',
'sequence',
'shareUrl',
'customGroupId',
'securityBeat',
'summary',
],
},
},
hasMore: { type: 'boolean' },
bottomTimeStamp: { type: 'string' },
},
required: ['collectionItemList', 'hasMore', 'bottomTimeStamp'],
},
},
required: ['errCode', 'errMsg', 'collectionSearchList'],
},
params: {
category: f.int({ min: 0 }).describe('收藏分类 ID;0 表示全部分类').default(0),
count: f.int({ min: 1, max: 500 }).describe('最多返回的收藏数量').default(50),
},
run: async (p, ctx) => {
return okResponse(await ctx.bridge.apis.collection.list(p.category, p.count));
},
}),
@@ -0,0 +1,60 @@
import { describe, expect, it, vi } from 'vitest';
import type { ApiActionContext } from '../src/api-handler';
import { ApiHandler } from '../src/api-handler';
import { ACTION_REGISTRY } from '../src/actions';
describe('get_collection_list action', () => {
it('validates and forwards category and count to the collection API', async () => {
const result = {
errCode: 0 as const,
errMsg: '',
collectionSearchList: {
collectionItemList: [],
hasMore: false,
bottomTimeStamp: '0',
},
};
const list = vi.fn(async () => result);
const bridge = { apis: { collection: { list } } };
const handler = new ApiHandler({ bridge } as unknown as ApiActionContext);
const response = await handler.handle('get_collection_list', {
category: '4',
count: '25',
});
expect(response).toMatchObject({ status: 'ok', retcode: 0, data: result });
expect(list).toHaveBeenCalledWith(4, 25);
const registered = ACTION_REGISTRY.resolve('get_collection_list');
if (!registered || registered.kind === 'raw') throw new Error('get_collection_list is not registered');
expect(registered.action.doc.summary).toBe('获取收藏列表');
expect(registered.action.doc.params.map((param) => param.name)).toEqual(['category', 'count']);
const itemSchema = registered.action.doc.returnsSchema?.properties
?.collectionSearchList?.properties?.collectionItemList?.items;
expect(Object.keys(itemSchema?.properties ?? {})).toEqual(expect.arrayContaining([
'cid', 'author', 'category', 'modifyTime', 'summary',
]));
expect(Object.keys(itemSchema?.properties?.summary?.properties ?? {})).toEqual([
'textSummary',
'linkSummary',
'gallerySummary',
'audioSummary',
'videoSummary',
'fileSummary',
'locationSummary',
'richMediaSummary',
]);
});
it.each([0, 501])('rejects invalid count %s before calling the collection API', async (count) => {
const list = vi.fn();
const bridge = { apis: { collection: { list } } };
const handler = new ApiHandler({ bridge } as unknown as ApiActionContext);
const response = await handler.handle('get_collection_list', { category: 0, count });
expect(response).toMatchObject({ status: 'failed', retcode: 1400 });
expect(list).not.toHaveBeenCalled();
});
});
+4
View File
@@ -16,6 +16,10 @@
"types": "./src/action.ts",
"default": "./src/action.ts"
},
"./collection": {
"types": "./src/collection.ts",
"default": "./src/collection.ts"
},
"./element": {
"types": "./src/element.ts",
"default": "./src/element.ts"
+201
View File
@@ -0,0 +1,201 @@
import type {
bool,
bytes,
double,
int_32,
pb,
pb_repeated,
uint_32,
uint_64,
} from '@snowluma/proton';
/** Weiyun collector common request header. */
export interface CollectionRequestHead {
uin?: pb<1, uint_64>;
sequence?: pb<2, uint_32>;
commandType?: pb<3, uint_32>;
operationId?: pb<4, uint_32>;
clientVersion?: pb<5, uint_64>;
platform?: pb<6, uint_32>;
ticketType?: pb<7, uint_32>;
reserved?: pb<10, uint_32>;
ticket?: pb<11, string>;
field14?: pb<14, uint_32>;
field15?: pb<15, uint_32>;
}
/** Weiyun collector common response header. */
export interface CollectionResponseHead {
retCode?: pb<101, int_32>;
retMsg?: pb<102, string>;
promptMsg?: pb<103, string>;
}
export interface GetCollectionListRequest {
field1?: pb<1, uint_32>;
field2?: pb<2, uint_32>;
field3?: pb<3, uint_32>;
timeStamp?: pb<4, uint_64>;
orderType?: pb<5, uint_32>;
groupId?: pb<6, uint_64>;
count?: pb<7, uint_32>;
searchDown?: pb<8, uint_32>;
field9?: pb<9, uint_32>;
}
export interface CollectionRequestOperation {
getCollectionList?: pb<20000, GetCollectionListRequest>;
}
export interface CollectionRequestBody {
operation?: pb<1, CollectionRequestOperation>;
}
export interface CollectionAuthor {
type?: pb<1, uint_32>;
numId?: pb<2, uint_64>;
strId?: pb<3, string>;
groupId?: pb<4, uint_64>;
groupName?: pb<5, string>;
uid?: pb<6, string>;
}
export interface CollectionPictureInfo {
url?: pb<1, string>;
field2?: pb<2, bytes>;
field3?: pb<3, bytes>;
field4?: pb<4, string>;
field5?: pb<5, string>;
field6?: pb<6, uint_32>;
field7?: pb<7, uint_32>;
field8?: pb<8, uint_32>;
field9?: pb<9, uint_32>;
author?: pb<10, CollectionAuthor>;
field11?: pb<11, string>;
}
export interface CollectionFileInfo {
field1?: pb<1, uint_32>;
field2?: pb<2, uint_64>;
field3?: pb<3, uint_32>;
field4?: pb<4, string>;
field5?: pb<5, string>;
field6?: pb<6, uint_64>;
field7?: pb<7, bytes>;
field8?: pb<8, bytes>;
field9?: pb<9, uint_32>;
field10?: pb<10, string>;
}
export interface CollectionTextSummary {
text?: pb<1, string>;
truncated?: pb<2, bool>;
}
export interface CollectionRichMediaSummary {
title?: pb<1, string>;
subTitle?: pb<2, string>;
brief?: pb<3, string>;
picList?: pb_repeated<4, CollectionPictureInfo>;
contentType?: pb<5, uint_32>;
originalUri?: pb<6, string>;
publisher?: pb<7, string>;
richMediaVersion?: pb<8, uint_32>;
}
export interface CollectionGallerySummary {
picList?: pb_repeated<1, CollectionPictureInfo>;
field2?: pb<2, string>;
}
export interface CollectionAudioSummary {
field1?: pb<1, uint_32>;
field2?: pb<2, string>;
field3?: pb<3, string>;
}
export interface CollectionVideoSummary {
field1?: pb<1, string>;
field2?: pb<2, uint_32>;
field3?: pb<3, uint_32>;
field10?: pb<10, uint_32>;
field20?: pb<20, uint_32>;
picture?: pb<21, CollectionPictureInfo>;
field30?: pb<30, uint_32>;
file?: pb<31, CollectionFileInfo>;
}
export interface CollectionFileSummary {
first?: pb<1, CollectionFileInfo>;
second?: pb<2, CollectionFileInfo>;
}
export interface CollectionLocationSummary {
name?: pb<1, string>;
latitude?: pb<2, double>;
longitude?: pb<3, double>;
altitude?: pb<4, double>;
field5?: pb<5, string>;
field6?: pb<6, string>;
}
export interface CollectionLinkSummary {
title?: pb<1, string>;
description?: pb<2, string>;
url?: pb<3, string>;
picList?: pb_repeated<4, CollectionPictureInfo>;
contentType?: pb<5, uint_32>;
originalUri?: pb<6, string>;
publisher?: pb<7, string>;
version?: pb<8, uint_32>;
}
export interface CollectionSummary {
textSummary?: pb<1, CollectionTextSummary>;
richMediaSummary?: pb<2, CollectionRichMediaSummary>;
gallerySummary?: pb<3, CollectionGallerySummary>;
audioSummary?: pb<4, CollectionAudioSummary>;
videoSummary?: pb<5, CollectionVideoSummary>;
fileSummary?: pb<6, CollectionFileSummary>;
locationSummary?: pb<7, CollectionLocationSummary>;
linkSummary?: pb<8, CollectionLinkSummary>;
}
export interface CollectionItem {
cid?: pb<1, string>;
type?: pb<2, uint_32>;
status?: pb<3, uint_32>;
author?: pb<4, CollectionAuthor>;
bid?: pb<5, uint_32>;
field6?: pb<6, uint_32>;
field7?: pb<7, string>;
category?: pb<8, uint_32>;
createTime?: pb<9, uint_64>;
collectTime?: pb<10, uint_64>;
modifyTime?: pb<11, uint_64>;
sequence?: pb<12, uint_64>;
field13?: pb<13, string>;
field14?: pb_repeated<14, string>;
summary?: pb<15, CollectionSummary>;
field16?: pb<16, bool>;
field17?: pb<17, uint_64>;
shareUrl?: pb<18, string>;
field19?: pb<19, uint_32>;
customGroupId?: pb<20, uint_32>;
securityBeat?: pb<21, bool>;
field506?: pb<506, string>;
}
export interface GetCollectionListResponse {
items?: pb_repeated<1, CollectionItem>;
totalCount?: pb<2, uint_32>;
reachedBottom?: pb<3, uint_32>;
}
export interface CollectionResponseOperation {
getCollectionList?: pb<20000, GetCollectionListResponse>;
}
export interface CollectionResponseBody {
operation?: pb<2, CollectionResponseOperation>;
}
+1
View File
@@ -21,6 +21,7 @@
// imports below for any NTV2-named type.
export type * from './action.js';
export type * from './collection.js';
export type * from './element.js';
// NOTE: `highway.ts` intentionally NOT re-exported here — see note above.
export type * from './longmsg.js';
+448
View File
@@ -0,0 +1,448 @@
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import type {
CollectionItem as CollectionItemWire,
CollectionRequestBody,
CollectionRequestHead,
CollectionResponseBody,
CollectionResponseHead,
GetCollectionListRequest,
} from '@snowluma/proto-defs/collection';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
const COLLECTION_ENDPOINT = 'https://collector.weiyun.com/collector.fcg';
const COLLECTION_HOST = 'collector.weiyun.com';
const COLLECTION_OPERATION_ID = 20_000;
const COLLECTION_TICKET_TYPE = 27;
const COLLECTION_APP_ID = 5_004;
const COLLECTION_PAGE_SIZE = 50;
const COLLECTION_MAX_COUNT = 500;
const COLLECTION_MAX_PAGES = 100;
const COLLECTION_TIMEOUT_MS = 10_000;
const COLLECTION_OPERATION_TIMEOUT_MS = 60_000;
const COLLECTION_RESPONSE_LIMIT = 16 * 1024 * 1024;
const INITIAL_TIMESTAMP = 0xFFFF_FFFF_FFFF_FFFFn;
const MAGIC = Uint8Array.from([0x20, 0x13, 0x03, 0x29]);
const VERSION = Uint8Array.from([0x00, 0x01]);
export interface CollectionHttpRequest {
readonly url: string;
readonly headers: Readonly<Record<string, string>>;
readonly body: Uint8Array;
readonly timeoutMs: number;
}
export type CollectionTransport = (request: CollectionHttpRequest) => Promise<Uint8Array>;
export interface GetCollectionListParams {
readonly uin: string;
readonly pskey: string;
readonly category?: number;
readonly count?: number;
readonly transport?: CollectionTransport;
}
export interface CollectionAuthor extends JsonObject {
type: number;
numId: string;
strId: string;
groupId: string;
groupName: string;
uid: string;
}
export interface CollectionSummary extends JsonObject {
textSummary: JsonValue;
linkSummary: JsonValue;
gallerySummary: JsonValue;
audioSummary: JsonValue;
videoSummary: JsonValue;
fileSummary: JsonValue;
locationSummary: JsonValue;
richMediaSummary: JsonValue;
}
export interface CollectionItem extends JsonObject {
cid: string;
type: number;
status: number;
author: CollectionAuthor;
bid: number;
category: number;
createTime: string;
collectTime: string;
modifyTime: string;
sequence: string;
shareUrl: string;
customGroupId: number;
securityBeat: boolean;
summary: CollectionSummary;
}
export interface CollectionSearchList extends JsonObject {
collectionItemList: CollectionItem[];
hasMore: boolean;
bottomTimeStamp: string;
}
export interface CollectionListResult extends JsonObject {
errCode: 0;
errMsg: string;
collectionSearchList: CollectionSearchList;
}
function positiveUin(value: string): bigint {
if (!/^[1-9]\d*$/.test(value)) throw new Error('collection uin must be a positive integer');
const uin = BigInt(value);
if (uin > INITIAL_TIMESTAMP) throw new Error('collection uin exceeds uint64 range');
return uin;
}
function positiveCount(value: number): number {
if (!Number.isSafeInteger(value) || value < 1 || value > COLLECTION_MAX_COUNT) {
throw new Error(`collection count must be between 1 and ${COLLECTION_MAX_COUNT}`);
}
return value;
}
function validCategory(value: number): number {
if (!Number.isSafeInteger(value) || value < 0) {
throw new Error('collection category must be a non-negative safe integer');
}
return value;
}
function encodeEnvelope(head: Uint8Array, body: Uint8Array): Uint8Array {
const totalLength = 16 + head.length + body.length;
const output = Buffer.allocUnsafe(totalLength);
output.set(MAGIC, 0);
output.set(VERSION, 4);
output.writeUInt32BE(totalLength, 6);
output.writeUInt32BE(body.length, 10);
output.writeUInt16BE(0, 14);
output.set(head, 16);
output.set(body, 16 + head.length);
return output;
}
function decodeEnvelope(bytes: Uint8Array): {
head: CollectionResponseHead;
body: CollectionResponseBody;
} {
const input = Buffer.from(bytes);
if (input.length <= 16) throw new Error('collection response is too short');
if (!input.subarray(0, 4).equals(Buffer.from(MAGIC))) {
throw new Error('collection response has invalid magic');
}
if (!input.subarray(4, 6).equals(Buffer.from(VERSION))) {
throw new Error('collection response has unsupported version');
}
const totalLength = input.readUInt32BE(6);
if (totalLength !== input.length) {
throw new Error(`collection response length mismatch: ${totalLength} != ${input.length}`);
}
const bodyLength = input.readUInt32BE(10);
if (input.readUInt16BE(14) !== 0) throw new Error('collection response has invalid reserved bytes');
if (bodyLength === 0 || bodyLength >= totalLength - 16) {
throw new Error('collection response has invalid body length');
}
const bodyOffset = totalLength - bodyLength;
return {
head: protobuf_decode<CollectionResponseHead>(input.subarray(16, bodyOffset)),
body: protobuf_decode<CollectionResponseBody>(input.subarray(bodyOffset)),
};
}
function jsonSafe(value: unknown): JsonValue {
if (value === null || value === undefined) return null;
if (typeof value === 'bigint') return value.toString();
if (typeof value === 'number') {
if (!Number.isFinite(value)) throw new Error('collection response contains a non-finite number');
return value;
}
if (typeof value === 'string' || typeof value === 'boolean') return value;
if (value instanceof Uint8Array) return Buffer.from(value).toString('base64');
if (Array.isArray(value)) return value.map(jsonSafe);
if (typeof value === 'object') {
const output: JsonObject = {};
for (const [key, field] of Object.entries(value)) output[key] = jsonSafe(field);
return output;
}
throw new Error(`collection response contains unsupported value type: ${typeof value}`);
}
function mapItem(item: CollectionItemWire): CollectionItem {
const author = item.author ?? {};
const summary = item.summary ?? {};
const textSummary = summary.textSummary;
const richMediaSummary = summary.richMediaSummary;
return {
cid: item.cid ?? '',
type: item.type ?? 0,
status: item.status ?? 0,
author: {
type: author.type ?? 0,
numId: (author.numId ?? 0n).toString(),
strId: author.strId ?? '',
groupId: (author.groupId ?? 0n).toString(),
groupName: author.groupName ?? '',
uid: author.uid ?? '',
},
bid: item.bid ?? 0,
category: item.category ?? 0,
createTime: (item.createTime ?? 0n).toString(),
collectTime: (item.collectTime ?? 0n).toString(),
modifyTime: (item.modifyTime ?? 0n).toString(),
sequence: (item.sequence ?? 0n).toString(),
shareUrl: item.shareUrl ?? '',
customGroupId: item.customGroupId ?? 0,
securityBeat: item.securityBeat ?? false,
summary: {
textSummary: textSummary ? {
text: textSummary.text ?? '',
truncated: textSummary.truncated ?? false,
} : null,
linkSummary: jsonSafe(summary.linkSummary),
gallerySummary: jsonSafe(summary.gallerySummary),
audioSummary: jsonSafe(summary.audioSummary),
videoSummary: jsonSafe(summary.videoSummary),
fileSummary: jsonSafe(summary.fileSummary),
locationSummary: jsonSafe(summary.locationSummary),
richMediaSummary: richMediaSummary ? {
title: richMediaSummary.title ?? '',
subTitle: richMediaSummary.subTitle ?? '',
brief: richMediaSummary.brief ?? '',
picList: jsonSafe(richMediaSummary.picList ?? []),
contentType: richMediaSummary.contentType ?? 0,
originalUri: richMediaSummary.originalUri ?? '',
publisher: richMediaSummary.publisher ?? '',
richMediaVersion: richMediaSummary.richMediaVersion ?? 0,
} : null,
},
};
}
function validateItem(item: CollectionItemWire): void {
if (!item.cid) throw new Error('collection item is missing cid');
if (!item.author) throw new Error(`collection item ${item.cid} is missing author`);
if (item.modifyTime === null || item.modifyTime === undefined || item.modifyTime <= 0n) {
throw new Error(`collection item ${item.cid} is missing modifyTime`);
}
}
async function failAfterCleanup(
primaryError: Error,
cleanup?: () => Promise<void>,
): Promise<never> {
if (cleanup) {
try {
await cleanup();
} catch (cleanupError) {
throw new AggregateError(
[primaryError, cleanupError],
`${primaryError.message}; response body cleanup also failed`,
);
}
}
throw primaryError;
}
async function defaultTransport(request: CollectionHttpRequest): Promise<Uint8Array> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), request.timeoutMs);
try {
const response = await fetch(request.url, {
method: 'POST',
headers: request.headers,
body: Buffer.from(request.body),
signal: controller.signal,
});
if (!response.ok) {
const error = new Error(`collection HTTP request failed: ${response.status} ${response.statusText}`);
await failAfterCleanup(
error,
response.body ? () => response.body!.cancel(error) : undefined,
);
}
const declaredLength = response.headers.get('content-length');
if (declaredLength !== null) {
if (!/^\d+$/.test(declaredLength)) {
const error = new Error('collection response has invalid content-length');
await failAfterCleanup(
error,
response.body ? () => response.body!.cancel(error) : undefined,
);
}
if (Number(declaredLength) > COLLECTION_RESPONSE_LIMIT) {
const error = new Error(`collection response exceeds ${COLLECTION_RESPONSE_LIMIT} bytes`);
await failAfterCleanup(
error,
response.body ? () => response.body!.cancel(error) : undefined,
);
}
}
if (!response.body) throw new Error('collection HTTP response has no body');
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let total = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
total += value.length;
if (total > COLLECTION_RESPONSE_LIMIT) {
const error = new Error(`collection response exceeds ${COLLECTION_RESPONSE_LIMIT} bytes`);
await failAfterCleanup(error, () => reader.cancel(error));
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const output = Buffer.allocUnsafe(total);
let offset = 0;
for (const chunk of chunks) {
output.set(chunk, offset);
offset += chunk.length;
}
return output;
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
throw new Error(`collection HTTP request timed out after ${request.timeoutMs}ms`, { cause: error });
}
throw error;
} finally {
clearTimeout(timeout);
}
}
function requestBytes(uin: bigint, pskey: string, sequence: number, timeStamp: bigint): Uint8Array {
const head = protobuf_encode<CollectionRequestHead>({
uin,
sequence,
commandType: 1,
operationId: COLLECTION_OPERATION_ID,
clientVersion: 0x6105F5E164Fn,
platform: 4,
ticketType: COLLECTION_TICKET_TYPE,
reserved: 0,
ticket: pskey,
field14: 8,
field15: 9,
});
const request: GetCollectionListRequest = {
field1: 0,
field2: 0,
field3: 0,
timeStamp,
orderType: 2,
groupId: 0n,
count: COLLECTION_PAGE_SIZE,
searchDown: 1,
field9: 0,
};
const body = protobuf_encode<CollectionRequestBody>({
operation: { getCollectionList: request },
});
return encodeEnvelope(head, body);
}
export async function getCollectionList(params: GetCollectionListParams): Promise<CollectionListResult> {
const uin = positiveUin(params.uin);
if (params.pskey === '') throw new Error('collection p_skey is empty');
const category = validCategory(params.category ?? 0);
const count = positiveCount(params.count ?? COLLECTION_PAGE_SIZE);
const targetMatchCount = category === 0 ? count : count + 1;
const transport = params.transport ?? defaultTransport;
const headers = {
'Content-Type': 'application/octet-stream',
Cookie: `uin=${params.uin};vt=${COLLECTION_TICKET_TYPE};vi=${params.pskey};appid=${COLLECTION_APP_ID}`,
Host: COLLECTION_HOST,
Range: 'bytes=0-',
} as const;
const matched: CollectionItem[] = [];
const seen = new Set<string>();
let sequence = 1;
let timeStamp = INITIAL_TIMESTAMP;
let serverHasMore = true;
let errMsg = '';
let pages = 0;
const operationDeadline = Date.now() + COLLECTION_OPERATION_TIMEOUT_MS;
while (matched.length < targetMatchCount && serverHasMore) {
if (pages >= COLLECTION_MAX_PAGES) {
throw new Error(`collection pagination exceeded ${COLLECTION_MAX_PAGES} pages`);
}
const remainingMs = operationDeadline - Date.now();
if (remainingMs <= 0) {
throw new Error(`collection pagination exceeded ${COLLECTION_OPERATION_TIMEOUT_MS}ms`);
}
pages += 1;
const responseBytes = await transport({
url: COLLECTION_ENDPOINT,
headers,
body: requestBytes(uin, params.pskey, sequence, timeStamp),
timeoutMs: Math.min(COLLECTION_TIMEOUT_MS, remainingMs),
});
if (Date.now() >= operationDeadline) {
throw new Error(`collection pagination exceeded ${COLLECTION_OPERATION_TIMEOUT_MS}ms`);
}
const response = decodeEnvelope(responseBytes);
const retCode = response.head.retCode ?? 0;
if (retCode !== 0) {
const message = response.head.retMsg || response.head.promptMsg || 'unknown error';
throw new Error(`collection service error ${retCode}: ${message}`);
}
errMsg = response.head.retMsg ?? '';
const page = response.body.operation?.getCollectionList;
if (!page) throw new Error('collection response is missing operation 20000');
const wireItems = page.items ?? [];
serverHasMore = (page.reachedBottom ?? 0) === 0;
let nextTimeStamp: bigint | null = null;
for (const wireItem of wireItems) {
validateItem(wireItem);
const modifyTime = wireItem.modifyTime ?? 0n;
if (nextTimeStamp === null || modifyTime < nextTimeStamp) nextTimeStamp = modifyTime;
const item = mapItem(wireItem);
const identity = `cid:${item.cid}`;
if (seen.has(identity)) continue;
seen.add(identity);
if (category === 0 || item.category === category) matched.push(item);
}
if (matched.length >= targetMatchCount || !serverHasMore) break;
if (wireItems.length === 0 || nextTimeStamp === null || nextTimeStamp === 0n) {
throw new Error('collection pagination made no progress while more data was reported');
}
if (nextTimeStamp >= timeStamp) {
throw new Error(`collection pagination cursor did not decrease: ${nextTimeStamp}`);
}
timeStamp = nextTimeStamp;
sequence += 1;
}
const collectionItemList = matched.slice(0, count);
let publicBottomTimeStamp = 0n;
for (const item of collectionItemList) {
const itemTime = BigInt(item.modifyTime);
if (publicBottomTimeStamp === 0n || itemTime < publicBottomTimeStamp) {
publicBottomTimeStamp = itemTime;
}
}
return {
errCode: 0,
errMsg,
collectionSearchList: {
collectionItemList,
hasMore: category === 0 ? serverHasMore || matched.length > count : matched.length > count,
bottomTimeStamp: publicBottomTimeStamp.toString(),
},
};
}
@@ -0,0 +1,512 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { bool, int_32, pb, pb_repeated, uint_32, uint_64 } from '@snowluma/proton';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { getCollectionList } from '../../src/web/collection';
interface RequestHeadOracle {
uin?: pb<1, uint_64>;
sequence?: pb<2, uint_32>;
commandType?: pb<3, uint_32>;
operationId?: pb<4, uint_32>;
clientVersion?: pb<5, uint_64>;
platform?: pb<6, uint_32>;
ticketType?: pb<7, uint_32>;
reserved?: pb<10, uint_32>;
ticket?: pb<11, string>;
field14?: pb<14, uint_32>;
field15?: pb<15, uint_32>;
}
interface GetCollectionListRequestOracle {
field1?: pb<1, uint_32>;
field2?: pb<2, uint_32>;
field3?: pb<3, uint_32>;
timeStamp?: pb<4, uint_64>;
orderType?: pb<5, uint_32>;
groupId?: pb<6, uint_64>;
count?: pb<7, uint_32>;
searchDown?: pb<8, uint_32>;
field9?: pb<9, uint_32>;
}
interface RequestOperationOracle {
getCollectionList?: pb<20000, GetCollectionListRequestOracle>;
}
interface RequestBodyOracle {
operation?: pb<1, RequestOperationOracle>;
}
interface ResponseHeadOracle {
trace?: pb<1, string>;
retCode?: pb<101, int_32>;
retMsg?: pb<102, string>;
promptMsg?: pb<103, string>;
}
interface CollectionAuthorOracle {
type?: pb<1, uint_32>;
numId?: pb<2, uint_64>;
strId?: pb<3, string>;
groupId?: pb<4, uint_64>;
groupName?: pb<5, string>;
uid?: pb<6, string>;
}
interface CollectionTextSummaryOracle {
text?: pb<1, string>;
truncated?: pb<2, bool>;
}
interface CollectionSummaryOracle {
textSummary?: pb<1, CollectionTextSummaryOracle>;
}
interface CollectionItemOracle {
cid?: pb<1, string>;
type?: pb<2, uint_32>;
status?: pb<3, uint_32>;
author?: pb<4, CollectionAuthorOracle>;
bid?: pb<5, uint_32>;
category?: pb<8, uint_32>;
createTime?: pb<9, uint_64>;
collectTime?: pb<10, uint_64>;
modifyTime?: pb<11, uint_64>;
sequence?: pb<12, uint_64>;
summary?: pb<15, CollectionSummaryOracle>;
shareUrl?: pb<18, string>;
customGroupId?: pb<20, uint_32>;
securityBeat?: pb<21, bool>;
}
interface GetCollectionListResponseOracle {
items?: pb_repeated<1, CollectionItemOracle>;
totalCount?: pb<2, uint_32>;
reachedBottom?: pb<3, uint_32>;
}
interface ResponseOperationOracle {
getCollectionList?: pb<20000, GetCollectionListResponseOracle>;
}
interface ResponseBodyOracle {
operation?: pb<2, ResponseOperationOracle>;
}
function encodeEnvelope(head: Uint8Array, body: Uint8Array): Uint8Array {
const totalLength = 16 + head.length + body.length;
const output = Buffer.alloc(totalLength);
output.set([0x20, 0x13, 0x03, 0x29, 0x00, 0x01], 0);
output.writeUInt32BE(totalLength, 6);
output.writeUInt32BE(body.length, 10);
output.set(head, 16);
output.set(body, 16 + head.length);
return output;
}
function decodeRequestEnvelope(bytes: Uint8Array): {
head: RequestHeadOracle;
request: GetCollectionListRequestOracle;
} {
const input = Buffer.from(bytes);
expect(Array.from(input.subarray(0, 6))).toEqual([0x20, 0x13, 0x03, 0x29, 0x00, 0x01]);
expect(input.readUInt32BE(6)).toBe(input.length);
const bodyLength = input.readUInt32BE(10);
const headEnd = input.length - bodyLength;
const head = protobuf_decode<RequestHeadOracle>(input.subarray(16, headEnd));
const body = protobuf_decode<RequestBodyOracle>(input.subarray(headEnd));
const request = body.operation?.getCollectionList;
if (!request) throw new Error('missing collection request body');
return { head, request };
}
function successResponse(items: CollectionItemOracle[], reachedBottom = 1): Uint8Array {
return encodeEnvelope(
protobuf_encode<ResponseHeadOracle>({ trace: 'response' }),
protobuf_encode<ResponseBodyOracle>({
operation: {
getCollectionList: {
items,
totalCount: items.length,
reachedBottom,
},
},
}),
);
}
function errorResponse(retCode: number, retMsg: string): Uint8Array {
return encodeEnvelope(
protobuf_encode<ResponseHeadOracle>({ trace: 'response', retCode, retMsg }),
protobuf_encode<ResponseBodyOracle>({ operation: { getCollectionList: {} } }),
);
}
describe('getCollectionList', () => {
afterEach(() => vi.unstubAllGlobals());
it('uses the Weiyun collection envelope and maps the public result', async () => {
const transport = vi.fn(async (request: {
url: string;
headers: Readonly<Record<string, string>>;
body: Uint8Array;
timeoutMs: number;
}) => {
expect(request.url).toBe('https://collector.weiyun.com/collector.fcg');
expect(request.headers.Cookie).toBe('uin=10001;vt=27;vi=ticket-value;appid=5004');
expect(request.headers.Range).toBe('bytes=0-');
expect(request.timeoutMs).toBe(10_000);
const { head, request: body } = decodeRequestEnvelope(request.body);
expect(head).toMatchObject({
uin: 10001n,
sequence: 1,
commandType: 1,
operationId: 20000,
clientVersion: 0x6105F5E164Fn,
platform: 4,
ticketType: 27,
ticket: 'ticket-value',
field14: 8,
field15: 9,
});
expect(body).toMatchObject({
field1: null,
field2: null,
field3: null,
timeStamp: 0xFFFF_FFFF_FFFF_FFFFn,
orderType: 2,
groupId: null,
count: 50,
searchDown: 1,
field9: null,
});
return successResponse([{
cid: 'cid-1',
type: 1,
status: 0,
author: {
type: 2,
numId: 123n,
strId: 'author-id',
groupId: 456n,
groupName: 'group-name',
uid: 'u_author',
},
bid: 3,
category: 4,
createTime: 1_000n,
collectTime: 1_100n,
modifyTime: 1_200n,
sequence: 1_300n,
summary: { textSummary: { text: 'hello', truncated: false } },
shareUrl: 'https://example.invalid/share',
customGroupId: 5,
securityBeat: true,
}]);
});
const result = await getCollectionList({
uin: '10001',
pskey: 'ticket-value',
category: 0,
count: 50,
transport,
});
expect(result).toEqual({
errCode: 0,
errMsg: '',
collectionSearchList: {
collectionItemList: [{
cid: 'cid-1',
type: 1,
status: 0,
author: {
type: 2,
numId: '123',
strId: 'author-id',
groupId: '456',
groupName: 'group-name',
uid: 'u_author',
},
bid: 3,
category: 4,
createTime: '1000',
collectTime: '1100',
modifyTime: '1200',
sequence: '1300',
summary: {
textSummary: { text: 'hello', truncated: false },
linkSummary: null,
gallerySummary: null,
audioSummary: null,
videoSummary: null,
fileSummary: null,
locationSummary: null,
richMediaSummary: null,
},
shareUrl: 'https://example.invalid/share',
customGroupId: 5,
securityBeat: true,
}],
hasMore: false,
bottomTimeStamp: '1200',
},
});
expect(transport).toHaveBeenCalledTimes(1);
});
it('filters categories while following a strictly decreasing cursor', async () => {
const cursors: bigint[] = [];
const sequences: number[] = [];
const transport = vi.fn(async (request: { body: Uint8Array }) => {
const decoded = decodeRequestEnvelope(request.body);
cursors.push(decoded.request.timeStamp ?? 0n);
sequences.push(decoded.head.sequence ?? 0);
if (cursors.length === 1) {
return successResponse([{
cid: 'other',
author: { numId: 1n },
category: 2,
modifyTime: 1_200n,
}], 0);
}
return successResponse([{
cid: 'match',
author: { numId: 1n },
category: 4,
modifyTime: 900n,
}], 1);
});
const result = await getCollectionList({
uin: '10001',
pskey: 'ticket-value',
category: 4,
count: 1,
transport,
});
expect(cursors).toEqual([0xFFFF_FFFF_FFFF_FFFFn, 1_200n]);
expect(sequences).toEqual([1, 2]);
expect(result.collectionSearchList.collectionItemList.map((item) => item.cid)).toEqual(['match']);
expect(result.collectionSearchList.hasMore).toBe(false);
expect(result.collectionSearchList.bottomTimeStamp).toBe('900');
});
it('checks later pages before reporting more filtered collection items', async () => {
const transport = vi.fn(async (request: { body: Uint8Array }) => {
const { head } = decodeRequestEnvelope(request.body);
if (head.sequence === 1) {
return successResponse([{
cid: 'only-match',
author: { numId: 1n },
category: 4,
modifyTime: 1_200n,
}], 0);
}
return successResponse([{
cid: 'different-category',
author: { numId: 2n },
category: 2,
modifyTime: 1_100n,
}], 1);
});
const result = await getCollectionList({
uin: '10001',
pskey: 'ticket-value',
category: 4,
count: 1,
transport,
});
expect(transport).toHaveBeenCalledTimes(2);
expect(result.collectionSearchList.collectionItemList.map((item) => item.cid))
.toEqual(['only-match']);
expect(result.collectionSearchList.hasMore).toBe(false);
expect(result.collectionSearchList.bottomTimeStamp).toBe('1200');
});
it('surfaces explicit service failures instead of returning an empty list', async () => {
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
transport: async () => errorResponse(-17, 'denied'),
})).rejects.toThrow('collection service error -17: denied');
});
it('fails when the server reports more data without advancing pagination', async () => {
const response = successResponse([], 0);
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
category: 4,
count: 1,
transport: async () => response,
})).rejects.toThrow('collection pagination made no progress');
});
it('rejects an unbounded count before making a request', async () => {
const transport = vi.fn();
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
count: 501,
transport,
})).rejects.toThrow('collection count must be between 1 and 500');
expect(transport).not.toHaveBeenCalled();
});
it('stops after the explicit pagination budget', async () => {
let calls = 0;
const transport = vi.fn(async () => {
calls += 1;
return successResponse([{
cid: `other-${calls}`,
author: { numId: 1n },
category: 2,
modifyTime: BigInt(10_000 - calls),
}], 0);
});
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
category: 4,
count: 1,
transport,
})).rejects.toThrow('collection pagination exceeded 100 pages');
expect(transport).toHaveBeenCalledTimes(100);
});
it('bounds the total time spent paginating collection results', async () => {
vi.useFakeTimers();
try {
const timeouts: number[] = [];
let calls = 0;
const transport = vi.fn(async (request: { timeoutMs: number }) => {
calls += 1;
timeouts.push(request.timeoutMs);
vi.advanceTimersByTime(8_000);
return successResponse([{
cid: `other-${calls}`,
author: { numId: 1n },
category: 2,
modifyTime: BigInt(10_000 - calls),
}], 0);
});
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
category: 4,
count: 1,
transport,
})).rejects.toThrow('collection pagination exceeded 60000ms');
expect(transport).toHaveBeenCalledTimes(8);
expect(timeouts.slice(0, 7)).toEqual(Array(7).fill(10_000));
expect(timeouts[7]).toBe(4_000);
} finally {
vi.useRealTimers();
}
});
it.each([
[
'cid',
{ author: { numId: 1n }, modifyTime: 1n },
'collection item is missing cid',
],
[
'author',
{ cid: 'cid-1', modifyTime: 1n },
'collection item cid-1 is missing author',
],
[
'modifyTime',
{ cid: 'cid-1', author: { numId: 1n } },
'collection item cid-1 is missing modifyTime',
],
] as const)('rejects collection items missing required %s', async (_field, item, message) => {
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
transport: async () => successResponse([item], 1),
})).rejects.toThrow(message);
});
it('uses the last returned item for the public cursor when count truncates a page', async () => {
const result = await getCollectionList({
uin: '10001',
pskey: 'ticket-value',
count: 1,
transport: async () => successResponse([
{ cid: 'first', author: { numId: 1n }, modifyTime: 1_200n },
{ cid: 'not-returned', author: { numId: 2n }, modifyTime: 1_100n },
], 1),
});
expect(result.collectionSearchList.collectionItemList.map((item) => item.cid)).toEqual(['first']);
expect(result.collectionSearchList.bottomTimeStamp).toBe('1200');
expect(result.collectionSearchList.hasMore).toBe(true);
});
it('cancels a failed HTTP response body before surfacing the status', async () => {
const cancel = vi.fn();
const stream = new ReadableStream<Uint8Array>({ cancel });
vi.stubGlobal('fetch', vi.fn(async () => new Response(stream, {
status: 503,
statusText: 'Unavailable',
})));
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
})).rejects.toThrow('collection HTTP request failed: 503 Unavailable');
expect(cancel).toHaveBeenCalledOnce();
});
it.each([
['invalid', 'collection response has invalid content-length'],
[`${16 * 1024 * 1024 + 1}`, 'collection response exceeds 16777216 bytes'],
])('cancels response bodies rejected by content-length %s', async (contentLength, message) => {
const cancel = vi.fn();
const stream = new ReadableStream<Uint8Array>({ cancel });
vi.stubGlobal('fetch', vi.fn(async () => new Response(stream, {
headers: { 'Content-Length': contentLength },
})));
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
})).rejects.toThrow(message);
expect(cancel).toHaveBeenCalledOnce();
});
it('preserves both the primary response error and cancellation failure', async () => {
const primary = new Error('collection response has invalid content-length');
const cleanup = new Error('cancel failed');
const stream = new ReadableStream<Uint8Array>({
cancel: () => { throw cleanup; },
});
vi.stubGlobal('fetch', vi.fn(async () => new Response(stream, {
headers: { 'Content-Length': 'invalid' },
})));
let thrown: unknown;
try {
await getCollectionList({ uin: '10001', pskey: 'ticket-value' });
} catch (error) {
thrown = error;
}
expect(thrown).toBeInstanceOf(AggregateError);
const aggregate = thrown as AggregateError;
expect(aggregate.errors).toHaveLength(2);
expect(aggregate.errors[0]).toMatchObject({ message: primary.message });
expect(aggregate.errors[1]).toBe(cleanup);
});
});
+3 -1
View File
@@ -65,6 +65,7 @@ import type {
NcGetUserStatusParams,
GroupTodoParams,
GetAiCharactersParams,
GetCollectionListParams,
AiVoiceParams,
DeleteGroupFolderParams,
SendPacketParams,
@@ -97,6 +98,7 @@ import type {
AiCharacterCategory,
UserOnlineStatus,
SendGroupAiRecordResult,
CollectionListInfo,
} from './results';
export type ActionData = JsonValue;
@@ -207,7 +209,7 @@ export interface SnowLumaActionMap {
get_group_at_all_remain: { params: JsonObject; data: GroupAtAllRemainInfo };
get_unidirectional_friend_list: { params: JsonObject; data: JsonArray };
set_self_longnick: { params: JsonObject; data: EmptyData };
get_collection_list: { params: JsonObject; data: JsonArray };
get_collection_list: { params: GetCollectionListParams; data: CollectionListInfo };
create_collection: { params: JsonObject; data: JsonValue };
set_qq_avatar: { params: JsonObject; data: EmptyData };
set_input_status: { params: JsonObject; data: EmptyData };
+7
View File
@@ -297,6 +297,13 @@ export interface FetchCustomFaceParams extends JsonObject {
count?: number;
}
export interface GetCollectionListParams extends JsonObject {
/** Collection category ID; 0 returns every category. */
category?: number;
/** Maximum number of collection items to return (1-500). */
count?: number;
}
export interface GetEmojiLikesParams extends MessageIdParams {
emoji_id: string;
}
+49
View File
@@ -126,6 +126,55 @@ export interface OnlineClientsInfo {
clients: OnlineClientInfo[];
}
export interface CollectionAuthorInfo extends JsonObject {
type: number;
numId: string;
strId: string;
groupId: string;
groupName: string;
uid: string;
}
export interface CollectionSummaryInfo extends JsonObject {
textSummary: JsonValue;
linkSummary: JsonValue;
gallerySummary: JsonValue;
audioSummary: JsonValue;
videoSummary: JsonValue;
fileSummary: JsonValue;
locationSummary: JsonValue;
richMediaSummary: JsonValue;
}
export interface CollectionItemInfo extends JsonObject {
cid: string;
type: number;
status: number;
author: CollectionAuthorInfo;
bid: number;
category: number;
createTime: string;
collectTime: string;
modifyTime: string;
sequence: string;
shareUrl: string;
customGroupId: number;
securityBeat: boolean;
summary: CollectionSummaryInfo;
}
export interface CollectionSearchListInfo extends JsonObject {
collectionItemList: CollectionItemInfo[];
hasMore: boolean;
bottomTimeStamp: string;
}
export interface CollectionListInfo extends JsonObject {
errCode: number;
errMsg: string;
collectionSearchList: CollectionSearchListInfo;
}
export interface UrlSafetyInfo {
level: number;
}