From 884db940df71fc09103e119f36376dd20ded9cc1 Mon Sep 17 00:00:00 2001 From: Airline233 Date: Thu, 2 Jul 2026 22:38:05 +0800 Subject: [PATCH] feat(qzone): add set_qzone_msg_right to change a feed's visibility (#186) * feat(qzone): add set_qzone_msg_right to change a feed's visibility Add updateQzoneMsgRight in the protocol layer, porting php-qzone's updateRight: fetch the feed via emotion_cgi_msgdetail_v6, rebuild the full publish-shaped payload (richval/pic_bo/con), then override ugc_right/allow_uins and POST to emotion_cgi_update. Expose it through QzoneApi.updateRight and the OneBot set_qzone_msg_right action, with the same ugc_right/target_uins validation as send_qzone_msg. Covered by protocol, core and onebot tests. * fix(qzone): make qzoneParse more stable and fixed a test example --- packages/core/src/bridge/apis/qzone.ts | 11 + packages/core/tests/actions/qzone.test.ts | 10 + packages/mcp/src/generated/catalog.json | 89 +++++- packages/mcp/src/generated/catalog.ts | 89 +++++- packages/onebot/src/actions/qzone.ts | 28 ++ packages/onebot/tests/qzone-actions.test.ts | 27 ++ packages/protocol/src/web/qzone.ts | 263 +++++++++++++++++- .../tests/web/qzone-update-right.test.ts | 143 ++++++++++ 8 files changed, 653 insertions(+), 7 deletions(-) create mode 100644 packages/protocol/tests/web/qzone-update-right.test.ts diff --git a/packages/core/src/bridge/apis/qzone.ts b/packages/core/src/bridge/apis/qzone.ts index 99785167..924dac2a 100644 --- a/packages/core/src/bridge/apis/qzone.ts +++ b/packages/core/src/bridge/apis/qzone.ts @@ -5,11 +5,13 @@ import { getQzoneMsgList, publishQzoneMsg, setQzoneLike, + updateQzoneMsgRight, uploadQzoneImageFromSource, type QzoneCommentResult, type QzoneFeedsResult, type QzoneMsgListResult, type QzonePublishResult, + type QzoneUpdateRightResult, type QzoneUploadImageResult, } from '@snowluma/protocol/web/qzone'; import type { BridgeContext } from '../bridge-context'; @@ -74,6 +76,15 @@ export class QzoneApi { await deleteQzoneMsg(cookieObject, this.ctx.identity.uin, tid); } + /** + * 修改机器人自己空间一条已发说说的查看权限(按 tid)。 + * `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。 + */ + async updateRight(tid: string, ugcRight: number, targetUins?: string): Promise { + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins); + } + /** * 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说; * 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。 diff --git a/packages/core/tests/actions/qzone.test.ts b/packages/core/tests/actions/qzone.test.ts index 219a1412..d76558ce 100644 --- a/packages/core/tests/actions/qzone.test.ts +++ b/packages/core/tests/actions/qzone.test.ts @@ -117,6 +117,16 @@ describe('apis/qzone', () => { expect(delSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'TID9'); }); + it('updateRight changes a feed\'s visibility on the bot\'s own space', async () => { + const getCookies = vi.fn(async () => ({ p_skey: 'PSK' })); + const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never }); + const updSpy = vi.spyOn(qzoneWeb, 'updateQzoneMsgRight').mockResolvedValue({ ugc_right: 16 }); + const out = await new QzoneApi(bridge as never).updateRight('TID9', 16, '10002|10003'); + expect(getCookies).toHaveBeenCalledWith('qzone.qq.com'); + expect(updSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'TID9', 16, '10002|10003'); + expect(out).toEqual({ ugc_right: 16 }); + }); + it('like defaults the feed owner to self and passes opUin=self + like flag', async () => { const getCookies = vi.fn(async () => ({ p_skey: 'PSK' })); const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never }); diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index 931ebc36..683ddff0 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -8903,6 +8903,93 @@ }, "category": "扩展" }, + { + "name": "set_qzone_msg_right", + "aliases": [], + "summary": "修改一条已发说说的查看权限(QQ 空间,按 tid)", + "returns": "更新后的权限对象。", + "returnsSchema": { + "type": "object", + "properties": { + "ugc_right": { + "type": "integer", + "description": "更新后的查看权限" + } + }, + "required": [ + "ugc_right" + ] + }, + "readOnly": false, + "params": [ + { + "name": "tid", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + }, + "desc": "说说 tid(来自 get_qzone_msg_list / send_qzone_msg)" + }, + { + "name": "ugc_right", + "type": "int", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见" + }, + { + "name": "target_uins", + "type": "uint[]", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + } + }, + "desc": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单" + } + ], + "invariants": [ + "ugc_right must be one of 1, 4, 16, 64, 128", + "target_uins is required when ugc_right is 16 or 128" + ], + "inputSchema": { + "type": "object", + "properties": { + "tid": { + "type": "string", + "minLength": 1, + "description": "说说 tid(来自 get_qzone_msg_list / send_qzone_msg)" + }, + "ugc_right": { + "type": "integer", + "minimum": 1, + "description": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见" + }, + "target_uins": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + }, + "description": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单" + } + }, + "required": [ + "tid", + "ugc_right" + ], + "additionalProperties": true + }, + "category": "空间" + }, { "name": "set_restart", "aliases": [], @@ -9834,7 +9921,7 @@ }, { "category": "空间", - "count": 7 + "count": 8 }, { "category": "流式接口", diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 66b59332..42422e11 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -8906,6 +8906,93 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "set_qzone_msg_right", + "aliases": [], + "summary": "修改一条已发说说的查看权限(QQ 空间,按 tid)", + "returns": "更新后的权限对象。", + "returnsSchema": { + "type": "object", + "properties": { + "ugc_right": { + "type": "integer", + "description": "更新后的查看权限" + } + }, + "required": [ + "ugc_right" + ] + }, + "readOnly": false, + "params": [ + { + "name": "tid", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + }, + "desc": "说说 tid(来自 get_qzone_msg_list / send_qzone_msg)" + }, + { + "name": "ugc_right", + "type": "int", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见" + }, + { + "name": "target_uins", + "type": "uint[]", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + } + }, + "desc": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单" + } + ], + "invariants": [ + "ugc_right must be one of 1, 4, 16, 64, 128", + "target_uins is required when ugc_right is 16 or 128" + ], + "inputSchema": { + "type": "object", + "properties": { + "tid": { + "type": "string", + "minLength": 1, + "description": "说说 tid(来自 get_qzone_msg_list / send_qzone_msg)" + }, + "ugc_right": { + "type": "integer", + "minimum": 1, + "description": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见" + }, + "target_uins": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + }, + "description": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单" + } + }, + "required": [ + "tid", + "ugc_right" + ], + "additionalProperties": true + }, + "category": "空间" + }, { "name": "set_restart", "aliases": [], @@ -9838,7 +9925,7 @@ export const CATEGORIES: CatalogCategory[] = [ }, { "category": "空间", - "count": 7 + "count": 8 }, { "category": "流式接口", diff --git a/packages/onebot/src/actions/qzone.ts b/packages/onebot/src/actions/qzone.ts index d3924b2b..16db40f8 100644 --- a/packages/onebot/src/actions/qzone.ts +++ b/packages/onebot/src/actions/qzone.ts @@ -147,6 +147,34 @@ export const actions = [ }, }), + // set_qzone_msg_right — 修改机器人自己空间一条已发说说的查看权限(按 tid)。 + // 写操作;ugc_right/target_uins 语义与 send_qzone_msg 一致。 + defineAction({ + name: 'set_qzone_msg_right', + returns: '更新后的权限对象。', + returnsSchema: { + type: 'object', + properties: { + ugc_right: { type: 'integer', description: '更新后的查看权限' }, + }, + required: ['ugc_right'], + }, + summary: '修改一条已发说说的查看权限(QQ 空间,按 tid)', + params: { + tid: f.string({ allowEmpty: false }).describe('说说 tid(来自 get_qzone_msg_list / send_qzone_msg)'), + ugc_right: f.int({ min: 1 }).describe('查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见'), + target_uins: f.array(f.uint()).describe('权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单').optional(), + }, + rules: (r) => [ + r.rule('ugc_right must be one of 1, 4, 16, 64, 128', (p) => QZONE_UGC_RIGHTS.has(p.ugc_right)), + r.rule('target_uins is required when ugc_right is 16 or 128', (p) => (p.ugc_right !== 16 && p.ugc_right !== 128) || !!p.target_uins?.length), + ], + run: async (p, ctx) => { + const res = await ctx.bridge.apis.qzone.updateRight(p.tid, p.ugc_right, p.target_uins?.join('|')); + return okResponse(res as unknown as JsonValue); + }, + }), + // like_qzone — 给一条说说点赞。target_uin 省略=机器人自己空间;点赞好友说说传其 uin。 // abstime=该说说的发表时间(unix 秒,来自 get_qzone_feeds/get_qzone_msg_list), // 传真实值更可靠;不传按 0。写操作;高频点赞会被 Qzone 风控,调用方需限流。 diff --git a/packages/onebot/tests/qzone-actions.test.ts b/packages/onebot/tests/qzone-actions.test.ts index 92c40a6c..486a331c 100644 --- a/packages/onebot/tests/qzone-actions.test.ts +++ b/packages/onebot/tests/qzone-actions.test.ts @@ -62,4 +62,31 @@ describe('qzone actions', () => { expect(publish).not.toHaveBeenCalled(); }); + it('set_qzone_msg_right joins target_uins with | and passes through', async () => { + const updateRight = vi.fn().mockResolvedValue({ ugc_right: 16 }); + const handler = makeHandler({ updateRight }); + + const res = await handler.handle('set_qzone_msg_right', { + tid: 'T1', + ugc_right: 16, + target_uins: [10001, 10002], + }); + + expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { ugc_right: 16 } }); + expect(updateRight).toHaveBeenCalledWith('T1', 16, '10001|10002'); + }); + + it('set_qzone_msg_right rejects invalid ugc_right and 16/128 without target_uins', async () => { + const updateRight = vi.fn(); + const handler = makeHandler({ updateRight }); + + const bad = await handler.handle('set_qzone_msg_right', { tid: 'T1', ugc_right: 2 }); + expect(bad).toMatchObject({ status: 'failed' }); + + const missing = await handler.handle('set_qzone_msg_right', { tid: 'T1', ugc_right: 128 }); + expect(missing).toMatchObject({ status: 'failed' }); + + expect(updateRight).not.toHaveBeenCalled(); + }); + }); diff --git a/packages/protocol/src/web/qzone.ts b/packages/protocol/src/web/qzone.ts index 222f55ce..3b0aee1f 100644 --- a/packages/protocol/src/web/qzone.ts +++ b/packages/protocol/src/web/qzone.ts @@ -64,20 +64,30 @@ export interface QzoneMsgListResult { /** * Parse a Qzone CGI body that may be raw JSON or a JSONP callback wrapper - * (`_Callback({...});` / `callback({...})`). We slice from the first `{` - * to the last `}` and JSON.parse that — robust to either form without + * (`_Callback({...});` / `callback({...})`). We first attempt to slice from + * the first `{` to the last `}`, when failed attempt from the first `back({` + * to the last `})` and JSON.parse that — robust to either form without * pinning the callback name, which Qzone varies. Throws if no object body * is present (e.g. an HTML error page), which the caller turns into a * failed response rather than a silent empty list. */ export function parseQzoneJson(text: string): T { const s = text.trim(); - const start = s.indexOf('{'); - const end = s.lastIndexOf('}'); + try { + const start = s.indexOf('{'); + const end = s.lastIndexOf('}'); + if (start !== -1 && end !== -1 && end > start) { + return JSON.parse(s.slice(start, end + 1)) as T; + } + } catch { + + } + const start = s.indexOf('back({'); + const end = s.lastIndexOf('})'); if (start === -1 || end === -1 || end < start) { throw new Error('invalid response from qzone api'); } - return JSON.parse(s.slice(start, end + 1)) as T; + return JSON.parse(s.slice(start + 5, end + 1)) as T; } /** @@ -1040,3 +1050,246 @@ export async function commentQzoneMsg( const commentId = data.commentid ?? data.commentId; return { comment_id: commentId !== undefined ? String(commentId) : '' }; } + +// ─────── 改说说权限 (update right) — emotion_cgi_msgdetail_v6 + emotion_cgi_update ─────── +// Changes the view permission (ugc_right) of an EXISTING 说说. The update CGI +// is not a partial patch — it re-submits the whole feed (content, richval, +// pic_bo, …), so the flow is two-step: GET the feed detail from +// emotion_cgi_msgdetail_v6 (NOTE: proxied domain is taotao.qq.com, not +// taotao.qzone.qq.com — that's what the working impl hits), rebuild the full +// publish-shaped payload from it, override ugc_right/allow_uins, and POST to +// emotion_cgi_update. Both the detail param set and the payload rebuild are +// CONFIRMED against php-qzone/qzone.class.php updateRight (live-verified +// there); success signal is `subcode == 0`, same envelope as the siblings. +// WRITE OP — rate-limit like publish. + +interface RawMsgDetailPic { + pic_id?: string; + pictype?: number | string; + type?: number | string; + height?: number | string; + b_height?: number | string; + width?: number | string; + b_width?: number | string; + smallurl?: string; + url1?: string; + url2?: string; + url3?: string; +} + +interface RawMsgDetailResponse { + code?: number; + subcode?: number; + message?: string; + msg?: string; + tid?: string; + uin?: number | string; + content?: string; + conlist?: Array<{ con?: string }> | null; + pic?: RawMsgDetailPic[] | null; + richtype?: number | string; + richval?: string; + pic_template?: string; + special_url?: string; + t1_subtype?: number | string; + subrichtype?: number | string; + feedversion?: number | string; + ver?: number | string; + ugc_right?: number | string; + to_sign?: number | string; + ugcright_id?: string; + code_version?: number | string; +} + +interface RawUpdateResponse { + code?: number; + subcode?: number; + message?: string; + msg?: string; + ugc_right?: number | string; +} + +/** Result of changing a 说说's view permission. */ +export interface QzoneUpdateRightResult { + [key: string]: JsonValue; + /** The feed's ugc_right after the update (echoed by the server when present). */ + ugc_right: number; +} + +/** + * Rebuild the full emotion_cgi_update payload from a msgdetail_v6 response. + * Field-for-field port of php-qzone's buildUpdatePayloadFromDetail: richval + * strings are reconstructed from each `pic[].pic_id` (`,albumid,lloc,sloc, + * type,height,width,,0,0`, tab-joined), `pic_bo` from the `bo=` query param + * of any picture URL variant (group tab-doubled), and the content from + * `conlist` when present. Exported for tests; THROWS on a detail body it + * cannot rebuild from (missing tid, or an image post whose pic info is + * unusable) rather than submitting a lossy update. + */ +export function buildQzoneUpdatePayload(detail: RawMsgDetailResponse, selfUin: string): URLSearchParams { + if (!detail.tid) { + throw new Error('qzone msg detail is missing tid'); + } + + const pics = detail.pic ?? []; + const richtype = detail.richtype !== undefined ? Number(detail.richtype) : (pics.length === 0 ? '' : 1); + const richvals: string[] = []; + const picBoItems: string[] = []; + + for (const pic of pics) { + const picId = String(pic.pic_id ?? ''); + if (!picId) continue; + + const parts = picId.split(','); + const albumId = parts[1] ?? ''; + const lloc = parts[2] ?? ''; + if (!albumId || !lloc) { + throw new Error('qzone msg detail has unsupported pic info'); + } + + const sloc = lloc; + const picType = String(pic.pictype ?? pic.type ?? 22); + const height = String(pic.height ?? pic.b_height ?? 0); + const width = String(pic.width ?? pic.b_width ?? 0); + richvals.push(`,${albumId},${lloc},${sloc},${picType},${height},${width},,0,0`); + + for (const urlKey of ['smallurl', 'url1', 'url2', 'url3'] as const) { + const picUrl = pic[urlKey]; + if (!picUrl) continue; + const match = /[?&]bo=([^&#]+)/.exec(picUrl); + if (match) { + picBoItems.push(decodeURIComponent(match[1]!)); + break; + } + } + } + + if (richtype === 1 && richvals.length === 0) { + throw new Error('qzone image post detail is missing pic info'); + } + + let content = detail.content ?? ''; + const conParts = (detail.conlist ?? []) + .map((c) => c.con) + .filter((c): c is string => c !== undefined); + if (conParts.length > 0) { + content = conParts.join('').trim(); + } + + const subrichtype = detail.t1_subtype ?? detail.subrichtype ?? (richvals.length === 0 ? '' : 1); + const boGroup = picBoItems.join(','); + const picBo = boGroup ? `${boGroup}\t${boGroup}` : ''; + + const hostuin = String(detail.uin ?? selfUin); + return new URLSearchParams({ + syn_tweet_verson: '1', + tid: String(detail.tid), + paramstr: '1', + pic_template: detail.pic_template ?? '', + richtype: String(richtype), + richval: richvals.length > 0 ? richvals.join('\t') : (detail.richval ?? ''), + special_url: detail.special_url ?? '', + subrichtype: String(subrichtype), + pic_bo: picBo, + con: content, + feedversion: String(detail.feedversion ?? 1), + ver: String(detail.ver ?? 1), + ugc_right: String(Number(detail.ugc_right ?? 1)), + to_sign: String(Number(detail.to_sign ?? 0)), + ugcright_id: String(detail.ugcright_id ?? detail.tid), + hostuin, + code_version: String(detail.code_version ?? 1), + format: 'fs', + qzreferrer: `https://user.qzone.qq.com/${hostuin}`, + }); +} + +/** Fetch one 说说's full detail (the update payload's source of truth). */ +async function getQzoneMsgDetail( + cookieObject: Record, + selfUin: string, + tid: string, +): Promise { + const bkn = getBknFromCookie(cookieObject); + const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msgdetail_v6?${new URLSearchParams( + { + tid, + uin: selfUin, + t1_source: '1', + not_trunc_con: '1', + need_right: '1', + not_adapt_outpic: '1', + g_tk: bkn, + }, + ).toString()}`; + + const text = await RequestUtil.HttpGetText(url, 'GET', '', { + Cookie: cookieToString(cookieObject), + }); + log.trace('getQzoneMsgDetail raw body (tid=%s): %s', tid, text); + const data = parseQzoneJson(text); + + const code = data.subcode ?? data.code ?? -1; + if (code !== 0) { + log.warn('getQzoneMsgDetail: non-zero code (tid=%s) code=%d msg=%s', tid, code, data.message ?? data.msg); + throw new Error(`qzone msg detail failed: code=${code} ${data.message ?? data.msg ?? ''}`.trim()); + } + return data; +} + +/** + * Change the view permission of an existing 说说 (`tid`, on the bot's own + * space) via the msgdetail_v6 → emotion_cgi_update two-step. `ugcRight` is + * one of 1(所有人)/4(好友)/16(部分可见)/64(仅自己)/128(部分不可见); + * `targetUins` (|-separated QQ numbers) is required for 16/128 and ignored + * otherwise. Errors PROPAGATE from both steps: a transport failure, a + * non-zero Qzone code on the detail fetch (unknown/foreign tid, auth), an + * unrebuildable detail, or a non-zero `subcode` on the update all throw. + */ +export async function updateQzoneMsgRight( + cookieObject: Record, + selfUin: string, + tid: string, + ugcRight: number, + targetUins?: string, +): Promise { + if (!cookieObject || typeof cookieObject !== 'object') { + throw new Error('cookieObject is required'); + } + if (!tid) { + throw new Error('tid is required'); + } + + const right = normalizeQzoneUgcRight(ugcRight); + const effectiveTargetUins = right === 16 || right === 128 ? normalizeTargetUins(targetUins) : ''; + if ((right === 16 || right === 128) && !effectiveTargetUins) { + throw new Error('target_uins is required when ugc_right is 16 or 128'); + } + + const detail = await getQzoneMsgDetail(cookieObject, selfUin, tid); + const bodyParams = buildQzoneUpdatePayload(detail, selfUin); + bodyParams.set('ugc_right', String(right)); + if (effectiveTargetUins) bodyParams.set('allow_uins', effectiveTargetUins); + + const bkn = getBknFromCookie(cookieObject); + const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_update?g_tk=${bkn}`; + const text = await RequestUtil.HttpGetText(url, 'POST', bodyParams.toString(), { + Cookie: cookieToString(cookieObject), + 'Content-Type': 'application/x-www-form-urlencoded', + }); + // format=fs wraps the JSON in a callback (`frameElement.callback({...});` + // or `_Callback({...});`) — parseQzoneJson's first-{-to-last-} slice + // handles every observed variant. + const data = parseQzoneJson(text); + + if (typeof data.subcode === 'number' && data.subcode !== 0) { + log.warn('updateQzoneMsgRight: non-zero subcode (tid=%s) subcode=%d msg=%s', tid, data.subcode, data.message ?? data.msg); + throw new Error(`qzone update right failed: subcode=${data.subcode} ${data.message ?? data.msg ?? ''}`.trim()); + } + if (typeof data.code === 'number' && data.code !== 0) { + log.warn('updateQzoneMsgRight: non-zero code (tid=%s) code=%d msg=%s', tid, data.code, data.message ?? data.msg); + throw new Error(`qzone update right failed: code=${data.code} ${data.message ?? data.msg ?? ''}`.trim()); + } + + return { ugc_right: Number(data.ugc_right ?? right) }; +} diff --git a/packages/protocol/tests/web/qzone-update-right.test.ts b/packages/protocol/tests/web/qzone-update-right.test.ts new file mode 100644 index 00000000..3b826a0d --- /dev/null +++ b/packages/protocol/tests/web/qzone-update-right.test.ts @@ -0,0 +1,143 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { buildQzoneUpdatePayload, updateQzoneMsgRight } from '@snowluma/protocol/web/qzone'; +import { RequestUtil } from '@snowluma/protocol/web/request-util'; + +// updateQzoneMsgRight is the two-step msgdetail_v6 → emotion_cgi_update flow. +// The real logic is the payload REBUILD (detail → publish-shaped form body, +// ported from php-qzone's live-verified updateRight): richval reconstruction +// from pic_id, pic_bo from the `bo=` query param, conlist → con. We pin that +// plus both request shapes and the throw contracts. + +const cookies = { p_skey: 'PSK', skey: 'SK', uin: 'o10000', p_uin: 'o10000' }; + +describe('qzone / buildQzoneUpdatePayload', () => { + it('rebuilds a text-only payload with ugcright_id defaulting to tid', () => { + const body = buildQzoneUpdatePayload( + { tid: 'T1', uin: 10000, content: 'hello', ugc_right: 1 }, + '10000', + ); + expect(body.get('tid')).toBe('T1'); + expect(body.get('con')).toBe('hello'); + expect(body.get('richtype')).toBe(''); + expect(body.get('richval')).toBe(''); + expect(body.get('pic_bo')).toBe(''); + expect(body.get('ugcright_id')).toBe('T1'); + expect(body.get('hostuin')).toBe('10000'); + expect(body.get('format')).toBe('fs'); + }); + + it('rebuilds richval from pic_id and pic_bo from the bo= query param', () => { + const body = buildQzoneUpdatePayload( + { + tid: 'T2', + uin: 10000, + content: 'pics', + conlist: [{ con: 'pi' }, { con: 'cs' }], + richtype: 1, + pic: [ + { + pic_id: 'X,ALBUM1,LLOC1,extra', + pictype: 22, + height: 800, + width: 600, + url1: 'https://photo.example/a.jpg?bo=abc%2Cdef&x=1', + }, + ], + }, + '10000', + ); + expect(body.get('con')).toBe('pics'); + expect(body.get('richtype')).toBe('1'); + expect(body.get('richval')).toBe(',ALBUM1,LLOC1,LLOC1,22,800,600,,0,0'); + expect(body.get('pic_bo')).toBe('abc,def\tabc,def'); + }); + + it('throws when an image post detail carries unusable pic info', () => { + expect(() => + buildQzoneUpdatePayload({ tid: 'T3', richtype: 1, pic: [{ pic_id: 'broken' }] }, '10000'), + ).toThrow('unsupported pic info'); + expect(() => buildQzoneUpdatePayload({ tid: 'T3', richtype: 1, pic: [] }, '10000')).toThrow( + 'missing pic info', + ); + }); + + it('throws when the detail has no tid', () => { + expect(() => buildQzoneUpdatePayload({}, '10000')).toThrow('missing tid'); + }); +}); + +describe('qzone / updateQzoneMsgRight (HTTP layer)', () => { + afterEach(() => vi.restoreAllMocks()); + + const detailBody = + '_Callback({"code":0,"subcode":0,"tid":"T1","uin":10000,"content":"hello","ugc_right":1});'; + + it('GETs the detail then POSTs the rebuilt payload with the new ugc_right', async () => { + const spy = vi + .spyOn(RequestUtil, 'HttpGetText') + .mockResolvedValueOnce(detailBody) + .mockResolvedValueOnce('frameElement.callback({"code":0,"subcode":0,"ugc_right":64});'); + + const out = await updateQzoneMsgRight(cookies, '10000', 'T1', 64); + expect(out).toEqual({ ugc_right: 64 }); + + const [detailUrl, detailMethod] = spy.mock.calls[0]!; + expect(detailMethod).toBe('GET'); + expect(detailUrl).toContain( + 'https://h5.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msgdetail_v6?', + ); + const dq = new URLSearchParams((detailUrl as string).split('?')[1]); + expect(dq.get('tid')).toBe('T1'); + expect(dq.get('uin')).toBe('10000'); + + const [updateUrl, updateMethod, updateBody] = spy.mock.calls[1]!; + expect(updateMethod).toBe('POST'); + expect(updateUrl).toContain( + 'https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_update?', + ); + const uq = new URLSearchParams(updateBody as string); + expect(uq.get('tid')).toBe('T1'); + expect(uq.get('con')).toBe('hello'); + expect(uq.get('ugc_right')).toBe('64'); + expect(uq.get('allow_uins')).toBeNull(); + }); + + it('sets allow_uins (deduped) for ugc_right 16 and requires it', async () => { + const spy = vi + .spyOn(RequestUtil, 'HttpGetText') + .mockResolvedValueOnce(detailBody) + .mockResolvedValueOnce('{"code":0,"subcode":0}'); + + await updateQzoneMsgRight(cookies, '10000', 'T1', 16, '10001|10001|10002'); + const uq = new URLSearchParams(spy.mock.calls[1]![2] as string); + expect(uq.get('ugc_right')).toBe('16'); + expect(uq.get('allow_uins')).toBe('10001|10002'); + + await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 128)).rejects.toThrow( + 'target_uins is required', + ); + }); + + it('rejects an invalid ugc_right before any request', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText'); + await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 2)).rejects.toThrow( + 'ugc_right must be one of', + ); + expect(spy).not.toHaveBeenCalled(); + }); + + it('throws on a non-zero detail code and skips the update POST', async () => { + const spy = vi + .spyOn(RequestUtil, 'HttpGetText') + .mockResolvedValueOnce('{"code":-3000,"subcode":-3000,"message":"need login"}'); + await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 64)).rejects.toThrow('code=-3000'); + expect(spy).toHaveBeenCalledTimes(1); + }); + + it('throws on a non-zero update subcode', async () => { + vi.spyOn(RequestUtil, 'HttpGetText') + .mockResolvedValueOnce(detailBody) + .mockResolvedValueOnce('{"code":0,"subcode":-200,"message":"denied"}'); + await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 64)).rejects.toThrow('subcode=-200'); + }); +});