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
This commit is contained in:
1 parent
3e99d3bb5a
commit
884db940df
8 files changed
+653
-7
No files matched your search
@@ -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<T>(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<string, string>,
|
||||
selfUin: string,
|
||||
tid: string,
|
||||
): Promise<RawMsgDetailResponse> {
|
||||
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<RawMsgDetailResponse>(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<string, string>,
|
||||
selfUin: string,
|
||||
tid: string,
|
||||
ugcRight: number,
|
||||
targetUins?: string,
|
||||
): Promise<QzoneUpdateRightResult> {
|
||||
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<RawUpdateResponse>(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) };
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user