From 3517257aa6e198fb80d12de834c3bd4a0fa87d2a Mon Sep 17 00:00:00 2001 From: H3CoF6 <1707889225@qq.com> Date: Sat, 25 Jul 2026 19:53:24 +0800 Subject: [PATCH] feat(onebot): expose friend dress queries (#277) Add a read-only action for querying QQ profile decorations from the authenticated web page. Validate and classify page responses, expose structured errors, and cover parsing with a sanitized fixture. --- packages/core/src/bridge/apis/web.ts | 12 + packages/mcp/src/generated/catalog.json | 39 ++- packages/mcp/src/generated/catalog.ts | 39 ++- packages/onebot/src/actions/extended.ts | 20 ++ packages/onebot/tests/action-registry.test.ts | 6 +- packages/protocol/src/web/friend-dress.ts | 241 +++++++++++++ .../web/fixtures/friend-dress-sample.html | 320 ++++++++++++++++++ .../protocol/tests/web/friend-dress.test.ts | 193 +++++++++++ 8 files changed, 865 insertions(+), 5 deletions(-) create mode 100644 packages/protocol/src/web/friend-dress.ts create mode 100644 packages/protocol/tests/web/fixtures/friend-dress-sample.html create mode 100644 packages/protocol/tests/web/friend-dress.test.ts diff --git a/packages/core/src/bridge/apis/web.ts b/packages/core/src/bridge/apis/web.ts index c6f28126..5d80e729 100644 --- a/packages/core/src/bridge/apis/web.ts +++ b/packages/core/src/bridge/apis/web.ts @@ -2,6 +2,7 @@ import { loadBinarySource } from '@snowluma/protocol/highway/utils'; import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key'; import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey'; import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence'; +import { getFriendDressWebAPI, type WebFriendDress } from '@snowluma/protocol/web/friend-dress'; import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor'; import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin'; import { @@ -417,4 +418,15 @@ export class WebApi { const cookieObject = await getCookies(bridge, 'qun.qq.com'); return await deleteGroupNoticeHttp(cookieObject, groupCode, fid); } + + // ─────────────── friend dress (好友装扮) ─────────────── + + /** 查某人正在用的好友装扮(挂件/名片/来电/输入状态等)。走 vip.qq.com 域, + * 纯 cookie 鉴权、抓 SSR HTML。「查到但没装扮」返回空 items;网络/未登录态/ + * 风控/页面改版/串号数据抛 FriendDressError(kind 区分具体环节)。 */ + async getFriendDress(targetUin: number): Promise { + const bridge = asBridge(this.ctx); + const cookieObject = await getCookies(bridge, 'vip.qq.com'); + return getFriendDressWebAPI(cookieObject, targetUin.toString()); + } } diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index 1b992676..dda43606 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -58,6 +58,43 @@ }, "category": "扩展" }, + { + "name": "_get_friend_dress", + "aliases": [], + "summary": "获取指定 QQ 号正在使用的个性装扮(挂件/名片/来电/输入状态等)", + "returns": "装扮信息;目标未使用任何可查询装扮时 items 为空数组。网络失败、未登录态/风控、页面改版、返回账号与请求不一致时返回失败并附具体原因", + "readOnly": true, + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "role": "user_id", + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "目标 QQ 号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1, + "description": "目标 QQ 号", + "x-role": "user_id" + } + }, + "required": [ + "user_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, { "name": "_get_group_notice", "aliases": [], @@ -10916,7 +10953,7 @@ }, { "category": "扩展", - "count": 109 + "count": 110 }, { "category": "群相册", diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index e88d4b5e..06da3913 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -61,6 +61,43 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "_get_friend_dress", + "aliases": [], + "summary": "获取指定 QQ 号正在使用的个性装扮(挂件/名片/来电/输入状态等)", + "returns": "装扮信息;目标未使用任何可查询装扮时 items 为空数组。网络失败、未登录态/风控、页面改版、返回账号与请求不一致时返回失败并附具体原因", + "readOnly": true, + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "role": "user_id", + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "目标 QQ 号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1, + "description": "目标 QQ 号", + "x-role": "user_id" + } + }, + "required": [ + "user_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, { "name": "_get_group_notice", "aliases": [], @@ -10920,7 +10957,7 @@ export const CATEGORIES: CatalogCategory[] = [ }, { "category": "扩展", - "count": 109 + "count": 110 }, { "category": "群相册", diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 540b0b78..a4b19c77 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1,4 +1,5 @@ import { readFile } from 'node:fs/promises'; +import { FriendDressError } from '@snowluma/protocol/web/friend-dress'; import type { ApiActionContext } from '../api-handler'; import { asNumber, asString } from '../api-handler'; import type { ForwardPreviewMeta } from '../modules/message-actions'; @@ -2438,6 +2439,25 @@ export const actions = [ return okResponse({ fileset_id: filesetId }); }, }), + + // 好友个性装扮 + defineAction({ + name: '_get_friend_dress', + summary: '获取指定 QQ 号正在使用的个性装扮(挂件/名片/来电/输入状态等)', + returns: '装扮信息;目标未使用任何可查询装扮时 items 为空数组。网络失败、未登录态/风控、页面改版、返回账号与请求不一致时返回失败并附具体原因', + readOnly: true, + params: { user_id: f.userId().describe('目标 QQ 号') }, + run: async (p, ctx) => { + try { + return okResponse(await ctx.bridge.apis.web.getFriendDress(p.user_id)); + } catch (e) { + if (e instanceof FriendDressError) { + return failedResponse(RETCODE.ACTION_FAILED, `failed to get friend dress (${e.kind}): ${e.message}`); + } + return failedResponse(RETCODE.ACTION_FAILED, `failed to get friend dress: ${(e as Error).message}`); + } + }, + }), ]; // 已过滤(机器人/被忽略)的入群请求。 diff --git a/packages/onebot/tests/action-registry.test.ts b/packages/onebot/tests/action-registry.test.ts index e841349d..86e0d0ce 100644 --- a/packages/onebot/tests/action-registry.test.ts +++ b/packages/onebot/tests/action-registry.test.ts @@ -90,9 +90,9 @@ describe('compileActionRegistry namespace conflicts', () => { }); describe('compiled production Action registry', () => { - it('preserves all 179 canonical Action docs', () => { - expect(ACTION_REGISTRY.actions).toHaveLength(179); - expect(collectActionDocs()).toHaveLength(179); + it('preserves all 180 canonical Action docs', () => { + expect(ACTION_REGISTRY.actions).toHaveLength(180); + expect(collectActionDocs()).toHaveLength(180); }); it('resolves every executable name to exactly one canonical doc', () => { diff --git a/packages/protocol/src/web/friend-dress.ts b/packages/protocol/src/web/friend-dress.ts new file mode 100644 index 00000000..8a1ba25e --- /dev/null +++ b/packages/protocol/src/web/friend-dress.ts @@ -0,0 +1,241 @@ +import { RequestUtil, cookieToString } from './request-util'; + +export interface WebFriendDressItem { + [key: string]: import('@snowluma/common/json').JsonValue; + /** 装扮业务 id(QQ 会员 appId,决定类别)。 */ + app_id: number; + /** 人类可读类别(按 appId 映射,未知则为 appId=)。 */ + kind: string; + /** 装扮 id(默认款为 0)。 */ + item_id: number; + name: string; + /** 静态预览图 url。 */ + preview_url: string; + /** 动态预览视频 url(名片/来电才有,否则空串)。 */ + video_url: string; + /** 商城价(非默认款才有,否则 0)。 */ + price: number; +} + +export interface WebFriendDress { + [key: string]: import('@snowluma/common/json').JsonValue; + target_uin: string; + is_svip: boolean; + /** 对方头像图 url(装扮页附带,非"头像装扮")。 */ + avatar_url: string; + /** 对方正在用的装扮(已剔除服务器不回真值的气泡/字体/头像)。 */ + items: WebFriendDressItem[]; +} + +/** 装扮查询失败的具体环节 —— 调用方据此给出可区分的错误提示。 */ +export type FriendDressErrorKind = + /** HTTP 请求本身失败(网络/非 2xx)。 */ + | 'network' + /** HTML 里抠不到 __INITIAL_ASYNCDATA__(未登录态/风控/页面改版)。 */ + | 'parse' + /** 抠到了 JSON 但结构不符合预期(页面改版)。 */ + | 'structure' + /** 页面返回的 targetUin 与请求的不一致(串号数据,不可信)。 */ + | 'uin_mismatch'; + +export class FriendDressError extends Error { + constructor( + readonly kind: FriendDressErrorKind, + message: string, + options?: ErrorOptions, + ) { + super(message, options); + this.name = 'FriendDressError'; + } +} + +/** appId → 装扮类别(取自装扮页 business-name / tab 文案)。 */ +const APP_KIND: Record = { + 2: '气泡', + 4: '挂件', + 5: '字体', + 15: '名片', + 17: '来电', + 22: '彩色屏保', + 23: '头像', + 47: '头像双击动作', + 352: '输入状态', +}; + +/** + * 服务器不会回真值的装扮类型:气泡(2)/字体(5)/头像(23)。这几类只按 targetUin 查 + * 永远回默认款,必须客户端在请求里带对应 id 才知道对方用了啥 —— 拿到也是废数据,剔除。 + */ +const UNRESOLVABLE_APPS = new Set([2, 5, 23]); + +/** + * HAR 里的 traceDetail:base64({"appid":"toaio","page_id":"37","item_id":"","item_type":""})。 + * 与 targetUin 无关,固定值;已是编码后的串,拼接时不可再被二次编码。 + */ +const TRACE_DETAIL = + 'base64-eyJhcHBpZCI6InRvYWlvIiwicGFnZV9pZCI6IjM3IiwiaXRlbV9pZCI6IiIsIml0ZW1fdHlwZSI6%0AIiJ9%0A'; + +/** aio webview 的移动端 UA(照 HAR;桌面 UA 可能返回不同壳)。 */ +const DRESS_UA = + 'Mozilla/5.0 (Linux; Android 13; 2109119BC Build/TKQ1.221114.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/121.0.6167.71 MQQBrowser/6.2 TBS/047925 Mobile Safari/537.36 V1_AND_SQ_9.2.66_13188_YYB_D QQ/9.2.66.33870 NetType/WIFI WebP/0.3.0 AppId/537339358'; + +interface RawDressItem { + appId?: number; + itemId?: number; + name?: string; + image?: string; + extrainfo?: { price?: number }; + extraappinfo?: { extraInfo?: { immersiveMaterial?: string } }; +} + +interface RawAsyncData { + targetUin?: string; + isSvip?: boolean; + avatarImage?: string; + rawUsingList?: RawDressItem[]; +} + +/** 按 targetUin 拼装扮页 URL(结构照 HAR)。 */ +function buildDressUrl(targetUin: string): string { + const inner = + `https://zb.vip.qq.com/v2/pages/aioDressPage?fromPage=1&targetUin=${targetUin}` + + `&widgetId=0&fontEffectId=0&bgId=custom&chatId=${targetUin}` + + `&isGroup=0&traceDetail=${TRACE_DETAIL}`; + const params = new URLSearchParams({ + fromPage: '1', + enteranceId: 'aio', + url: inner, + fontEffectId: '0', + chatId: targetUin, + widgetId: '0', + targetUin, + isGroup: '0', + bgId: 'custom', + }); + // traceDetail 已是编码后的 base64-... 串,单独拼避免被二次编码。 + return `https://zb.vip.qq.com/v2/pages/aioDressPage?${params.toString()}&traceDetail=${TRACE_DETAIL}`; +} + +/** 从 SSR HTML 抠出 window.__INITIAL_ASYNCDATA__ 的 JSON(抠不到/坏 JSON 抛 parse)。 */ +function parseAsyncData(html: string): unknown { + const m = html.match(/window\.__INITIAL_ASYNCDATA__\s*=\s*(\{[\s\S]*?\});\(function/); + if (!m?.[1]) { + throw new FriendDressError('parse', '装扮页中未找到 __INITIAL_ASYNCDATA__(未登录态/风控/页面改版)'); + } + try { + return JSON.parse(m[1]) as unknown; + } catch (e) { + throw new FriendDressError('parse', '__INITIAL_ASYNCDATA__ 不是合法 JSON', { cause: e }); + } +} + +/** 运行时结构校验:不符合预期的一律抛 structure,绝不带着畸形数据继续。 */ +function validateAsyncData(data: unknown): RawAsyncData & { rawUsingList: RawDressItem[] } { + if (data === null || typeof data !== 'object' || Array.isArray(data)) { + throw new FriendDressError('structure', '__INITIAL_ASYNCDATA__ 顶层不是对象'); + } + const d = data as Record; + if (d['targetUin'] !== undefined && typeof d['targetUin'] !== 'string') { + throw new FriendDressError('structure', 'targetUin 不是字符串'); + } + if (d['isSvip'] !== undefined && typeof d['isSvip'] !== 'boolean') { + throw new FriendDressError('structure', 'isSvip 不是布尔值'); + } + if (d['avatarImage'] !== undefined && typeof d['avatarImage'] !== 'string') { + throw new FriendDressError('structure', 'avatarImage 不是字符串'); + } + if (!Array.isArray(d['rawUsingList'])) { + throw new FriendDressError('structure', 'rawUsingList 缺失或不是数组'); + } + d['rawUsingList'].forEach((item: unknown, i: number) => { + if (item === null || typeof item !== 'object' || Array.isArray(item)) { + throw new FriendDressError('structure', `rawUsingList[${i}] 不是对象`); + } + const r = item as Record; + if (r['appId'] !== undefined && typeof r['appId'] !== 'number') { + throw new FriendDressError('structure', `rawUsingList[${i}].appId 不是数字`); + } + if (r['itemId'] !== undefined && typeof r['itemId'] !== 'number') { + throw new FriendDressError('structure', `rawUsingList[${i}].itemId 不是数字`); + } + if (r['name'] !== undefined && typeof r['name'] !== 'string') { + throw new FriendDressError('structure', `rawUsingList[${i}].name 不是字符串`); + } + if (r['image'] !== undefined && typeof r['image'] !== 'string') { + throw new FriendDressError('structure', `rawUsingList[${i}].image 不是字符串`); + } + }); + return data as RawAsyncData & { rawUsingList: RawDressItem[] }; +} + +/** + * 抠出该装扮项的动态预览视频 url(没有则空串)。 + * - 名片(appId 15):video 藏在 extraInfo.immersiveMaterial(JSON 字符串)的 videoUrl。 + * - 来电(appId 17):无独立字段,按预览图同目录换名 (web_)image.jpg → media.mp4 + * (funCall/item/{itemId}/media.mp4,已验证可访问);文件名不匹配时不猜测,返回空串。 + */ +function resolveVideoUrl(r: RawDressItem): string { + if (r.appId === 15) { + const raw = r.extraappinfo?.extraInfo?.immersiveMaterial; + if (typeof raw !== 'string' || !raw) return ''; + try { + const videoUrl = (JSON.parse(raw) as { videoUrl?: unknown }).videoUrl; + return typeof videoUrl === 'string' ? videoUrl : ''; + } catch { + return ''; + } + } + if (r.appId === 17 && r.image && /\/(?:web_)?image\.jpg$/.test(r.image)) { + return r.image.replace(/\/(?:web_)?image\.jpg$/, '/media.mp4'); + } + return ''; +} + +function toItem(r: RawDressItem): WebFriendDressItem { + const appId = r.appId ?? 0; + return { + app_id: appId, + kind: APP_KIND[appId] ?? `appId=${appId}`, + item_id: r.itemId ?? 0, + name: r.name ?? '', + preview_url: r.image ?? '', + video_url: resolveVideoUrl(r), + price: typeof r.extrainfo?.price === 'number' ? r.extrainfo.price : 0, + }; +} + +/** + * 查 targetUin 正在用的好友装扮(挂件/名片/来电/输入状态等)。「查到但没装扮」 + * 正常返回空 items;请求/解析/校验的任何一环失败都抛 {@link FriendDressError}, + * 带 kind 区分网络、未登录态/风控、页面改版、串号数据。 + */ +export async function getFriendDressWebAPI( + cookieObject: Record, + targetUin: string, +): Promise { + let html: string; + try { + html = await RequestUtil.HttpGetText(buildDressUrl(targetUin), 'GET', '', { + Cookie: cookieToString(cookieObject), + 'User-Agent': DRESS_UA, + Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + 'Accept-Language': 'zh-CN,zh;q=0.9', + }); + } catch (e) { + throw new FriendDressError('network', `装扮页请求失败: ${e instanceof Error ? e.message : String(e)}`, { cause: e }); + } + + const data = validateAsyncData(parseAsyncData(html)); + if (data.targetUin !== undefined && data.targetUin !== targetUin) { + throw new FriendDressError('uin_mismatch', `装扮页返回账号 ${data.targetUin} 与请求账号 ${targetUin} 不一致`); + } + + return { + target_uin: data.targetUin ?? targetUin, + is_svip: data.isSvip ?? false, + avatar_url: data.avatarImage ?? '', + items: data.rawUsingList + .filter((r) => !UNRESOLVABLE_APPS.has(r.appId ?? 0)) + .map(toItem), + }; +} diff --git a/packages/protocol/tests/web/fixtures/friend-dress-sample.html b/packages/protocol/tests/web/fixtures/friend-dress-sample.html new file mode 100644 index 00000000..a649b168 --- /dev/null +++ b/packages/protocol/tests/web/fixtures/friend-dress-sample.html @@ -0,0 +1,320 @@ + + + + + + + + + + + +好友装扮 + + + + + + + + + + + +
好友正在用
他是尊贵的SVIP,免费用7000多款装扮
+ 气泡 +
在说什么呢
+ 用同款 +
+ 名片 +
二次元少女
+ 用同款 +
+ 浮屏 +
花瓣
+ 用同款 +
+ 来电 +
岁月成碑
+ 用同款 +
+ 挂件 +
默认挂件
+ 去商城 +
+ 头像 +
自定义头像
+ 去商城 +
更多
热门推荐
+ 去商城 +
+ 气泡 +
+ 字体 +
+ 挂件 +
+ 名片 +
+ 主题 +
+ 背景 +
+ 头像 +
+ 来电 +
+ 数据加载中 +
+ + + + + + + + + diff --git a/packages/protocol/tests/web/friend-dress.test.ts b/packages/protocol/tests/web/friend-dress.test.ts new file mode 100644 index 00000000..aa62d1d1 --- /dev/null +++ b/packages/protocol/tests/web/friend-dress.test.ts @@ -0,0 +1,193 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { + FriendDressError, + getFriendDressWebAPI, +} from '@snowluma/protocol/web/friend-dress'; +import { RequestUtil } from '@snowluma/protocol/web/request-util'; + +// 真实装扮页 SSR HTML(脱敏:uin 改为 10000、头像 hash 已打码)。 +// __INITIAL_ASYNCDATA__ 里 7 项装扮:气泡(2)/名片(15)/彩色屏保(22)/来电(17)/ +// 挂件(4)/头像(23)/头像双击动作(47) —— 其中 2/23 属服务器不回真值的废数据。 +const SAMPLE_HTML = readFileSync( + fileURLToPath(new URL('./fixtures/friend-dress-sample.html', import.meta.url)), + 'utf8', +); + +const cookies = { uin: 'o10001', skey: 'SKEY', p_uin: 'o10001', p_skey: 'PSKEY' }; + +/** 把任意 asyncData 对象包成最小可解析的 SSR HTML。 */ +const wrapHtml = (data: unknown): string => + ``; + +const mockHtml = (html: string) => + vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(html as never); + +describe('friend-dress / real sample parsing', () => { + afterEach(() => vi.restoreAllMocks()); + + it('sends cookie + mobile UA to zb.vip.qq.com with the target uin', async () => { + const request = mockHtml(SAMPLE_HTML); + await getFriendDressWebAPI(cookies, '10000'); + + const [url, method, , headers] = request.mock.calls[0]!; + expect(url).toContain('https://zb.vip.qq.com/v2/pages/aioDressPage?'); + expect(url).toContain('targetUin=10000'); + // traceDetail 是预编码的 base64 串,必须原样出现(不能被二次编码成 base64%2D…)。 + expect(url).toContain('&traceDetail=base64-'); + expect(method).toBe('GET'); + expect(headers).toMatchObject({ + Cookie: 'uin=o10001; skey=SKEY; p_uin=o10001; p_skey=PSKEY', + }); + expect((headers as Record)['User-Agent']).toContain('QQ/'); + }); + + it('parses the real page: svip, avatar, and only resolvable dress items', async () => { + mockHtml(SAMPLE_HTML); + const dress = await getFriendDressWebAPI(cookies, '10000'); + + expect(dress.target_uin).toBe('10000'); + expect(dress.is_svip).toBe(true); + expect(dress.avatar_url).toBe('https://q.qlogo.cn/g?b=qq&nk=10000&s=100'); + + // 气泡(2)/头像(23) 是服务器永远回默认款的废数据,必须被剔除。 + const appIds = dress.items.map((i) => i.app_id); + expect(appIds).not.toContain(2); + expect(appIds).not.toContain(23); + expect(appIds).toEqual([15, 22, 17, 4, 47]); + }); + + it('maps item fields: kind, itemId default 0, price default 0', async () => { + mockHtml(SAMPLE_HTML); + const dress = await getFriendDressWebAPI(cookies, '10000'); + + const card = dress.items.find((i) => i.app_id === 15)!; + expect(card.kind).toBe('名片'); + expect(card.item_id).toBe(201534); + expect(card.name).toBe('二次元少女'); + expect(card.preview_url).toBe('https://tianquan.gtimg.cn/card/original/201534/templateThumb.jpg'); + expect(card.price).toBe(0); + + // 默认挂件没有 itemId 字段 → 0。 + const widget = dress.items.find((i) => i.app_id === 4)!; + expect(widget.item_id).toBe(0); + expect(widget.kind).toBe('挂件'); + }); + + it('derives the funcall video url from the real web_image.jpg preview', async () => { + mockHtml(SAMPLE_HTML); + const dress = await getFriendDressWebAPI(cookies, '10000'); + + const funcall = dress.items.find((i) => i.app_id === 17)!; + expect(funcall.preview_url).toBe('https://tianquan.gtimg.cn/funcall/funCall/2730/web_image.jpg'); + expect(funcall.video_url).toBe('https://tianquan.gtimg.cn/funcall/funCall/2730/media.mp4'); + }); +}); + +describe('friend-dress / synthetic payloads', () => { + afterEach(() => vi.restoreAllMocks()); + + const base = { targetUin: '10000', isSvip: false, avatarImage: '', rawUsingList: [] as unknown[] }; + + it('an empty rawUsingList is a valid result, not an error', async () => { + mockHtml(wrapHtml(base)); + const dress = await getFriendDressWebAPI(cookies, '10000'); + expect(dress.items).toEqual([]); + expect(dress.is_svip).toBe(false); + }); + + it('does NOT return the image url as video when a funcall preview has an unexpected name', async () => { + mockHtml(wrapHtml({ + ...base, + rawUsingList: [{ appId: 17, itemId: 1, name: 'x', image: 'https://cdn.example/funCall/1/preview.png' }], + })); + const dress = await getFriendDressWebAPI(cookies, '10000'); + expect(dress.items[0]!.video_url).toBe(''); + expect(dress.items[0]!.preview_url).toBe('https://cdn.example/funCall/1/preview.png'); + }); + + it('extracts the card video from immersiveMaterial and survives broken JSON there', async () => { + mockHtml(wrapHtml({ + ...base, + rawUsingList: [ + { + appId: 15, itemId: 1, name: 'a', image: 'https://cdn.example/a.jpg', + extraappinfo: { extraInfo: { immersiveMaterial: '{"videoUrl":"https://cdn.example/a.mp4"}' } }, + }, + { + appId: 15, itemId: 2, name: 'b', image: 'https://cdn.example/b.jpg', + extraappinfo: { extraInfo: { immersiveMaterial: '{not json' } }, + }, + ], + })); + const dress = await getFriendDressWebAPI(cookies, '10000'); + expect(dress.items[0]!.video_url).toBe('https://cdn.example/a.mp4'); + expect(dress.items[1]!.video_url).toBe(''); + }); + + it('labels unknown appIds without dropping them', async () => { + mockHtml(wrapHtml({ + ...base, + rawUsingList: [{ appId: 999, itemId: 7, name: 'n', image: '' }], + })); + const dress = await getFriendDressWebAPI(cookies, '10000'); + expect(dress.items[0]!.kind).toBe('appId=999'); + }); +}); + +describe('friend-dress / error classification', () => { + afterEach(() => vi.restoreAllMocks()); + + const expectKind = async (uin: string, kind: string) => { + const e = await getFriendDressWebAPI(cookies, uin).catch((err: unknown) => err); + expect(e).toBeInstanceOf(FriendDressError); + expect((e as FriendDressError).kind).toBe(kind); + return e as FriendDressError; + }; + + it('network: transport failure is not folded into a parse error', async () => { + vi.spyOn(RequestUtil, 'HttpGetText').mockRejectedValue(new Error('Unexpected status code: 403')); + const e = await expectKind('10000', 'network'); + expect(e.message).toContain('403'); + }); + + it('parse: html without __INITIAL_ASYNCDATA__ (login-wall / risk-control shell)', async () => { + mockHtml('请先登录'); + await expectKind('10000', 'parse'); + }); + + it('parse: __INITIAL_ASYNCDATA__ present but not valid JSON', async () => { + mockHtml(''); + await expectKind('10000', 'parse'); + }); + + it('parse: a top-level array never matches the SSR object shape', async () => { + mockHtml(wrapHtml([1, 2])); + await expectKind('10000', 'parse'); + }); + + it.each([ + ['rawUsingList missing', { targetUin: '10000' }], + ['rawUsingList not an array', { targetUin: '10000', rawUsingList: 'nope' }], + ['item not an object', { targetUin: '10000', rawUsingList: ['nope'] }], + ['item appId not a number', { targetUin: '10000', rawUsingList: [{ appId: 'four' }] }], + ['targetUin not a string', { targetUin: 10000, rawUsingList: [] }], + ])('structure: %s', async (_label, payload) => { + mockHtml(wrapHtml(payload)); + await expectKind('10000', 'structure'); + }); + + it('uin_mismatch: page answers for a different account than requested', async () => { + mockHtml(wrapHtml({ targetUin: '20000', rawUsingList: [] })); + const e = await expectKind('10000', 'uin_mismatch'); + expect(e.message).toContain('20000'); + expect(e.message).toContain('10000'); + }); + + it('tolerates a missing targetUin by echoing the requested uin', async () => { + mockHtml(wrapHtml({ rawUsingList: [] })); + const dress = await getFriendDressWebAPI(cookies, '10000'); + expect(dress.target_uin).toBe('10000'); + }); +});