chore: prepare v2.0.0 release
This commit is contained in:
1 parent
1001f55a06
commit
c15b2d857d
31 files changed
+965
-40
No files matched your search
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/protocol",
|
||||
"version": "1.14.22",
|
||||
"version": "2.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
|
||||
|
||||
@@ -62,6 +62,31 @@ export interface QzoneMsgListResult {
|
||||
msglist: QzoneEmotion[];
|
||||
}
|
||||
|
||||
export interface QzoneCommentReply {
|
||||
[key: string]: JsonValue;
|
||||
uin: number;
|
||||
name: string;
|
||||
/** Unix seconds. */
|
||||
time: number;
|
||||
content: string;
|
||||
/** Scoped to the containing post (or parent comment for replies). */
|
||||
comment_id: string;
|
||||
}
|
||||
|
||||
export interface QzoneComment extends QzoneCommentReply {
|
||||
/** Inline replies supplied by Qzone; may not include every reply. */
|
||||
replies: QzoneCommentReply[];
|
||||
}
|
||||
|
||||
export interface QzoneMsgDetailResult {
|
||||
[key: string]: JsonValue;
|
||||
tid: string;
|
||||
content: string;
|
||||
/** Server-reported total, not the length of this comment page. */
|
||||
comment_num: number;
|
||||
comments: QzoneComment[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a Qzone CGI body that may be raw JSON or a JSONP callback wrapper
|
||||
* (`_Callback({...});` / `callback({...})`). Uses a layered fallback approach:
|
||||
@@ -1553,6 +1578,8 @@ interface RawMsgDetailResponse {
|
||||
tid?: string;
|
||||
uin?: number | string;
|
||||
content?: string;
|
||||
cmtnum?: unknown;
|
||||
commentlist?: unknown;
|
||||
conlist?: Array<{ con?: string }> | null;
|
||||
pic?: RawMsgDetailPic[] | null;
|
||||
richtype?: number | string;
|
||||
@@ -1686,32 +1713,36 @@ export function buildQzoneUpdatePayload(
|
||||
});
|
||||
}
|
||||
|
||||
/** Fetch one 说说's full detail (the update payload's source of truth). */
|
||||
async function getQzoneMsgDetail(
|
||||
/** Shared raw detail for reading comments and rebuilding permission updates. */
|
||||
async function fetchQzoneMsgDetail(
|
||||
cookieObject: Record<string, string>,
|
||||
selfUin: string,
|
||||
targetUin: string,
|
||||
tid: string,
|
||||
page?: { pos: number; num: number },
|
||||
): 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,
|
||||
uin: targetUin,
|
||||
t1_source: '1',
|
||||
not_trunc_con: '1',
|
||||
need_right: '1',
|
||||
not_adapt_outpic: '1',
|
||||
g_tk: bkn,
|
||||
...(page ? { pos: String(page.pos), num: String(page.num) } : {}),
|
||||
},
|
||||
).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);
|
||||
detailObject(data, 'response');
|
||||
|
||||
const code = data.subcode ?? data.code ?? -1;
|
||||
// Either error field can carry the failure; subcode=0 must not mask code!=0.
|
||||
const code =
|
||||
data.code !== undefined && data.code !== 0 ? data.code : (data.subcode ?? data.code ?? -1);
|
||||
|
||||
if (code !== 0) {
|
||||
log.warn(
|
||||
@@ -1728,6 +1759,102 @@ async function getQzoneMsgDetail(
|
||||
return data;
|
||||
}
|
||||
|
||||
function detailObject(value: unknown, field: string): Record<string, unknown> {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error(`invalid qzone msg detail: ${field} must be an object`);
|
||||
}
|
||||
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function detailString(value: unknown, field: string): string {
|
||||
if (typeof value !== 'string') {
|
||||
throw new Error(`invalid qzone msg detail: ${field} must be a string`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function detailInteger(value: unknown, field: string, min = 0): number {
|
||||
const number = typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : value;
|
||||
|
||||
if (typeof number !== 'number' || !Number.isSafeInteger(number) || number < min) {
|
||||
throw new Error(`invalid qzone msg detail: ${field} must be an integer >= ${min}`);
|
||||
}
|
||||
|
||||
return number;
|
||||
}
|
||||
|
||||
function detailList(value: unknown, field: string): unknown[] {
|
||||
if (value === undefined || value === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!Array.isArray(value)) {
|
||||
throw new Error(`invalid qzone msg detail: ${field} must be an array`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function mapQzoneComment(value: Record<string, unknown>, field: string): QzoneCommentReply {
|
||||
const id =
|
||||
typeof value.tid === 'number'
|
||||
? String(detailInteger(value.tid, `${field}.tid`))
|
||||
: detailString(value.tid, `${field}.tid`);
|
||||
|
||||
if (!id) {
|
||||
throw new Error(`invalid qzone msg detail: ${field}.tid is empty`);
|
||||
}
|
||||
|
||||
return {
|
||||
comment_id: id,
|
||||
uin: detailInteger(value.uin, `${field}.uin`, 1),
|
||||
name: detailString(value.name, `${field}.name`),
|
||||
time: detailInteger(value.create_time, `${field}.create_time`),
|
||||
content: detailString(value.content, `${field}.content`),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one post and a page of comments, with the inline replies Qzone supplies.
|
||||
* Wire fields and pos/num follow SmartHypercube/Qzone-API's Comment / Emotion.load:
|
||||
* https://github.com/SmartHypercube/Qzone-API/blob/master/qzone.py
|
||||
* Mapping is independent of the update payload; malformed data must not look
|
||||
* like a successful empty page. No raw response (private content) is logged.
|
||||
*/
|
||||
export async function getQzoneMsgDetail(
|
||||
cookieObject: Record<string, string>,
|
||||
targetUin: string,
|
||||
tid: string,
|
||||
pos = 0,
|
||||
num = 20,
|
||||
): Promise<QzoneMsgDetailResult> {
|
||||
const data = await fetchQzoneMsgDetail(cookieObject, targetUin, tid, { pos, num });
|
||||
const resultTid = detailString(data.tid, 'tid');
|
||||
|
||||
if (!resultTid || resultTid !== tid) {
|
||||
throw new Error('invalid qzone msg detail: tid does not match the requested post');
|
||||
}
|
||||
|
||||
return {
|
||||
tid: resultTid,
|
||||
content: detailString(data.content, 'content'),
|
||||
comment_num: detailInteger(data.cmtnum, 'cmtnum'),
|
||||
comments: detailList(data.commentlist, 'commentlist').map((value, index) => {
|
||||
const field = `commentlist[${index}]`;
|
||||
const comment = detailObject(value, field);
|
||||
return {
|
||||
...mapQzoneComment(comment, field),
|
||||
replies: detailList(comment.list_3, `${field}.list_3`).map((reply, replyIndex) => {
|
||||
const replyField = `${field}.list_3[${replyIndex}]`;
|
||||
return mapQzoneComment(detailObject(reply, replyField), replyField);
|
||||
}),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -1760,7 +1887,7 @@ export async function updateQzoneMsgRight(
|
||||
throw new Error('target_uins is required when ugc_right is 16 or 128');
|
||||
}
|
||||
|
||||
const detail = await getQzoneMsgDetail(cookieObject, selfUin, tid);
|
||||
const detail = await fetchQzoneMsgDetail(cookieObject, selfUin, tid);
|
||||
const bodyParams = buildQzoneUpdatePayload(detail, selfUin);
|
||||
bodyParams.set('ugc_right', String(right));
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { getQzoneMsgDetail } from '@snowluma/protocol/web/qzone';
|
||||
import { RequestUtil, getBknFromCookie } from '@snowluma/protocol/web/request-util';
|
||||
|
||||
const cookies = { p_skey: 'PSK', skey: 'SK', uin: 'o10000' };
|
||||
// Synthetic data using Qzone-API's documented commentlist / list_3 wire fields.
|
||||
const reply = { tid: 1, uin: 10000, name: 'Bot', create_time: 1700000002, content: 'Thanks!' };
|
||||
const comment = {
|
||||
tid: 0,
|
||||
uin: '20002',
|
||||
name: 'Reader',
|
||||
create_time: '1700000001',
|
||||
content: 'Hello\n[em]e100[/em]',
|
||||
list_3: [reply],
|
||||
};
|
||||
const detail = { code: 0, tid: 'T1', content: 'Post', cmtnum: 12, commentlist: [comment] };
|
||||
|
||||
describe('qzone / getQzoneMsgDetail', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('reads a comment page through the authenticated detail CGI and maps replies', async () => {
|
||||
const request = vi
|
||||
.spyOn(RequestUtil, 'HttpGetText')
|
||||
.mockResolvedValue(`_preloadCallback(${JSON.stringify(detail)});`);
|
||||
const result = await getQzoneMsgDetail(cookies, '30003', 'T1', 5, 10);
|
||||
expect(result).toEqual({
|
||||
tid: 'T1',
|
||||
content: 'Post',
|
||||
comment_num: 12,
|
||||
comments: [
|
||||
{
|
||||
comment_id: '0',
|
||||
uin: 20002,
|
||||
name: 'Reader',
|
||||
time: 1700000001,
|
||||
content: 'Hello\n[em]e100[/em]',
|
||||
replies: [
|
||||
{
|
||||
comment_id: '1',
|
||||
uin: 10000,
|
||||
name: 'Bot',
|
||||
time: 1700000002,
|
||||
content: 'Thanks!',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
const [url, method, body, headers] = request.mock.calls[0]!;
|
||||
const parsed = new URL(url);
|
||||
expect(parsed.origin + parsed.pathname).toBe(
|
||||
'https://h5.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msgdetail_v6',
|
||||
);
|
||||
expect(Object.fromEntries(parsed.searchParams)).toMatchObject({
|
||||
uin: '30003',
|
||||
tid: 'T1',
|
||||
pos: '5',
|
||||
num: '10',
|
||||
not_trunc_con: '1',
|
||||
g_tk: getBknFromCookie(cookies),
|
||||
});
|
||||
expect(method).toBe('GET');
|
||||
expect(body).toBe('');
|
||||
expect(headers).toMatchObject({ Cookie: expect.stringContaining('p_skey=PSK') });
|
||||
});
|
||||
|
||||
it.each([[undefined], [null], [[]]])(
|
||||
'accepts an empty comment page (%j)',
|
||||
async (commentlist) => {
|
||||
const request = vi
|
||||
.spyOn(RequestUtil, 'HttpGetText')
|
||||
.mockResolvedValue(
|
||||
JSON.stringify({ ...detail, content: '', cmtnum: 0, commentlist }),
|
||||
);
|
||||
await expect(getQzoneMsgDetail(cookies, '10000', 'T1')).resolves.toEqual({
|
||||
tid: 'T1',
|
||||
content: '',
|
||||
comment_num: 0,
|
||||
comments: [],
|
||||
});
|
||||
const query = new URL(request.mock.calls[0]![0]).searchParams;
|
||||
expect(query.get('pos')).toBe('0');
|
||||
expect(query.get('num')).toBe('20');
|
||||
},
|
||||
);
|
||||
|
||||
it('preserves the total when a page is empty and normalizes absent replies', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText')
|
||||
.mockResolvedValueOnce(JSON.stringify({ ...detail, commentlist: [] }))
|
||||
.mockResolvedValueOnce(
|
||||
JSON.stringify({ ...detail, commentlist: [{ ...comment, list_3: null }] }),
|
||||
);
|
||||
await expect(getQzoneMsgDetail(cookies, '10000', 'T1', 20)).resolves.toMatchObject({
|
||||
comment_num: 12,
|
||||
comments: [],
|
||||
});
|
||||
const result = await getQzoneMsgDetail(cookies, '10000', 'T1');
|
||||
expect(result.comments[0]!.replies).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([{ code: -3000, subcode: 0 }, { code: 0, subcode: -4001 }, { subcode: -4001 }])(
|
||||
'propagates remote failure %j',
|
||||
async (codes) => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(
|
||||
JSON.stringify({ ...codes, message: 'denied' }),
|
||||
);
|
||||
await expect(getQzoneMsgDetail(cookies, '10000', 'T1')).rejects.toThrow(
|
||||
/qzone msg detail failed: .*denied/,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{},
|
||||
{ ...detail, tid: undefined },
|
||||
{ ...detail, tid: 'OTHER' },
|
||||
{ ...detail, code: '0' },
|
||||
{ ...detail, content: {} },
|
||||
{ ...detail, cmtnum: -1 },
|
||||
{ ...detail, commentlist: {} },
|
||||
{ ...detail, commentlist: [null] },
|
||||
{ ...detail, commentlist: [{ ...comment, uin: 'bad' }] },
|
||||
{ ...detail, commentlist: [{ ...comment, tid: {} }] },
|
||||
{ ...detail, commentlist: [{ ...comment, create_time: 'yesterday' }] },
|
||||
{ ...detail, commentlist: [{ ...comment, list_3: {} }] },
|
||||
{ ...detail, commentlist: [{ ...comment, list_3: [{ ...reply, content: {} }] }] },
|
||||
])('rejects malformed data instead of returning an empty success (%#)', async (data) => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(JSON.stringify(data));
|
||||
await expect(getQzoneMsgDetail(cookies, '10000', 'T1')).rejects.toThrow(/qzone msg detail/);
|
||||
});
|
||||
|
||||
it('propagates transport and JSONP parse errors', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText')
|
||||
.mockRejectedValueOnce(new Error('network down'))
|
||||
.mockResolvedValueOnce('<html>login</html>');
|
||||
await expect(getQzoneMsgDetail(cookies, '10000', 'T1')).rejects.toThrow('network down');
|
||||
await expect(getQzoneMsgDetail(cookies, '10000', 'T1')).rejects.toThrow(
|
||||
'invalid response from qzone api',
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user