feat(qzone): 完善空间 API 并兼容 SnowLuma API 格式 (#2124)

* feat(qzone): 接入内置空间动态、说说和赞评接口

新增好友动态、个人说说、详情及点赞、取消赞、评论和回复动作。
纯文本发表接入QQ内置空间接口,保留原有图片发表和删除路径。
保留完整动态身份和原始数据,约束游标、权限转换及请求错误处理。

验证:全工作区类型检查,367项测试通过、1项既有条件测试跳过,
变更文件ESLint及WebUI、Shell、Framework、OpenAPI构建通过。

* feat(qzone): 补齐空间管理、评论分页及 SnowLuma 兼容

* fix(qzone): 兼容真实 FormSender 回执与评论字段

* fix(qzone): 兼容黑名单回执中的空间名称

* docs(qzone): remove redundant API readme
This commit is contained in:
Qiao authored and GitHub committed 2026-10-30 00:17:49 +08:00
1 parent ba0a53dd37
commit 49ecfe0f56
48 files changed
+7534 -23

No files matched your search

+12 -1
View File
@@ -86,8 +86,19 @@ describe('Qzone data helpers', () => {
expect(result.tid).toBe('t1tid456');
});
test('keeps server publish time and the SL unknown-time sentinel', () => {
expect(parseQzonePublishResponse({ code: 0, tid: 'post', t1_time: '1700000000', now: 1700000001 })).toEqual({ tid: 'post', time: 1700000000 });
expect(parseQzonePublishResponse({ code: 0, tid: 'post', now: 1700000001 })).toEqual({ tid: 'post', time: 1700000001 });
expect(parseQzonePublishResponse({ code: 0, tid: 'post' })).toEqual({ tid: 'post', time: 0 });
expect(parseQzonePublishResponse({ code: 0, tid: 'post', t1_time: '22:08', t1_ntime: 1700000002 })).toEqual({ tid: 'post', time: 1700000002 });
expect(parseQzonePublishResponse({ code: 0, tid: 'post', t1_time: '22:08', now: 1700000003 })).toEqual({ tid: 'post', time: 1700000003 });
expect(parseQzonePublishResponse({ code: 0, tid: 'post', t1_time: '22:08' })).toEqual({ tid: 'post', time: 0 });
expect(() => parseQzonePublishResponse({ code: 0, tid: 'post', t1_time: 'bad' })).toThrow('勿自动重试');
expect(() => parseQzonePublishResponse({ code: -1, subcode: 0, tid: 'post' })).toThrow('服务端拒绝');
});
test('parseQzonePublishResponse throws when subcode indicates failure', () => {
expect(() => parseQzonePublishResponse({ subcode: -200, message: '权限不足' })).toThrow('权限不足');
expect(() => parseQzonePublishResponse({ subcode: -200, message: 'private-response' })).toThrow('服务端拒绝请求');
});
test('parseQzonePublishResponse throws when tid missing', () => {
+221
View File
@@ -0,0 +1,221 @@
// StreamBasic must be evaluated before OneBotAction because of their circular import.
import '../napcat-onebot/action/stream/StreamBasic';
import { describe, expect, it, vi } from 'vitest';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import { GetQzoneFeeds, GetQzoneFeedsPayloadSchema } from '@/napcat-onebot/action/extends/qzone/GetQzoneFeeds';
import { GetQzoneMsgList, GetQzoneMsgListPayloadSchema } from '@/napcat-onebot/action/extends/qzone/GetQzoneMsgList';
import { GetQzoneMsgDetail, GetQzoneMsgDetailPayloadSchema } from '@/napcat-onebot/action/extends/qzone/GetQzoneMsgDetail';
import { LikeQzone } from '@/napcat-onebot/action/extends/qzone/LikeQzone';
import { UnlikeQzone } from '@/napcat-onebot/action/extends/qzone/UnlikeQzone';
import { CommentQzone } from '@/napcat-onebot/action/extends/qzone/CommentQzone';
import { QzoneDetailReturnSchema, QzoneFeedItemExample, QzoneFeedReferenceExample, QzoneParentCommentSchema } from '@/napcat-onebot/action/extends/qzone/common';
function createCore () {
const QzoneApi = {
getFriendFeeds: vi.fn().mockResolvedValue({ feeds: [QzoneFeedItemExample], has_more: false, next_cursor: null }),
getMsgList: vi.fn().mockResolvedValue({ msglist: [QzoneFeedItemExample], has_more: false, next_cursor: null }),
getMsgDetail: vi.fn().mockResolvedValue({ ...QzoneFeedItemExample, comments: [] }),
setLike: vi.fn().mockResolvedValue(undefined),
comment: vi.fn().mockResolvedValue({ comment_id: 'new-comment', comment: { id: 'new-comment' } }),
};
return { apis: { QzoneApi }, context: { logger: { logError: vi.fn() } } };
}
describe('QQ空间 OneBot actions', () => {
it('passes the opaque cursor through and keeps raw feed fields in the result', async () => {
const core = createCore();
const action = new GetQzoneFeeds(undefined as never, core as never);
const first = await action._handle({ format: 'native' });
await action._handle({ cursor: 'next-page' });
expect(core.apis.QzoneApi.getFriendFeeds.mock.calls).toEqual([[undefined], ['next-page']]);
expect(first).toHaveProperty('feeds.0.feed_ref', QzoneFeedReferenceExample);
expect(first).toHaveProperty('feeds.0.feed', QzoneFeedItemExample.feed);
expect(first).not.toHaveProperty('total');
});
it('uses the current account by default and preserves numeric or string target account IDs', async () => {
const core = createCore();
const action = new GetQzoneMsgList(undefined as never, core as never);
await action._handle({ format: 'native' });
await action._handle({ format: 'native', target_uin: 123456, cursor: 'next-page' });
await action._handle({ format: 'native', target_uin: '9007199254740993' });
expect(core.apis.QzoneApi.getMsgList.mock.calls).toEqual([
[undefined, undefined],
['123456', 'next-page'],
['9007199254740993', undefined],
]);
});
it('forwards the complete reference to detail and both like operations', async () => {
const core = createCore();
const reference = {
...QzoneFeedReferenceExample,
cell_feed_transfer: { source_token: 'opaque-transfer', unknown_field: 7 },
};
await new GetQzoneMsgDetail(undefined as never, core as never)._handle({ feed_ref: reference });
await new LikeQzone(undefined as never, core as never)._handle({ feed_ref: reference });
await new UnlikeQzone(undefined as never, core as never)._handle({ feed_ref: reference });
expect(core.apis.QzoneApi.getMsgDetail).toHaveBeenCalledExactlyOnceWith(reference);
expect(core.apis.QzoneApi.setLike.mock.calls).toEqual([[reference, true], [reference, false]]);
});
it('preserves opaque reference fields and empty auxiliary union keys through schema parsing', async () => {
const core = createCore();
const reference = {
union_id: {
uf_key: 'feed-key',
ugc_id: '',
feed_id: '',
serialized_data: '',
ext_ids: [{ ext_id_type: 5, str: 'tid', unknown_numeric: '9007199254740993' }],
unknown_field: { keep: 'unchanged' },
},
cell_feed_transfer: { unknown_fields: [0, false, 'opaque-transfer'] },
};
const action = new GetQzoneMsgDetail(undefined as never, core as never);
const expected = structuredClone(reference);
const result = await action.handle({ feed_ref: reference }, 'test', {} as never);
expect(result.status).toBe('ok');
expect(core.apis.QzoneApi.getMsgDetail).toHaveBeenCalledExactlyOnceWith(expected);
expect(reference).toEqual(expected);
expect(reference.union_id.ext_ids[0]?.unknown_numeric).toBe('9007199254740993');
});
it('preserves a complete parent comment and empty auxiliary UID through the real handle parser', async () => {
const core = createCore();
const parent = {
id: '0',
user: { uin: '10002', uid: '', nick: '评论作者', opaque_user: { keep: true } },
content: [{ type: 0, content: '原评论', unknown_segment: 'keep' }],
replys: [{ id: 'reply-1', content: [{ type: 0, content: '楼中楼' }] }],
like: { id: 'comment-like-key', count: 2, status: 0 },
unknown_field: { serialized: '9007199254740993' },
};
const expected = structuredClone(parent);
const action = new CommentQzone(undefined as never, core as never);
const result = await action.handle({
feed_ref: QzoneFeedReferenceExample, content: '回复', comment: parent,
}, 'test', {} as never);
expect(result.status).toBe('ok');
expect(core.apis.QzoneApi.comment).toHaveBeenCalledExactlyOnceWith(
QzoneFeedReferenceExample, '回复', expected, undefined
);
expect(parent).toEqual(expected);
});
it('adds optional detail pagination without changing raw comment shape or write parent requirements', () => {
const detail = TypeCompiler.Compile(QzoneDetailReturnSchema);
const parent = TypeCompiler.Compile(QzoneParentCommentSchema);
expect(detail.Check({ ...QzoneFeedItemExample, comments: [] })).toBe(true);
expect(detail.Check({
...QzoneFeedItemExample,
comments: [{ id: 0, user: { uid: 'u_commenter', portrait: { source: 'opaque' } }, replys: [{ id: 'reply' }], unknown_field: true }],
comment_has_more: true,
comment_next_cursor: 'opaque-cursor',
})).toBe(true);
expect(parent.Check({ id: 0, user: { uid: 'u_commenter' } })).toBe(false);
expect(parent.Check({ id: '0', user: { uin: '10002', uid: '' } })).toBe(true);
});
it('publishes root comments and replies without synthesizing parent identities', async () => {
const core = createCore();
const action = new CommentQzone(undefined as never, core as never);
const parent = { id: '0', user: { uin: '10002', uid: 'u_parent' }, opaque_field: 'keep' };
const target = { uin: '10003', uid: 'u_reply', nick: '回复目标' };
const result = await action._handle({ feed_ref: QzoneFeedReferenceExample, content: '正文' });
await action._handle({ feed_ref: QzoneFeedReferenceExample, content: '回复', comment: parent });
await action._handle({ feed_ref: QzoneFeedReferenceExample, content: '楼中楼', comment: parent, reply_user: target });
expect(core.apis.QzoneApi.comment.mock.calls).toEqual([
[QzoneFeedReferenceExample, '正文', undefined, undefined],
[QzoneFeedReferenceExample, '回复', parent, undefined],
[QzoneFeedReferenceExample, '楼中楼', parent, target],
]);
expect(result.comment_id).toBe('new-comment');
});
it('rejects empty comments and reply targets without a parent before invoking the API', async () => {
const core = createCore();
const action = new CommentQzone(undefined as never, core as never);
const blank = await action.handle({ feed_ref: QzoneFeedReferenceExample, content: ' \n ' }, 'test', {} as never);
const orphan = await action.handle({
feed_ref: QzoneFeedReferenceExample,
content: '正文',
reply_user: { uin: '10003' },
}, 'test', {} as never);
expect(blank.status).toBe('failed');
expect(orphan.status).toBe('failed');
expect(core.apis.QzoneApi.comment).not.toHaveBeenCalled();
});
it('accepts both schema families while rejecting invalid references and scalar shapes', () => {
const feeds = TypeCompiler.Compile(GetQzoneFeedsPayloadSchema);
const list = TypeCompiler.Compile(GetQzoneMsgListPayloadSchema);
const detail = TypeCompiler.Compile(GetQzoneMsgDetailPayloadSchema);
expect(feeds.Check({ cursor: 'a'.repeat(65537) })).toBe(false);
expect(feeds.Check({ page_num: 1, count: 10 })).toBe(true);
expect(list.Check({ pos: 0, num: 20 })).toBe(true);
expect(list.Check({ target_uin: Number.MAX_SAFE_INTEGER + 1 })).toBe(false);
expect(list.Check({ target_uin: 'not-a-qq-number' })).toBe(false);
expect(detail.Check({ tid: 'shuoshuo-tid' })).toBe(true);
expect(detail.Check({ feed_ref: { union_id: [] } })).toBe(false);
expect(detail.Check({ feed_ref: { union_id: {} } })).toBe(false);
expect(detail.Check({ feed_ref: { ...QzoneFeedReferenceExample, feed_action_domain_type: 0 } })).toBe(false);
});
it('surfaces API errors as failed actions and only calls the write API once', async () => {
const core = createCore();
core.apis.QzoneApi.setLike.mockRejectedValue(new Error('QQ空间返回的点赞结果不完整'));
const action = new LikeQzone(undefined as never, core as never);
const result = await action.handle({ feed_ref: QzoneFeedReferenceExample }, 'test', {} as never);
expect(result.status).toBe('failed');
expect(result.message).toContain('点赞结果不完整');
expect(core.apis.QzoneApi.setLike).toHaveBeenCalledTimes(1);
});
it('returns explicit null data for both successful like actions', async () => {
const core = createCore();
for (const Action of [LikeQzone, UnlikeQzone]) {
const result = await new Action(undefined as never, core as never).handle(
{ feed_ref: QzoneFeedReferenceExample }, 'test', {} as never
);
expect(JSON.parse(JSON.stringify(result))).toMatchObject({ status: 'ok', retcode: 0, data: null });
}
});
it('declares the SnowLuma action names with schema-valid payload and result examples', () => {
const core = createCore();
const actions = [
new GetQzoneFeeds(undefined as never, core as never),
new GetQzoneMsgList(undefined as never, core as never),
new GetQzoneMsgDetail(undefined as never, core as never),
new LikeQzone(undefined as never, core as never),
new UnlikeQzone(undefined as never, core as never),
new CommentQzone(undefined as never, core as never),
];
expect(actions.map(action => action.actionName)).toEqual([
'get_qzone_feeds', 'get_qzone_msg_list', 'get_qzone_msg_detail', 'like_qzone', 'unlike_qzone', 'comment_qzone',
]);
for (const action of actions) {
expect(TypeCompiler.Compile(action.payloadSchema).Check(action.payloadExample)).toBe(true);
expect(TypeCompiler.Compile(action.returnSchema).Check(action.returnExample)).toBe(true);
}
});
});
@@ -0,0 +1,160 @@
// StreamBasic must be evaluated before OneBotAction because of their circular import.
import '../napcat-onebot/action/stream/StreamBasic';
import { describe, expect, it, vi } from 'vitest';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import { GetQzoneCommentList } from '@/napcat-onebot/action/extends/qzone/GetQzoneCommentList';
import { GetQzoneCommentReplies } from '@/napcat-onebot/action/extends/qzone/GetQzoneCommentReplies';
import { QzoneFeedReferenceExample } from '@/napcat-onebot/action/extends/qzone/common';
import { QzoneCommentPageExample, QzoneReplyPageExample } from '@/napcat-onebot/action/extends/qzone/common-comment';
function createCore () {
return {
apis: {
QzoneApi: {
getComments: vi.fn().mockResolvedValue(QzoneCommentPageExample),
getCommentReplies: vi.fn().mockResolvedValue(QzoneReplyPageExample),
},
},
context: { logger: { logError: vi.fn() } },
};
}
describe('QQ空间评论读取 actions', () => {
it('passes the complete reference and optional opaque cursor to comment reads', async () => {
const core = createCore();
const action = new GetQzoneCommentList(undefined as never, core as never);
const reference = {
...QzoneFeedReferenceExample,
union_id: { ...QzoneFeedReferenceExample.union_id, unknown_field: { large_id: '9007199254740993' } },
cell_feed_transfer: { opaque: [0, false, 'keep'] },
};
const expected = structuredClone(reference);
const first = await action.handle({ feed_ref: reference }, 'test', {} as never);
await action.handle({ feed_ref: reference, cursor: 'next-comment-cursor' }, 'test', {} as never);
expect(core.apis.QzoneApi.getComments.mock.calls).toEqual([[expected, undefined], [expected, 'next-comment-cursor']]);
expect(first.data).toBe(QzoneCommentPageExample);
expect(reference).toEqual(expected);
});
it('retains raw parent identity types, UID-only authors and every unknown field through handle parsing', async () => {
const core = createCore();
const action = new GetQzoneCommentReplies(undefined as never, core as never);
const parent = {
id: 0,
user: { uid: 'u_commenter', uin: '', nick: '', portrait: { source: 'opaque-portrait' }, unknown_user: 'keep' },
content: [{ type: 0, content: '原评论', unknown_segment: true }],
replys: [{ id: 'reply-1', content: [{ type: 0, content: '内联回复' }] }],
reply_attach_info: 'server-reply-pointer',
like: { id: 'like-key', count: 0, status: 0 },
unknown_field: { large_id: '9007199254740993' },
};
const expected = structuredClone(parent);
const result = await action.handle({ feed_ref: QzoneFeedReferenceExample, comment: parent }, 'test', {} as never);
await action.handle({ feed_ref: QzoneFeedReferenceExample, comment: { id: '0' }, cursor: 'next-reply-cursor' }, 'test', {} as never);
expect(result.status).toBe('ok');
expect(core.apis.QzoneApi.getCommentReplies.mock.calls).toEqual([
[QzoneFeedReferenceExample, expected, undefined],
[QzoneFeedReferenceExample, { id: '0' }, 'next-reply-cursor'],
]);
expect(typeof core.apis.QzoneApi.getCommentReplies.mock.calls[0]?.[1]?.id).toBe('number');
expect(typeof core.apis.QzoneApi.getCommentReplies.mock.calls[1]?.[1]?.id).toBe('string');
expect(parent).toEqual(expected);
});
it('allows an omitted author or empty auxiliary user object when the parent ID is exact', async () => {
const core = createCore();
const action = new GetQzoneCommentReplies(undefined as never, core as never);
for (const parent of [{ id: 'parent' }, { id: 'parent', user: {} }, { id: 0, user: { uin: '', uid: '' } }]) {
const result = await action.handle({ feed_ref: QzoneFeedReferenceExample, comment: parent }, 'test', {} as never);
expect(result.status).toBe('ok');
}
expect(core.apis.QzoneApi.getCommentReplies).toHaveBeenCalledTimes(3);
});
it('rejects malformed parent IDs before TypeBox can coerce them or invoke the core', async () => {
const core = createCore();
const action = new GetQzoneCommentReplies(undefined as never, core as never);
for (const id of [undefined, null, false, true, '', ' ', -1, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1, {}, []]) {
const result = await action.handle({ feed_ref: QzoneFeedReferenceExample, comment: { id } } as never, 'test', {} as never);
expect(result.status).toBe('failed');
}
expect(core.apis.QzoneApi.getCommentReplies).not.toHaveBeenCalled();
});
it('rejects malformed read payloads and unsupported page controls before invoking the core', async () => {
const cases = [
[GetQzoneCommentList, { feed_ref: QzoneFeedReferenceExample, page_size: 100 }],
[GetQzoneCommentList, { feed_ref: QzoneFeedReferenceExample, cursor: false }],
[GetQzoneCommentList, { feed_ref: QzoneFeedReferenceExample, cursor: '' }],
[GetQzoneCommentList, { feed_ref: QzoneFeedReferenceExample, cursor: 'x'.repeat(16385) }],
[GetQzoneCommentList, { feed_ref: { union_id: {} } }],
[GetQzoneCommentReplies, { feed_ref: QzoneFeedReferenceExample, comment: [] }],
[GetQzoneCommentReplies, { feed_ref: QzoneFeedReferenceExample, comment: { id: 'parent', user: [] } }],
[GetQzoneCommentReplies, { feed_ref: QzoneFeedReferenceExample, comment: { id: 'parent', user: null } }],
[GetQzoneCommentReplies, { feed_ref: QzoneFeedReferenceExample, comment: { id: 'parent', content: '中'.repeat(22 * 1024) } }],
[GetQzoneCommentReplies, { feed_ref: QzoneFeedReferenceExample, comment: { id: 'parent' }, page_size: 20 }],
[GetQzoneCommentReplies, { feed_ref: QzoneFeedReferenceExample, comment: { id: 'parent' }, target_uin: '10002' }],
] as const;
for (const [Action, payload] of cases) {
const core = createCore();
const result = await new Action(undefined as never, core as never).handle(payload as never, 'test', {} as never);
expect(result.status).toBe('failed');
expect(core.apis.QzoneApi.getComments).not.toHaveBeenCalled();
expect(core.apis.QzoneApi.getCommentReplies).not.toHaveBeenCalled();
}
});
it('returns partial and unknown metadata exactly instead of claiming complete comment history', async () => {
const core = createCore();
const page = {
...QzoneCommentPageExample,
comment_num: null,
comments: [{ ...QzoneCommentPageExample.comments[0]!, reply_num: null, has_more_replies: null, replies: [] }],
has_more: true,
next_cursor: 'next-page',
raw: { unknown_server_field: true },
};
core.apis.QzoneApi.getComments.mockResolvedValueOnce(page);
const result = await new GetQzoneCommentList(undefined as never, core as never).handle(
{ feed_ref: QzoneFeedReferenceExample }, 'test', {} as never
);
expect(result.data).toBe(page);
expect(page.comments[0]?.has_more_replies).toBeNull();
expect(page.raw).toEqual({ unknown_server_field: true });
});
it('surfaces cursor failures without retrying the read', async () => {
const core = createCore();
core.apis.QzoneApi.getComments.mockRejectedValueOnce(new Error('QQ空间评论游标无效或已过期'));
const result = await new GetQzoneCommentList(undefined as never, core as never).handle(
{ feed_ref: QzoneFeedReferenceExample, cursor: 'expired-cursor' }, 'test', {} as never
);
expect(result.status).toBe('failed');
expect(result.message).toContain('游标无效或已过期');
expect(core.apis.QzoneApi.getComments).toHaveBeenCalledTimes(1);
});
it('declares complete API metadata with schema-valid detailed examples', () => {
const core = createCore();
const actions = [
new GetQzoneCommentList(undefined as never, core as never),
new GetQzoneCommentReplies(undefined as never, core as never),
];
expect(actions.map(action => action.actionName)).toEqual(['get_qzone_comment_list', 'get_qzone_comment_replies']);
for (const action of actions) {
expect(action.actionSummary).not.toBe('');
expect(action.actionDescription).not.toBe('');
expect(action.actionTags).toContain('扩展接口');
expect(TypeCompiler.Compile(action.payloadSchema).Check(action.payloadExample)).toBe(true);
expect(TypeCompiler.Compile(action.returnSchema).Check(action.returnExample)).toBe(true);
}
});
});
@@ -0,0 +1,401 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { NTQQQzoneApi } from '@/napcat-core/apis/qzone';
import type { QzoneComment, QzoneFeed, QzoneFeedReference } from '@/napcat-core/data/qzone-rpc';
function createApi () {
const core = {
selfInfo: { uin: '10001', uid: 'self-uid', nick: '当前账号' },
apis: {
UserApi: {
getSKey: vi.fn().mockResolvedValue('s'),
getPSkey: vi.fn().mockResolvedValue({ result: 0, domainPskeyMap: new Map([['qzone.qq.com', 'p']]) }),
},
},
};
return { api: new NTQQQzoneApi({} as never, core as never), core };
}
function response (data: Record<string, unknown>, retcode = 0): Response {
return new Response(JSON.stringify({ retcode, data }), { status: 200 });
}
function reference (): QzoneFeedReference {
return {
union_id: { uf_key: 'old-key', ugc_id: 'old-ugc', feed_id: 'old-feed', serialized_data: 'old-opaque' },
cell_feed_transfer: { nested: { value: 'old-transfer' } },
feed_action_domain_type: 1,
like_key: 'old-like',
};
}
function parent (): QzoneComment {
return {
id: 0,
user: { uid: 'uid-only-author', nick: '父评论作者', portrait: 'https://example.com/avatar' },
time: 1700000000,
content: [{ type: 0, content: ' 原评论 ' }],
like: { id: 'parent-like', count: 2, status: 1 },
reply_num: 8,
has_more_reply: true,
reply_attach_info: 'inline-reply-end',
replys: [{ id: 'inline-reply', content: [{ type: 0, content: '内联回复' }] }],
opaque: { keep: 'parent-context' },
};
}
function detail (comments: QzoneComment[] = [parent()]): { feed: { feed: QzoneFeed }; attach_info: string; has_more: boolean; extra: string; } {
return {
feed: {
feed: {
cell_common: {
union_id: { uf_key: 'fresh-key', ugc_id: 'fresh-ugc', feed_id: 'fresh-feed', serialized_data: 'fresh-opaque' },
feed_type: 1,
feed_sub_type: 1,
domain_type: 2,
cur_like_key: 'fresh-like',
},
cell_feed_transfer: { nested: { value: 'fresh-transfer' } },
cell_comment: { num: 32, comments },
cell_summary: { summary: [{ type: 0, content: '说说正文' }] },
},
},
attach_info: 'comment-page-2',
has_more: true,
extra: 'retained-business-data',
};
}
describe('Qzone comment and reply page transport', () => {
let fetchMock: ReturnType<typeof vi.fn<typeof fetch>>;
beforeEach(() => {
fetchMock = vi.fn<typeof fetch>();
vi.stubGlobal('fetch', fetchMock);
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it('gets the first comment batch from detail and returns its updated full reference and raw response', async () => {
const { api } = createApi();
const business = detail();
fetchMock.mockResolvedValueOnce(response(business));
const page = await api.getComments(reference());
expect(String(fetchMock.mock.calls[0]![0])).toContain('/GetFeedDetail?');
expect(page).toMatchObject({
comment_num: 32,
has_more: true,
next_cursor: expect.any(String),
raw: business,
feed_ref: {
union_id: business.feed.feed.cell_common!.union_id,
cell_feed_transfer: business.feed.feed.cell_feed_transfer,
feed_action_domain_type: 2,
like_key: 'fresh-like',
},
});
expect(page.comments[0]).toMatchObject({
comment_id: '0',
user_id: null,
uid: 'uid-only-author',
nickname: '父评论作者',
time: 1700000000,
content: ' 原评论 ',
like_count: 2,
liked: true,
reply_num: 8,
has_more_replies: true,
comment: parent(),
});
expect(page.comments[0]?.replies).toHaveLength(1);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('fetches exactly one continuation page with the fresh context and never invents a page-size or total', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response(detail()));
fetchMock.mockResolvedValueOnce(response({ cell_comment: { comments: [{ id: 'next-comment', opaque: true }] }, has_more: false, extra: 'next' }));
const first = await api.getComments(reference());
const next = await api.getComments(first.feed_ref, first.next_cursor!);
const [url, options] = fetchMock.mock.calls[1]!;
expect(String(url)).toContain('/GetComment?');
expect(options?.headers).toMatchObject({ 'x-oidb': '{"uint32_command":"0x9bfd","uint32_service_type":"1"}' });
expect(JSON.parse(options?.body as string)).toEqual({
union_id: first.feed_ref.union_id, attach_info: 'comment-page-2', cell_feed_transfer: first.feed_ref.cell_feed_transfer,
});
expect(next).toMatchObject({ comment_num: null, has_more: false, next_cursor: null, raw: { extra: 'next' } });
expect(next.comments).toHaveLength(1);
expect(next.comments[0]?.comment).toEqual({ id: 'next-comment', opaque: true });
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('preserves old detail comments and exposes a usable continuation without another detail read', async () => {
const { api } = createApi();
const original = reference();
original['opaque_entry'] = { preserve: 'internal-context' };
const business = detail();
delete business.feed.feed.cell_feed_transfer;
fetchMock.mockResolvedValueOnce(response(business));
fetchMock.mockResolvedValueOnce(response({ cell_comment: { num: 33, comments: [] }, has_more: false }));
const first = await api.getMsgDetail(original);
expect(first.comments).toEqual([parent()]);
expect(first.feed_ref).not.toHaveProperty('cell_feed_transfer');
expect(first.feed_ref).not.toHaveProperty('opaque_entry');
expect(first.comment_has_more).toBe(true);
expect(first.comment_next_cursor).toEqual(expect.any(String));
const next = await api.getComments(first.feed_ref!, first.comment_next_cursor!);
expect(String(fetchMock.mock.calls[1]![0])).toContain('/GetComment?');
expect(JSON.parse(fetchMock.mock.calls[1]![1]?.body as string)).toMatchObject({
union_id: business.feed.feed.cell_common!.union_id, cell_feed_transfer: original.cell_feed_transfer,
});
expect(next.feed_ref).toMatchObject({ cell_feed_transfer: original.cell_feed_transfer, opaque_entry: { preserve: 'internal-context' } });
expect(next.comment_num).toBe(33);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('does not issue a detail continuation when its old normalized feed_ref is null', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ feed: { feed: { cell_comment: { comments: [parent()] } } }, has_more: true, attach_info: 'next' }));
const result = await api.getMsgDetail(reference());
expect(result.feed_ref).toBeNull();
expect(result.comments).toEqual([parent()]);
expect(result.comment_has_more).toBe(true);
expect(result.comment_next_cursor).toBeNull();
});
it('retains missing detail union/transfer from the supplied context for explicit comment reads', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ feed: { feed: { cell_comment: { num: 0, comments: [] } } }, has_more: false }));
await expect(api.getComments(reference())).resolves.toMatchObject({
feed_ref: reference(), comment_num: 0, comments: [], has_more: false, next_cursor: null,
});
});
it('returns additional replies using numeric parent id zero and a complete UID-only parent', async () => {
const { api } = createApi();
const originalParent = parent();
const reply = { id: 1, user: { uid: 'reply-uid', nick: '' }, target_user: { uid: 'uid-only-author' }, time: 1700000001, content: [{ type: 0, content: '追加回复' }], opaque: true };
fetchMock.mockResolvedValueOnce(response({ replys: [reply], has_more: true, reply_attach_info: 'reply-page-2', opaque: 'kept' }));
const page = await api.getCommentReplies(reference(), originalParent);
const [url, options] = fetchMock.mock.calls[0]!;
expect(String(url)).toContain('/GetReplies?');
expect(options?.headers).toMatchObject({ 'x-oidb': '{"uint32_command":"0x9bfe","uint32_service_type":"1"}' });
const request = JSON.parse(options?.body as string);
expect(request).toEqual({
union_id: reference().union_id,
cur_comment: originalParent,
comment_attach_info: '',
reply_attach_info: 'inline-reply-end',
page_size: 20,
cell_feed_transfer: reference().cell_feed_transfer,
});
expect(request.cur_comment.id).toBe(0);
expect(page).toMatchObject({ comment_id: '0', reply_num: 8, has_more: true, next_cursor: expect.any(String), raw: { opaque: 'kept' } });
expect(page.replies).toHaveLength(1);
expect(page.replies[0]).toMatchObject({ reply_id: '1', uid: 'reply-uid', target_uid: 'uid-only-author', content: '追加回复', reply });
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('supports read parents without user and preserves string id zero without write-author validation', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ replys: [], has_more: false }));
const result = await api.getCommentReplies(reference(), { id: '0', opaque: { data: true } });
expect(result).toMatchObject({ comment_id: '0', reply_num: null, replies: [], has_more: false, next_cursor: null });
expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string)).toMatchObject({
cur_comment: { id: '0', opaque: { data: true } }, reply_attach_info: '', comment_attach_info: '', page_size: 20,
});
});
it('snapshots the parent and transfer before awaiting auth and uses stored context on continuation', async () => {
const { api } = createApi();
const inputRef = reference();
const savedRef = structuredClone(inputRef);
const inputParent = parent();
const savedParent = structuredClone(inputParent);
fetchMock.mockResolvedValueOnce(response({ replys: [{ id: 'page-one' }], has_more: true, reply_attach_info: 'reply-page-2' }));
fetchMock.mockResolvedValueOnce(response({ replys: [{ id: 'page-two' }], has_more: false, reply_num: 9 }));
const pending = api.getCommentReplies(inputRef, inputParent);
(inputRef.cell_feed_transfer as { nested: { value: string; }; }).nested.value = 'caller-transfer-mutation';
inputParent.user!.nick = 'caller-user-mutation';
inputParent.content![0]!.content = 'caller-content-mutation';
inputParent.replys!.push({ id: 'caller-injected' });
const first = await pending;
expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string)).toMatchObject({ cur_comment: savedParent, cell_feed_transfer: savedRef.cell_feed_transfer });
// A different author identity is rejected, while modified display/body fields never replace the cached parent.
await expect(api.getCommentReplies(savedRef, inputParent, first.next_cursor!)).rejects.toThrow('游标无效');
const callerParent = structuredClone(savedParent);
callerParent.content = [{ type: 0, content: 'ignored new body' }];
callerParent.replys = [{ id: 'ignored extra reply' }];
const last = await api.getCommentReplies(savedRef, callerParent, first.next_cursor!);
expect(JSON.parse(fetchMock.mock.calls[1]![1]?.body as string)).toEqual({
union_id: savedRef.union_id,
cur_comment: { ...savedParent, reply_attach_info: 'reply-page-2', has_more_reply: true },
comment_attach_info: '',
reply_attach_info: 'reply-page-2',
page_size: 20,
cell_feed_transfer: savedRef.cell_feed_transfer,
});
expect(last.replies).toHaveLength(1);
expect(last.reply_num).toBe(9);
expect(last.next_cursor).toBeNull();
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('protects cached comment context from mutations through returned feed_ref and raw objects', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response(detail()));
fetchMock.mockResolvedValueOnce(response({ cell_comment: { comments: [] }, has_more: false }));
const first = await api.getComments(reference());
const savedRef = structuredClone(first.feed_ref);
(first.feed_ref.cell_feed_transfer as { nested: { value: string; }; }).nested.value = 'response-mutation';
((first.raw['feed'] as { feed: QzoneFeed; }).feed.cell_feed_transfer as { nested: { value: string; }; }).nested.value = 'raw-mutation';
const next = await api.getComments(savedRef, first.next_cursor!);
expect(next.feed_ref).toEqual(savedRef);
expect(JSON.parse(fetchMock.mock.calls[1]![1]?.body as string).cell_feed_transfer).toEqual(savedRef.cell_feed_transfer);
});
it('binds cursors to query kind, full feed reference and exact parent id/user', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response(detail()));
const comments = await api.getComments(reference());
const ref = comments.feed_ref;
fetchMock.mockResolvedValueOnce(response({ replys: [], has_more: true, reply_attach_info: 'reply-next' }));
const replies = await api.getCommentReplies(ref, parent());
await expect(api.getCommentReplies(ref, parent(), comments.next_cursor!)).rejects.toThrow('游标无效');
await expect(api.getComments(ref, replies.next_cursor!)).rejects.toThrow('游标无效');
for (const modified of [
{ ...ref, union_id: { ...ref.union_id, serialized_data: 'different-union-context' } },
{ ...ref, cell_feed_transfer: { different: true } },
{ ...ref, feed_action_domain_type: 3 },
]) {
await expect(api.getComments(modified, comments.next_cursor!)).rejects.toThrow('游标无效');
}
await expect(api.getCommentReplies(ref, { ...parent(), id: '0' }, replies.next_cursor!)).rejects.toThrow('游标无效');
await expect(api.getCommentReplies(ref, { ...parent(), user: { uid: 'other-user' } }, replies.next_cursor!)).rejects.toThrow('游标无效');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('allows JSON property reordering but rejects account changes and expired cursors before network IO', async () => {
const { api, core } = createApi();
const clock = vi.spyOn(Date, 'now').mockReturnValue(1000000);
fetchMock.mockResolvedValueOnce(response(detail()));
fetchMock.mockResolvedValueOnce(response({ cell_comment: { comments: [] }, has_more: false }));
const first = await api.getComments(reference());
const reordered = Object.fromEntries(Object.entries(first.feed_ref).reverse()) as QzoneFeedReference;
await api.getComments(reordered, first.next_cursor!);
core.selfInfo.uin = '20002';
core.selfInfo.uid = 'another-uid';
await expect(api.getComments(first.feed_ref, first.next_cursor!)).rejects.toThrow('游标无效');
core.selfInfo.uin = '10001';
core.selfInfo.uid = 'self-uid';
clock.mockReturnValue(1000000 + 10 * 60 * 1000);
await expect(api.getComments(first.feed_ref, first.next_cursor!)).rejects.toThrow('已过期');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('reuses the shared 128-entry cursor bound across existing feeds and new comment pages', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response(detail()));
const first = await api.getComments(reference());
fetchMock.mockImplementation(async () => response({ feeds: [{ feed: detail().feed.feed }], has_more: true, attach_info: 'feed-next' }));
for (let i = 0; i < 128; i++) await api.getFriendFeeds();
await expect(api.getComments(first.feed_ref, first.next_cursor!)).rejects.toThrow('游标无效');
expect(fetchMock).toHaveBeenCalledTimes(129);
});
it('rejects malformed parents and reference bodies before acquiring tickets', async () => {
const { api, core } = createApi();
const cycle: Record<string, unknown> = { id: 0 };
cycle['loop'] = cycle;
const badParents: unknown[] = [
{}, { id: '' }, { id: true }, { id: null }, { id: -1 }, { id: 1.5 }, { id: Number.MAX_SAFE_INTEGER + 1 },
{ id: 0, user: [] }, { id: 0, user: 'bad' }, { id: 0, opaque: 'x'.repeat(65536) },
{ id: 0, number: Number.NaN }, { id: 0, method: () => {} }, cycle,
];
for (const invalid of badParents) await expect(api.getCommentReplies(reference(), invalid as QzoneComment)).rejects.toThrow();
await expect(api.getComments({ union_id: {} })).rejects.toThrow();
await expect(api.getCommentReplies(reference(), { id: 0, reply_attach_info: 12 })).rejects.toThrow('续页信息无效');
expect(fetchMock).not.toHaveBeenCalled();
expect(core.apis.UserApi.getSKey).not.toHaveBeenCalled();
});
it('rejects missing or non-advancing server pointers rather than repeating the same page', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ ...detail(), attach_info: undefined }));
await expect(api.getComments(reference())).rejects.toThrow('未推进');
fetchMock.mockResolvedValueOnce(response(detail()));
const first = await api.getComments(reference());
fetchMock.mockResolvedValueOnce(response({ cell_comment: { comments: [] }, has_more: true, attach_info: 'comment-page-2' }));
await expect(api.getComments(first.feed_ref, first.next_cursor!)).rejects.toThrow('未推进');
fetchMock.mockResolvedValueOnce(response({ replys: [], has_more: true }));
await expect(api.getCommentReplies(reference(), parent())).rejects.toThrow('未推进');
fetchMock.mockResolvedValueOnce(response({ replys: [], has_more: true, reply_attach_info: 'inline-reply-end' }));
await expect(api.getCommentReplies(reference(), parent())).rejects.toThrow('未推进');
expect(fetchMock).toHaveBeenCalledTimes(5);
});
it('does not disguise malformed response objects as successful empty pages', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response(detail()));
const first = await api.getComments(reference());
fetchMock.mockResolvedValueOnce(response({}));
await expect(api.getComments(first.feed_ref, first.next_cursor!)).rejects.toThrow('cell_comment');
fetchMock.mockResolvedValueOnce(response({ cell_comment: { comments: [null] }, has_more: false }));
await expect(api.getComments(first.feed_ref, first.next_cursor!)).rejects.toThrow('评论响应格式异常');
fetchMock.mockResolvedValueOnce(response({}));
await expect(api.getCommentReplies(reference(), parent())).rejects.toThrow('回复响应格式异常');
fetchMock.mockResolvedValueOnce(response({ replys: [null], has_more: false }));
await expect(api.getCommentReplies(reference(), parent())).rejects.toThrow('回复响应格式异常');
expect(fetchMock).toHaveBeenCalledTimes(5);
});
it('accepts omitted empty lists only when the server explicitly marks the final page', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response(detail()));
const first = await api.getComments(reference());
for (const lastPage of [{ has_more: false }, { cell_comment: { num: 0 }, has_more: false }]) {
fetchMock.mockResolvedValueOnce(response(lastPage));
await expect(api.getComments(first.feed_ref, first.next_cursor!)).resolves.toMatchObject({
comments: [], has_more: false, next_cursor: null, raw: lastPage,
});
}
fetchMock.mockResolvedValueOnce(response({ has_more: false }));
await expect(api.getCommentReplies(reference(), parent())).resolves.toMatchObject({
replies: [], has_more: false, next_cursor: null, raw: { has_more: false },
});
for (const badPage of [{ cell_comment: {} }, { has_more: true, attach_info: 'advanced' }, { cell_comment: null, has_more: false }, { cell_comment: { comments: null }, has_more: false }]) {
fetchMock.mockResolvedValueOnce(response(badPage));
await expect(api.getComments(first.feed_ref, first.next_cursor!)).rejects.toThrow('评论响应');
}
for (const badPage of [{ has_more: true, reply_attach_info: 'advanced' }, { replys: null, has_more: false }]) {
fetchMock.mockResolvedValueOnce(response(badPage));
await expect(api.getCommentReplies(reference(), parent())).rejects.toThrow('回复响应');
}
expect(fetchMock).toHaveBeenCalledTimes(10);
});
it('retains detail compatibility for omitted initial comment cells and never echoes private RPC errors', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ feed: { feed: {} }, has_more: false }));
const page = await api.getComments(reference());
expect(page).toMatchObject({ comment_num: null, comments: [], has_more: false, next_cursor: null });
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ retcode: 4003, message: 'private credential', data: {} })));
try {
await api.getCommentReplies(reference(), parent());
expect.fail('must reject business error');
} catch (error) {
expect(String(error)).toContain('4003');
expect(String(error)).not.toContain('private');
}
expect(fetchMock).toHaveBeenCalledTimes(2);
});
});
@@ -0,0 +1,174 @@
import { describe, expect, test } from 'vitest';
import { normalizeQzoneComment, normalizeQzoneReply } from '@/napcat-core/data/qzone-comments';
import { normalizeQzoneFeed, normalizeQzoneMediaImages, normalizeQzoneRichContent, type QzoneComment } from '@/napcat-core/data/qzone-rpc';
describe('Qzone comment and reply projections', () => {
test('keeps unknown comment values null without inventing history or counts', () => {
const comment = { future_field: { opaque: true } };
const normalized = normalizeQzoneComment(comment);
expect(normalized).toEqual({
comment_id: null,
user_id: null,
uid: null,
nickname: null,
time: null,
content: null,
images: null,
like_count: null,
liked: null,
reply_num: null,
has_more_replies: null,
replies: [],
comment,
});
expect(normalized.comment).toBe(comment);
});
test('normalizes the observed parent fields and preserves its complete raw object', () => {
const reply = {
id: 'reply-1',
user: { uin: '10002', uid: 'u_reply', nick: '回复者' },
target_user: { uin: '10001', uid: 'u_parent', nick: '作者' },
time: '1700000001',
content: [{ type: 0, content: '原始回复' }],
like: { id: 'reply-like-key', count: '3', status: 0 },
future_reply_field: 'keep',
};
const comment: QzoneComment = {
id: '0',
user: { uin: '10001', uid: 'u_parent', nick: '作者', portrait: 'https://example.com/avatar' },
time: 1700000000,
content: [{ type: 0, content: '第一行\n' }, { type: 1, name: 'Qiao', uin: '10003' }],
media_items: [{ type: 0, image: { photo_url: [{ spec: 6, url: { url: 'https://example.com/original' } }] } }],
like: { id: 'parent-like-key', count: 7, status: 1 },
reply_num: 12,
has_more_reply: true,
reply_attach_info: 'opaque-token',
replys: [reply],
unknown_field: [0, false, 'keep'],
};
const normalized = normalizeQzoneComment(comment);
expect(normalized).toMatchObject({
comment_id: '0',
user_id: '10001',
uid: 'u_parent',
nickname: '作者',
time: 1700000000,
content: '第一行\n@Qiao',
images: ['https://example.com/original'],
like_count: 7,
liked: true,
reply_num: 12,
has_more_replies: true,
});
expect(normalized.replies).toHaveLength(1);
expect(normalized.replies[0]).toMatchObject({
reply_id: 'reply-1',
user_id: '10002',
uid: 'u_reply',
nickname: '回复者',
time: 1700000001,
content: '原始回复',
like_count: 3,
liked: false,
target_user_id: '10001',
target_uid: 'u_parent',
target_nickname: '作者',
});
expect(normalized.comment).toBe(comment);
expect(normalized.replies[0]?.reply).toBe(reply);
expect(comment['reply_attach_info']).toBe('opaque-token');
expect(comment.user?.['portrait']).toBe('https://example.com/avatar');
expect(comment['unknown_field']).toEqual([0, false, 'keep']);
});
test('uses time rather than create_time and does not turn display defaults into facts', () => {
expect(normalizeQzoneComment({ create_time: 1700000000 }).time).toBeNull();
expect(normalizeQzoneReply({ create_time: 1700000000 }).time).toBeNull();
expect(normalizeQzoneComment({ time: 0, reply_num: 0, has_more_reply: false, like: { count: 0, status: 0 } }))
.toMatchObject({ time: 0, reply_num: 0, has_more_replies: false, like_count: 0, liked: false });
expect(normalizeQzoneReply({ time: '0', like: { count: '0', status: '1' } })).toMatchObject({ time: 0, like_count: 0, liked: null });
expect(normalizeQzoneComment({ has_more_reply: 1, like: { status: 2 } })).toMatchObject({ has_more_replies: null, liked: null });
});
test('accepts ID zero while never inventing a rounded numeric identity', () => {
for (const id of [0, '0']) {
const raw = { id };
expect(normalizeQzoneComment(raw).comment_id).toBe('0');
expect(normalizeQzoneReply(raw).reply_id).toBe('0');
expect(normalizeQzoneComment(raw).comment.id).toBe(id);
}
expect(normalizeQzoneReply({ id: '9007199254740993' }).reply_id).toBe('9007199254740993');
for (const id of [Number.MAX_SAFE_INTEGER + 1, -1, NaN, Infinity, 0.5, '', ' ']) {
expect(normalizeQzoneComment({ id }).comment_id).toBeNull();
expect(normalizeQzoneReply({ id }).reply_id).toBeNull();
}
});
test('preserves UID-only authors and separates author identity from reply target', () => {
const reply: QzoneComment = {
id: 0,
user: { uid: 'uid-only', nick: '' },
target_user: { uin: '9007199254740993', uid: 'target-uid', nick: '回复目标' },
content: [{ type: 0, content: '仅原文' }],
};
expect(normalizeQzoneReply(reply)).toMatchObject({
reply_id: '0',
user_id: null,
uid: 'uid-only',
nickname: '',
content: '仅原文',
target_user_id: '9007199254740993',
target_uid: 'target-uid',
target_nickname: '回复目标',
});
expect(normalizeQzoneComment({ user: { uin: '', uid: 'uid-only' } })).toMatchObject({ user_id: null, uid: 'uid-only' });
expect(normalizeQzoneReply({ user: { uin: '10001', uid: '' } })).toMatchObject({ user_id: '10001', uid: null, target_user_id: null });
expect(normalizeQzoneReply({ user: { uin: Number.MAX_SAFE_INTEGER + 1 } } as never).user_id).toBeNull();
});
test('does not infer reply totals or continuation from inline replies', () => {
const comment = { replys: [{ id: 'a' }, { id: 'b' }] };
expect(normalizeQzoneComment(comment)).toMatchObject({ reply_num: null, has_more_replies: null });
expect(normalizeQzoneComment(comment).replies).toHaveLength(2);
expect(normalizeQzoneComment({ replys: [] })).toMatchObject({ replies: [], reply_num: null, has_more_replies: null });
expect(normalizeQzoneComment({ reply_num: 20, has_more_reply: true })).toMatchObject({ replies: [], reply_num: 20, has_more_replies: true });
});
test('retains unknown reply media while projecting only known images', () => {
const video = { type: 1, video: { url: 'https://example.com/video', cover: { default_url: { url: 'https://example.com/cover' } } } };
const unknown = { type: 99, vendor_media: { raw: true } };
const reply = { media_items: [video, unknown], unknown_reply_field: { keep: true } };
const result = normalizeQzoneReply(reply);
expect(result.images).toBeNull();
expect(result.reply).toBe(reply);
expect(result.reply['media_items']).toEqual([video, unknown]);
expect(normalizeQzoneReply({ media_items: [video] }).images).toEqual([]);
expect(normalizeQzoneReply({ media_items: [] }).images).toEqual([]);
});
test('preserves unsupported text segments and invalid numbers as unknown projections', () => {
const reply = { content: [{ type: 99, content: 'future segment' }], time: 'unknown', like: { count: -1, status: true } };
expect(normalizeQzoneReply(reply)).toMatchObject({ content: null, time: null, like_count: null, liked: null });
expect(normalizeQzoneReply(reply).reply).toBe(reply);
expect(normalizeQzoneComment({ reply_num: '9007199254740993' }).reply_num).toBeNull();
});
test('does not silently drop malformed inline reply entries', () => {
expect(() => normalizeQzoneComment({ replys: [null] } as never)).toThrow('内联回复');
expect(() => normalizeQzoneComment({ replys: 'bad-shape' } as never)).toThrow('内联回复');
expect(() => normalizeQzoneReply(null as never)).toThrow('回复数据');
expect(() => normalizeQzoneComment(null as never)).toThrow('评论数据');
});
test('shares rich text and image projections with feed normalization without changing feed behavior', () => {
const content = [{ type: 0, content: 'same ' }, { type: 1, name: 'Qiao' }];
const media = [{ type: 0, image: { default_url: { url: '//example.com/image' } } }];
const feed = normalizeQzoneFeed({ cell_summary: { summary: content }, cell_media: { media_items: media } });
const comment = normalizeQzoneComment({ content, media_items: media });
expect(normalizeQzoneRichContent(content)).toBe(feed.content);
expect(normalizeQzoneMediaImages(media)).toEqual(feed.images);
expect(comment.content).toBe(feed.content);
expect(comment.images).toEqual(feed.images);
});
});
@@ -0,0 +1,176 @@
// StreamBasic must be evaluated before OneBotAction because of their circular import.
import '../napcat-onebot/action/stream/StreamBasic';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import * as fileUtils from '@/napcat-common/src/file';
import { SendQzoneMsg } from '@/napcat-onebot/action/extends/SendQzoneMsg';
import { DeleteQzoneMsg } from '@/napcat-onebot/action/extends/DeleteQzoneMsg';
const tempDirs: string[] = [];
function createCore () {
const directory = mkdtempSync(join(tmpdir(), 'napcat-qzone-compat-'));
tempDirs.push(directory);
return {
NapCatTempPath: directory,
selfInfo: { uin: '10001', uid: 'u_current' },
apis: {
QzoneApi: { publishMsg: vi.fn().mockResolvedValue({ tid: 'modern-tid' }) },
WebApi: {
uploadImageToQzone: vi.fn().mockResolvedValue('legacy-richval'),
publishQzoneMsg: vi.fn().mockResolvedValue({ tid: 'legacy-tid' }),
deleteQzoneMsg: vi.fn().mockResolvedValue(undefined),
},
},
};
}
afterEach(() => {
for (const directory of tempDirs.splice(0)) {
rmSync(directory, { recursive: true, force: true });
}
});
describe('Qzone existing action compatibility', () => {
it('keeps send_qzone_msg parameters and tid response for pure text', async () => {
const core = createCore();
const action = new SendQzoneMsg(undefined as never, core as never);
await expect(action._handle({ content: '朋友可见', ugc_right: '16', target_uins: ['10002'] }))
.resolves.toEqual({ tid: 'modern-tid', time: 0 });
expect(core.apis.QzoneApi.publishMsg).toHaveBeenCalledExactlyOnceWith('朋友可见', 16, ['10002']);
expect(core.apis.WebApi.publishQzoneMsg).not.toHaveBeenCalled();
});
it('does not retry an uncertain modern publish through the legacy CGI', async () => {
const core = createCore();
core.apis.QzoneApi.publishMsg.mockRejectedValue(new Error('发表结果未知,请查询后确认'));
const action = new SendQzoneMsg(undefined as never, core as never);
await expect(action._handle({ content: '仅发送一次', images: [] })).rejects.toThrow('结果未知');
expect(core.apis.QzoneApi.publishMsg).toHaveBeenCalledTimes(1);
expect(core.apis.WebApi.publishQzoneMsg).not.toHaveBeenCalled();
});
it('preserves decimal target identifiers without a lossy numeric conversion', async () => {
const core = createCore();
const action = new SendQzoneMsg(undefined as never, core as never);
await action._handle({ content: '指定好友', ugc_right: 16, target_uins: ['9007199254740993'] });
expect(core.apis.QzoneApi.publishMsg).toHaveBeenCalledExactlyOnceWith('指定好友', 16, ['9007199254740993']);
});
it.each([{ images: [] }, { images: ['base64://aGVsbG8='] }])('rejects an invalid exclusion list before any write ($images)', async ({ images }) => {
const core = createCore();
const action = new SendQzoneMsg(undefined as never, core as never);
await expect(action._handle({ content: '排除指定好友', ugc_right: 128, target_uins: ['10002', 'invalid'], images }))
.rejects.toThrow('target_uins');
expect(core.apis.QzoneApi.publishMsg).not.toHaveBeenCalled();
expect(core.apis.WebApi.uploadImageToQzone).not.toHaveBeenCalled();
expect(core.apis.WebApi.publishQzoneMsg).not.toHaveBeenCalled();
});
it('keeps legacy image publishing and cleans decoded images without deleting user files', async () => {
const core = createCore();
const localImage = join(core.NapCatTempPath, 'user-image.png');
writeFileSync(localImage, 'user image');
const action = new SendQzoneMsg(undefined as never, core as never);
await expect(action._handle({
content: '带图说说',
images: ['base64://aGVsbG8=', pathToFileURL(localImage).href],
ugc_right: 64,
})).resolves.toEqual({ tid: 'legacy-tid', time: 0 });
expect(core.apis.QzoneApi.publishMsg).not.toHaveBeenCalled();
expect(core.apis.WebApi.uploadImageToQzone.mock.calls.map(args => args[0])).toEqual([
Buffer.from('hello').toString('base64'),
Buffer.from('user image').toString('base64'),
]);
expect(core.apis.WebApi.publishQzoneMsg).toHaveBeenCalledExactlyOnceWith(
'带图说说', ['legacy-richval', 'legacy-richval'], 64, undefined
);
expect(readdirSync(core.NapCatTempPath)).toEqual(['user-image.png']);
expect(readFileSync(localImage, 'utf8')).toBe('user image');
});
it('cleans temporary images and does not publish after an upload failure', async () => {
const core = createCore();
core.apis.WebApi.uploadImageToQzone.mockRejectedValue(new Error('upload failed'));
const action = new SendQzoneMsg(undefined as never, core as never);
await expect(action._handle({ content: '带图', images: ['base64://aGVsbG8='] })).rejects.toThrow('upload failed');
expect(core.apis.WebApi.publishQzoneMsg).not.toHaveBeenCalled();
expect(core.apis.QzoneApi.publishMsg).not.toHaveBeenCalled();
expect(readdirSync(core.NapCatTempPath)).toEqual([]);
});
it('stops before upload and cleans decoded images if the account changes during image decoding', async () => {
for (const change of [{ uin: '10002' }, { uid: 'u_other' }]) {
const core = createCore();
const decode = fileUtils.uriToLocalFile;
const decoder = vi.spyOn(fileUtils, 'uriToLocalFile').mockImplementationOnce(async (...args) => {
const result = await decode(...args);
Object.assign(core.selfInfo, change);
return result;
});
try {
await expect(new SendQzoneMsg(undefined as never, core as never)._handle({
content: '带图', images: ['base64://aGVsbG8='],
})).rejects.toThrow('QQ账号已切换');
expect(core.apis.WebApi.uploadImageToQzone).not.toHaveBeenCalled();
expect(core.apis.WebApi.publishQzoneMsg).not.toHaveBeenCalled();
expect(core.apis.QzoneApi.publishMsg).not.toHaveBeenCalled();
expect(readdirSync(core.NapCatTempPath)).toEqual([]);
} finally {
decoder.mockRestore();
}
}
});
it('stops the upload chain without publishing to a changed account and preserves user images', async () => {
for (const change of [{ uin: '10002' }, { uid: 'u_other' }]) {
const core = createCore();
const localImage = join(core.NapCatTempPath, 'user-image.png');
writeFileSync(localImage, 'user image');
core.apis.WebApi.uploadImageToQzone.mockImplementationOnce(async () => {
Object.assign(core.selfInfo, change);
return 'legacy-richval';
});
await expect(new SendQzoneMsg(undefined as never, core as never)._handle({
content: '带图', images: ['base64://aGVsbG8=', pathToFileURL(localImage).href],
})).rejects.toThrow('QQ账号已切换');
expect(core.apis.WebApi.uploadImageToQzone).toHaveBeenCalledTimes(1);
expect(core.apis.WebApi.publishQzoneMsg).not.toHaveBeenCalled();
expect(core.apis.QzoneApi.publishMsg).not.toHaveBeenCalled();
expect(readdirSync(core.NapCatTempPath)).toEqual(['user-image.png']);
expect(readFileSync(localImage, 'utf8')).toBe('user image');
}
});
it('validates existing selective visibility before uploading or publishing', async () => {
const core = createCore();
const action = new SendQzoneMsg(undefined as never, core as never);
await expect(action._handle({ content: '指定好友', ugc_right: 128, images: ['base64://aGVsbG8='] }))
.rejects.toThrow('target_uins 不能为空');
expect(core.apis.QzoneApi.publishMsg).not.toHaveBeenCalled();
expect(core.apis.WebApi.uploadImageToQzone).not.toHaveBeenCalled();
});
it('keeps delete_qzone_msg on its existing tid-based CGI path', async () => {
const core = createCore();
const action = new DeleteQzoneMsg(undefined as never, core as never);
await expect(action._handle({ tid: 'existing-tid' })).resolves.toBeNull();
expect(core.apis.WebApi.deleteQzoneMsg).toHaveBeenCalledExactlyOnceWith('existing-tid');
});
});
@@ -0,0 +1,147 @@
import { describe, expect, test } from 'vitest';
import { parseQzoneWebResponse } from '@/napcat-core/data/qzone-web';
const DOMAIN = 'document.domain="h5.qzone.qq.com";';
const ASSIGN_CALLBACK = 'cb=frameElement.callback;';
const TRY_SETUP = `var cb;try{${DOMAIN}${ASSIGN_CALLBACK}}catch(e){try{${DOMAIN}${ASSIGN_CALLBACK}}catch(e){${DOMAIN}${ASSIGN_CALLBACK}}}`;
function html (script: string, doctype = true): string {
return `${doctype ? '<!DOCTYPE html>\n' : ''}<html>\n<head>\n<meta http-equiv="content-type" content="text/html; charset=utf-8" />\n</head>\n<body>\n<script type="text/javascript">\n${script}\n</script>\n</body>\n</html>`;
}
function callback (value: unknown): string {
return `frameElement.callback(${JSON.stringify(value)});`;
}
describe('QQ空间 inert FormSender envelopes', () => {
test.each([
{ code: 0, subcode: 0, data: '' },
{ code: 0, subcode: 0, data: { name: 'Ack' } },
{ code: 0, subcode: 0, data: { id: 0, content: 'synthetic reply', postTime: 1700000000 }, err: { code: 0 } },
])('accepts the observed three-domain try/catch wrapper with a synthetic response (%j)', (response) => {
for (const doctype of [true, false]) {
expect(parseQzoneWebResponse(html(`${TRY_SETUP}\n${callback(response)}`, doctype), true)).toEqual(response);
}
});
test('accepts the upload domain preamble and explicit ret=0 without inventing code=0', () => {
const response = { ret: 0, data: { url: 'https://images.example.test/upload.png', width: 20, height: 10 } };
const body = html(`${DOMAIN}${callback(response)}`, false);
expect(parseQzoneWebResponse(body)).toEqual(response);
expect(() => parseQzoneWebResponse(body, true)).toThrow('成功状态');
});
test('supports formatting and tag case without accepting extra attributes or syntax', () => {
const setup = 'var cb ; try { document.domain = "h5.qzone.qq.com" ; cb = frameElement.callback ; } catch (e) { try { document.domain="h5.qzone.qq.com"; cb=frameElement.callback; } catch(e) { document.domain="h5.qzone.qq.com"; cb=frameElement.callback; } }';
const body = html(`${setup}\n frameElement.callback ( { "code": 0 } ) ;`)
.replace('<html>', '<HTML>')
.replace('http-equiv="content-type"', 'http-equiv="Content-Type"')
.replace('charset=utf-8', 'charset=UTF-8')
.replace(' />', '/>');
expect(parseQzoneWebResponse(body, true)).toEqual({ code: 0 });
});
test('treats callback-looking content as data and preserves existing Ack normalization', () => {
const response = { code: 0, data: { content: 'var cb; document.domain="other.test"; callback({"code":-1});', braces: '{}[]()' } };
expect(parseQzoneWebResponse(html(`${TRY_SETUP}${callback(response)}`))).toEqual(response);
expect(parseQzoneWebResponse(html(`${DOMAIN}frameElement.callback({"ret":0,"data":{name:"Ack"}});`)))
.toEqual({ ret: 0, data: { name: 'Ack' } });
});
test.each(['Example Space', '', '合成空间名称', 'quote " and slash \\', 'line one\nline two', '}; callback({"code":-1});'])('accepts the observed bare name string key without changing its value (%j)', (name) => {
const payload = `{"code":0,"subcode":0,"message":"","default":0,"data":{name:${JSON.stringify(name)}}}`;
const body = html(`${TRY_SETUP}frameElement.callback(${payload});`);
expect(parseQzoneWebResponse(body, true)).toEqual({ code: 0, subcode: 0, message: '', default: 0, data: { name } });
});
test('normalizes only object keys and preserves name-looking text inside JSON strings', () => {
const content = '{name:"Example"}, name:"Ack", escaped quote \\"';
const payload = `{"code":0,"data":{"content":${JSON.stringify(content)},name:"Example","nested":[{name:"Nested"}]}}`;
expect(parseQzoneWebResponse(html(`${DOMAIN}frameElement.callback(${payload});`)))
.toEqual({ code: 0, data: { content, name: 'Example', nested: [{ name: 'Nested' }] } });
});
test.each([
'{"code":0,"data":{name:1}}',
'{"code":0,"data":{name:null}}',
'{"code":0,"data":{name:false}}',
'{"code":0,"data":{name:["Example"]}}',
'{"code":0,"data":{name:{"value":"Example"}}}',
'{"code":0,"data":{name:someName}}',
'{"code":0,"data":{name:"Example"+"suffix"}}',
'{"code":0,"data":{name:("Example")}}',
'{"code":0,"data":{name:\'Example\'}}',
'{"code":0,"data":{other:"Example"}}',
'{"code":0,"data":{namex:"Example"}}',
'{"code":0,"data":[name:"Example"]}',
'{"code":0,"data":{name:"Example",other:"value"}}',
'{"code":-1,"\\u0063ode":0,"data":{name:"Example"}}',
'{"code":0,"subcode":-1,"data":{name:"Example"}}',
])('does not extend bare-name compatibility to other syntax or failed statuses (%s)', (payload) => {
expect(() => parseQzoneWebResponse(html(`${TRY_SETUP}frameElement.callback(${payload});`))).toThrow();
});
test.each([
html(`${TRY_SETUP}${callback({ code: 0 })}`).replace('<body>', '<body onload="alert(1)">'),
html(`${TRY_SETUP}${callback({ code: 0 })}`).replace('<head>', '<head><script>alert(1)</script>'),
html(`${TRY_SETUP}${callback({ code: 0 })}`).replace('</body>', '<img src="x" onerror="alert(1)"></body>'),
html(`${TRY_SETUP}${callback({ code: 0 })}`).replace('type="text/javascript"', 'type="text/javascript" src="https://example.test/x.js"'),
html(`${TRY_SETUP}${callback({ code: 0 })}`).replace('type="text/javascript"', 'type="text/javascript" onload="alert(1)"'),
html(`${TRY_SETUP}${callback({ code: 0 })}`).replace('</script>', '</script><script>callback({"code":0});</script>'),
html(`${TRY_SETUP}${callback({ code: 0 })}`).replace('charset=utf-8', 'charset=gbk'),
html(`alert(1);${TRY_SETUP}${callback({ code: 0 })}`),
html(`${TRY_SETUP}alert(1);${callback({ code: 0 })}`),
html(`${TRY_SETUP}${callback({ code: 0 })}alert(1);`),
html(`${TRY_SETUP}${callback({ code: 0 })}${callback({ code: 0 })}`),
html(`${TRY_SETUP}${callback({ code: 0 })}`).replace('"h5.qzone.qq.com"', '"other.example.test"'),
html(`${DOMAIN}document.domain="other.example.test";${callback({ code: 0 })}`),
html(`${TRY_SETUP}_Callback({"code":0});`),
html(`${TRY_SETUP}cb({"code":0});`),
html(callback({ code: 0 })),
html(`${DOMAIN}frameElement.callback((function(){return {"code":0};})());`),
html(`${DOMAIN}frameElement.callback({"code":(0,1)});`),
'<html><body>login required</body></html>',
])('rejects unobserved HTML, setup and executable additions', (body) => {
expect(() => parseQzoneWebResponse(body)).toThrow();
});
test.each([
'{"code":0,"subcode":-1}',
'{"code":0,"ret":-1}',
'{"ret":0,"code":-1}',
'{"ret":"0"}',
'{"code":-1,"code":0}',
'{"code":-1,"\\u0063ode":0}',
'{"ret":-1,"ret":0}',
'{"code":0,"data":{}};alert(1);frameElement.callback({"code":0}',
'{"message":"success without numeric acknowledgement"}',
])('retains strict success and duplicate-code checks inside HTML (%s)', (payload) => {
expect(() => parseQzoneWebResponse(html(`${TRY_SETUP}frameElement.callback(${payload});`))).toThrow();
});
test('never exposes callback contents when an HTML response cannot be parsed', () => {
let error: unknown;
try {
parseQzoneWebResponse(html(`${DOMAIN}frameElement.callback({"code":0,"private":"synthetic-private",broken});`));
} catch (value) {
error = value;
}
expect(error).toBeInstanceOf(Error);
expect((error as Error).message).toBe('QQ空间响应JSON格式异常');
expect((error as Error).message).not.toContain('synthetic-private');
});
test.each([
'{"code":0}',
'frameElement.callback({"code":0});',
'_Callback({"code":0});',
'<script>frameElement.callback({"code":0});</script>',
'frameElement.callback({"code":0});</script>',
])('preserves the original accepted response envelopes (%s)', (body) => {
expect(parseQzoneWebResponse(body, true)).toEqual({ code: 0 });
});
});
@@ -0,0 +1,202 @@
// StreamBasic must be evaluated before OneBotAction because of their circular import.
import '../napcat-onebot/action/stream/StreamBasic';
import { describe, expect, it, vi } from 'vitest';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import { GetQzoneProfile } from '@/napcat-onebot/action/extends/qzone/GetQzoneProfile';
import { SetQzoneProfile } from '@/napcat-onebot/action/extends/qzone/SetQzoneProfile';
import { SetQzoneMsgRight } from '@/napcat-onebot/action/extends/qzone/SetQzoneMsgRight';
import { SetQzoneBan } from '@/napcat-onebot/action/extends/qzone/SetQzoneBan';
function createCore () {
const QzoneApi = {
getProfile: vi.fn().mockResolvedValue({ name: '', description: '' }),
setProfile: vi.fn().mockResolvedValue(undefined),
setMsgRight: vi.fn().mockImplementation(async (_tid: string, right: number) => ({ ugc_right: right })),
setBan: vi.fn().mockResolvedValue(undefined),
};
return { apis: { QzoneApi }, context: { logger: { logError: vi.fn() } } };
}
describe('QQ空间资料和权限 actions', () => {
it('reads the current profile by default and preserves large decimal target strings', async () => {
const core = createCore();
const action = new GetQzoneProfile(undefined as never, core as never);
const result = await action.handle({}, 'test', {} as never);
await action.handle({ target_uin: 10002 }, 'test', {} as never);
await action.handle({ target_uin: '9007199254740993' }, 'test', {} as never);
expect(result).toMatchObject({ status: 'ok', data: { name: '', description: '' } });
expect(core.apis.QzoneApi.getProfile.mock.calls).toEqual([
[undefined], ['10002'], ['9007199254740993'],
]);
});
it('distinguishes omitted profile fields from explicit empty strings through handle parsing', async () => {
const core = createCore();
const action = new SetQzoneProfile(undefined as never, core as never);
const result = await action.handle({ name: '' }, 'test', {} as never);
await action.handle({ description: '' }, 'test', {} as never);
await action.handle({ name: undefined, description: '说明' }, 'test', {} as never);
expect(JSON.parse(JSON.stringify(result))).toMatchObject({ status: 'ok', retcode: 0, data: null });
expect(core.apis.QzoneApi.setProfile.mock.calls).toEqual([
[{ name: '' }], [{ description: '' }], [{ description: '说明' }],
]);
expect(Object.keys(core.apis.QzoneApi.setProfile.mock.calls[0]?.[0] ?? {})).toEqual(['name']);
});
it('normalizes supported profile scalars to strings without trimming content', async () => {
const core = createCore();
const action = new SetQzoneProfile(undefined as never, core as never);
await action.handle({ name: 0, description: false }, 'test', {} as never);
await action.handle({ name: true, description: ' 保留空白\r\n ' }, 'test', {} as never);
expect(core.apis.QzoneApi.setProfile.mock.calls).toEqual([
[{ name: '0', description: 'false' }],
[{ name: 'true', description: ' 保留空白\r\n ' }],
]);
});
it('normalizes right codes and target IDs before a single own-post permission request', async () => {
const core = createCore();
const action = new SetQzoneMsgRight(undefined as never, core as never);
const result = await action.handle({
tid: 'existing-tid',
ugc_right: '16',
target_uins: [10002, '9007199254740993', '10002'],
}, 'test', {} as never);
expect(core.apis.QzoneApi.setMsgRight).toHaveBeenCalledExactlyOnceWith(
'existing-tid', 16, ['10002', '9007199254740993']
);
expect(result).toMatchObject({ status: 'ok', data: { ugc_right: 16 } });
});
it('keeps enable false and serializes successful ban writes with explicit null data', async () => {
const core = createCore();
const action = new SetQzoneBan(undefined as never, core as never);
const disabled = await action.handle({ user_id: '9007199254740993', enable: false }, 'test', {} as never);
const enabled = await action.handle({ user_id: 10002 }, 'test', {} as never);
expect(core.apis.QzoneApi.setBan.mock.calls).toEqual([
['9007199254740993', false], ['10002', true],
]);
expect(JSON.parse(JSON.stringify(disabled))).toMatchObject({ status: 'ok', data: null });
expect(JSON.parse(JSON.stringify(enabled))).toMatchObject({ status: 'ok', data: null });
});
it('normalizes safe numeric permission-update IDs without accepting lossy values', async () => {
const core = createCore();
const result = await new SetQzoneMsgRight(undefined as never, core as never).handle({ tid: 0, ugc_right: '4' }, 'test', {} as never);
expect(result).toMatchObject({ status: 'ok', data: { ugc_right: 4 } });
expect(core.apis.QzoneApi.setMsgRight).toHaveBeenCalledExactlyOnceWith('0', 4, []);
});
it('normalizes supported SnowLuma boolean spellings without treating arbitrary text as true', async () => {
const core = createCore();
const action = new SetQzoneBan(undefined as never, core as never);
for (const enable of ['false', '0', ' NO ', 'Off', 0]) {
const result = await action.handle({ user_id: '10002', enable }, 'test', {} as never);
expect(result.status).toBe('ok');
expect(core.apis.QzoneApi.setBan).toHaveBeenLastCalledWith('10002', false);
}
for (const enable of ['true', '1', ' YES ', 'On', 1]) {
const result = await action.handle({ user_id: '10002', enable }, 'test', {} as never);
expect(result.status).toBe('ok');
expect(core.apis.QzoneApi.setBan).toHaveBeenLastCalledWith('10002', true);
}
});
it('rejects malformed or lossy values before any core call', async () => {
const cases = [
[GetQzoneProfile, { target_uin: Number.MAX_SAFE_INTEGER + 1 }],
[GetQzoneProfile, { target_uin: false }],
[GetQzoneProfile, { target_uin: 'bad-uin' }],
[SetQzoneProfile, {}],
[SetQzoneProfile, { name: undefined }],
[SetQzoneProfile, { name: null }],
[SetQzoneProfile, { name: ['text'] }],
[SetQzoneProfile, { description: { content: 'text' } }],
[SetQzoneProfile, { name: Infinity }],
[SetQzoneProfile, { name: NaN }],
[SetQzoneProfile, { name: 'x'.repeat(8193) }],
[SetQzoneMsgRight, { tid: 'tid', ugc_right: 2 }],
[SetQzoneMsgRight, { tid: '', ugc_right: 1 }],
[SetQzoneMsgRight, { tid: ' ', ugc_right: 1 }],
[SetQzoneMsgRight, { tid: true, ugc_right: 1 }],
[SetQzoneMsgRight, { tid: Number.MAX_SAFE_INTEGER + 1, ugc_right: 1 }],
[SetQzoneMsgRight, { tid: Infinity, ugc_right: 1 }],
[SetQzoneMsgRight, { tid: 'tid', ugc_right: true }],
[SetQzoneMsgRight, { tid: 'tid', ugc_right: 16 }],
[SetQzoneMsgRight, { tid: 'tid', ugc_right: 128, target_uins: [] }],
[SetQzoneMsgRight, { tid: 'tid', ugc_right: 16, target_uins: [Number.MAX_SAFE_INTEGER + 1] }],
[SetQzoneMsgRight, { tid: 'tid', ugc_right: 16, target_uins: ['10002', false] }],
[SetQzoneMsgRight, { tid: 'tid', ugc_right: 16, target_uins: '10002' }],
[SetQzoneBan, { user_id: 0 }],
[SetQzoneBan, { user_id: Number.MAX_SAFE_INTEGER + 1 }],
[SetQzoneBan, { user_id: '10002', enable: 'unknown' }],
[SetQzoneBan, { user_id: '10002', enable: 2 }],
[SetQzoneBan, { user_id: '10002', enable: null }],
] as const;
for (const [Action, payload] of cases) {
const core = createCore();
const result = await new Action(undefined as never, core as never).handle(payload as never, 'test', {} as never);
expect(result.status).toBe('failed');
for (const method of Object.values(core.apis.QzoneApi)) expect(method).not.toHaveBeenCalled();
}
});
it('rejects unknown parameters and current-account overrides before any core call', async () => {
const cases = [
[GetQzoneProfile, { target_uin: '10002', unknown: true }],
[SetQzoneProfile, { name: 'text', target_uin: '10002' }],
[SetQzoneMsgRight, { tid: 'tid', ugc_right: 1, target_uin: '10002' }],
[SetQzoneBan, { user_id: '10002', unknown: true }],
] as const;
for (const [Action, payload] of cases) {
const core = createCore();
const result = await new Action(undefined as never, core as never).handle(payload as never, 'test', {} as never);
expect(result.status).toBe('failed');
for (const method of Object.values(core.apis.QzoneApi)) expect(method).not.toHaveBeenCalled();
}
});
it('surfaces a failed write without retrying or claiming null success', async () => {
const core = createCore();
core.apis.QzoneApi.setProfile.mockRejectedValue(new Error('QQ空间未明确确认资料修改成功'));
const result = await new SetQzoneProfile(undefined as never, core as never).handle({ name: 'text' }, 'test', {} as never);
expect(result.status).toBe('failed');
expect(result.message).toContain('未明确确认');
expect(core.apis.QzoneApi.setProfile).toHaveBeenCalledTimes(1);
});
it('has complete API metadata and schema-valid examples for all four actions', () => {
const core = createCore();
const actions = [
new GetQzoneProfile(undefined as never, core as never),
new SetQzoneProfile(undefined as never, core as never),
new SetQzoneMsgRight(undefined as never, core as never),
new SetQzoneBan(undefined as never, core as never),
];
expect(actions.map(action => action.actionName)).toEqual([
'get_qzone_profile', 'set_qzone_profile', 'set_qzone_msg_right', 'set_qzone_ban',
]);
for (const action of actions) {
expect(action.actionSummary.length).toBeGreaterThan(0);
expect(action.actionDescription.length).toBeGreaterThan(0);
expect(action.actionTags).toContain('扩展接口');
expect(TypeCompiler.Compile(action.payloadSchema).Check(action.payloadExample)).toBe(true);
expect(TypeCompiler.Compile(action.returnSchema).Check(action.returnExample)).toBe(true);
}
});
});
@@ -0,0 +1,95 @@
// StreamBasic must be evaluated before OneBotAction because of their circular import.
import '../napcat-onebot/action/stream/StreamBasic';
import { describe, expect, it, vi } from 'vitest';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import { CommentQzone } from '@/napcat-onebot/action/extends/qzone/CommentQzone';
import { QzoneFeedReferenceExample, QzoneParentCommentSchema, QzoneUserSchema } from '@/napcat-onebot/action/extends/qzone/common';
import { normalizeQzoneCommentPayload } from '@/napcat-onebot/action/extends/qzone/common-snowluma';
import type { QzoneComment } from '@/napcat-core/data/qzone-rpc';
function createCore () {
return {
apis: {
QzoneApi: {
comment: vi.fn().mockResolvedValue({ comment_id: 'new-reply', comment: { id: 'new-reply' } }),
},
},
context: { logger: { logError: vi.fn() } },
};
}
function parentComment () {
return {
id: '0',
user: { uin: '10002', uid: null, nick: '作者', portrait: { type: 1, opaque: 'keep' } },
content: [{ type: 0, content: '原评论', extra: { keep: true } }],
replys: [{ id: 'inline-reply', user: { uid: null }, opaque_reply: [false, 0] }],
like: { id: 'raw-like-key', status: 0, count: 1 },
opaque_parent: { keep: ['9007199254740993', null] },
} satisfies QzoneComment;
}
describe('Qzone native parent with nullable raw UID', () => {
it('retains null UID and complete raw parent fields through the real handle parser', async () => {
const core = createCore();
const parent = parentComment();
const snapshot = structuredClone(parent);
const payload = { feed_ref: QzoneFeedReferenceExample, content: '回复', comment: parent };
const expectedPayload = structuredClone(payload);
const normalized = normalizeQzoneCommentPayload(payload);
expect(normalized.format).toBe('native');
if (normalized.format === 'native') expect(normalized.comment).toBe(parent);
const result = await new CommentQzone(undefined as never, core as never).handle(payload, 'test', {} as never);
expect(result).toMatchObject({ status: 'ok', data: { comment_id: 'new-reply' } });
expect(core.apis.QzoneApi.comment).toHaveBeenCalledExactlyOnceWith(QzoneFeedReferenceExample, '回复', snapshot, undefined);
expect(core.apis.QzoneApi.comment.mock.calls[0]?.[2]).toHaveProperty('user.uid', null);
expect(parent).toEqual(snapshot);
expect(parent.user.uid).toBeNull();
expect(payload).toEqual(expectedPayload);
});
it('keeps a nullable raw parent separate from an explicit reply target', async () => {
const core = createCore();
const parent = parentComment();
const snapshot = structuredClone(parent);
const target = { uin: '10003', uid: 'u_target', nick: '接收者', extra: { keep: true } };
const expectedTarget = structuredClone(target);
const result = await new CommentQzone(undefined as never, core as never).handle({
feed_ref: QzoneFeedReferenceExample, content: '指定回复', comment: parent, reply_user: target,
}, 'test', {} as never);
expect(result.status).toBe('ok');
expect(core.apis.QzoneApi.comment).toHaveBeenCalledExactlyOnceWith(QzoneFeedReferenceExample, '指定回复', snapshot, expectedTarget);
expect(parent).toEqual(snapshot);
expect(target).toEqual(expectedTarget);
});
it('allows null only in raw parent UID without relaxing parent identity or explicit target validation', async () => {
const parentSchema = TypeCompiler.Compile(QzoneParentCommentSchema);
const userSchema = TypeCompiler.Compile(QzoneUserSchema);
expect(parentSchema.Check(parentComment())).toBe(true);
expect(userSchema.Check({ uin: '10002', uid: null })).toBe(false);
const invalidParents = [
{ id: '0', user: { uin: '10002', uid: false } },
{ id: '0', user: { uin: '10002', uid: 0 } },
{ id: '0', user: { uin: '10002', uid: {} } },
{ id: 0, user: { uin: '10002', uid: null } },
{ id: '0', user: { uid: null } },
{ id: '0', user: { uin: Number.MAX_SAFE_INTEGER + 1, uid: null } },
];
const core = createCore();
const action = new CommentQzone(undefined as never, core as never);
for (const comment of invalidParents) {
const result = await action.handle({ feed_ref: QzoneFeedReferenceExample, content: '回复', comment } as never, 'test', {} as never);
expect(result.status).toBe('failed');
}
const invalidTarget = await action.handle({
feed_ref: QzoneFeedReferenceExample, content: '回复', comment: parentComment(), reply_user: { uin: '10003', uid: null },
} as never, 'test', {} as never);
expect(invalidTarget.status).toBe('failed');
expect(core.apis.QzoneApi.comment).not.toHaveBeenCalled();
});
});
+357
View File
@@ -0,0 +1,357 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { NTQQQzoneApi } from '@/napcat-core/apis/qzone';
import type { QzoneComment, QzoneFeed, QzoneFeedReference } from '@/napcat-core/data/qzone-rpc';
const unionId = { uf_key: 'union-key', ugc_id: 'ugc-key', feed_id: 'feed-key', serialized_data: 'opaque', ext_ids: [{ ext_id_type: 5, str: 'mood-tid' }] };
const feed: QzoneFeed = {
cell_common: { union_id: unionId, feed_type: 1, feed_sub_type: 1, cur_like_key: 'like-key', domain_type: 1 },
cell_summary: { summary: [{ type: 0, content: '正文' }] },
cell_user_info: { user: { uin: '10001', uid: 'self-uid', nick: '当前账号' } },
cell_feed_transfer: { opaque: 'context' },
};
const reference: QzoneFeedReference = {
union_id: unionId, cell_feed_transfer: { opaque: 'context' }, feed_action_domain_type: 1, like_key: 'like-key',
};
function response (data: Record<string, unknown>, retcode = 0): Response {
return new Response(JSON.stringify({ retcode, data }), { status: 200 });
}
function createApi () {
const core = {
selfInfo: { uin: '10001', uid: 'self-uid', nick: '当前账号' },
apis: {
UserApi: {
getSKey: vi.fn().mockResolvedValue('s'),
getPSkey: vi.fn().mockResolvedValue({ result: 0, domainPskeyMap: new Map([['qzone.qq.com', 'p']]) }),
getUidByUinV2: vi.fn().mockResolvedValue('target-uid'),
},
},
};
return { api: new NTQQQzoneApi({} as never, core as never), core };
}
describe('Qzone modern HTTP2RPC API', () => {
let fetchMock: ReturnType<typeof vi.fn<typeof fetch>>;
beforeEach(() => {
fetchMock = vi.fn<typeof fetch>();
vi.stubGlobal('fetch', fetchMock);
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it('uses the fixed JSON RPC route, PSKey-first gtk and only current account cookies', async () => {
const { api, core } = createApi();
fetchMock.mockResolvedValueOnce(response({ feeds: [{ feed }], has_more: false }));
const result = await api.getFriendFeeds();
expect(result.feeds).toHaveLength(1);
expect(result.feeds[0]?.tid).toBe('mood-tid');
expect(result.feeds[0]?.feed).toEqual(feed);
expect(result.next_cursor).toBeNull();
expect(core.apis.UserApi.getPSkey).toHaveBeenCalledExactlyOnceWith(['qzone.qq.com']);
const [url, options] = fetchMock.mock.calls[0]!;
expect(String(url)).toBe('https://h5.qzone.qq.com/http2rpc/gotrpc/v1/trpc.qzone.feeds_reader.FeedsReader/GetFriendFeeds?g_tk=177685');
expect(options).toMatchObject({ method: 'POST', redirect: 'error', signal: expect.any(AbortSignal) });
expect(options?.headers).toMatchObject({
Cookie: 'uin=o10001; p_uin=o10001; skey=s; p_skey=p',
'Content-Type': 'application/json',
'x-oidb': '{"uint32_command":"0x97e5","uint32_service_type":"0"}',
'x-web-qua': 'V1_HT5_QZ_9.9.32_001_IDC_B',
});
expect(JSON.parse(options?.body as string)).toEqual({ refresh_id: expect.stringMatching(/^10001_\d+$/) });
});
it('falls back to SKey gtk and rejects missing auth without leaking ticket errors', async () => {
const { api, core } = createApi();
core.apis.UserApi.getPSkey.mockRejectedValueOnce(new Error('private ticket detail'));
fetchMock.mockResolvedValueOnce(response({ feeds: [], has_more: false }));
await api.getFriendFeeds();
expect(String(fetchMock.mock.calls[0]![0])).toContain('g_tk=177688');
core.apis.UserApi.getSKey.mockRejectedValueOnce(new Error('private skey detail'));
core.apis.UserApi.getPSkey.mockRejectedValueOnce(new Error('private pskey detail'));
await expect(api.getFriendFeeds()).rejects.toThrow('QQ空间取票失败');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('rejects invalid identity and account switches during ticket acquisition', async () => {
const { api, core } = createApi();
core.selfInfo.uin = '';
await expect(api.getFriendFeeds()).rejects.toThrow('需要已登录');
expect(core.apis.UserApi.getSKey).not.toHaveBeenCalled();
core.selfInfo.uin = '10001';
core.apis.UserApi.getPSkey.mockImplementationOnce(async () => {
core.selfInfo.uin = '20001';
core.selfInfo.uid = 'another-uid';
return { result: 0, domainPskeyMap: new Map([['qzone.qq.com', 'p']]) };
});
await expect(api.getFriendFeeds()).rejects.toThrow('QQ账号已切换');
expect(fetchMock).not.toHaveBeenCalled();
});
it('retains the refresh id, attach info and last non-ad full union identity across pages', async () => {
const { api } = createApi();
const ad: QzoneFeed = { cell_common: { feed_type: 3, union_id: { uf_key: 'ad-key' } } };
const unknown: QzoneFeed = { cell_common: { feed_type: 1, union_id: { uf_key: '' } }, new_cell: { opaque: true } };
const noIdentity: QzoneFeed = { cell_common: { feed_type: 1 }, new_cell: { opaque: 'also-preserved' } };
fetchMock.mockResolvedValueOnce(response({ feeds: [{ feed }, { feed: ad }, { feed: unknown }, { feed: noIdentity }], has_more: true, attach_info: 'page-2' }));
fetchMock.mockResolvedValueOnce(response({ feeds: [{ feed: unknown }], has_more: false }));
const first = await api.getFriendFeeds();
expect(first.feeds).toHaveLength(4);
expect(first.feeds[2]?.feed).toEqual(unknown);
expect(first.feeds[2]?.feed_ref).toBeNull();
expect(first.feeds[3]?.feed_ref).toBeNull();
expect(first.next_cursor).toEqual(expect.any(String));
const firstRequest = JSON.parse(fetchMock.mock.calls[0]![1]?.body as string);
// A caller mutating returned display data must not change the cached pagination identity.
first.feeds[0]!.feed.cell_common!.union_id!.uf_key = 'caller-mutated';
const last = await api.getFriendFeeds(first.next_cursor!);
expect(last.feeds[0]?.feed).toEqual(unknown);
expect(last.has_more).toBe(false);
expect(JSON.parse(fetchMock.mock.calls[1]![1]?.body as string)).toEqual({
refresh_id: firstRequest.refresh_id, attach_info: 'page-2', last_client_feed_union_id: unionId,
});
});
it('rejects cursors for a different query kind, target or account and after expiry', async () => {
const { api, core } = createApi();
const clock = vi.spyOn(Date, 'now').mockReturnValue(1000000);
fetchMock.mockImplementation(async () => response({ feeds: [{ feed }], has_more: true, attach_info: 'next' }));
const friend = await api.getFriendFeeds();
await expect(api.getMsgList(undefined, friend.next_cursor!)).rejects.toThrow('游标无效');
const moods = await api.getMsgList('20001');
await expect(api.getMsgList('30001', moods.next_cursor!)).rejects.toThrow('游标无效');
core.selfInfo.uin = '20001';
core.selfInfo.uid = 'other-uid';
await expect(api.getFriendFeeds(friend.next_cursor!)).rejects.toThrow('游标无效');
core.selfInfo.uin = '10001';
core.selfInfo.uid = 'self-uid';
clock.mockReturnValue(1000000 + 10 * 60 * 1000);
await expect(api.getFriendFeeds(friend.next_cursor!)).rejects.toThrow('已过期');
await expect(api.getFriendFeeds('x'.repeat(16385))).rejects.toThrow('游标无效');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('bounds saved cursors and evicts the oldest issued token', async () => {
const { api } = createApi();
fetchMock.mockImplementation(async () => response({ feeds: [{ feed }], has_more: true, attach_info: 'next' }));
const first = await api.getFriendFeeds();
for (let i = 0; i < 128; i++) await api.getFriendFeeds();
await expect(api.getFriendFeeds(first.next_cursor!)).rejects.toThrow('游标无效');
expect(fetchMock).toHaveBeenCalledTimes(129);
});
it('uses resolved UID for mood lists and returns explicit seal state without a fake total', async () => {
const { api, core } = createApi();
const seal = { type: 1, summary: '已封存', additional: 'preserved' };
fetchMock.mockResolvedValueOnce(response({ feeds: [], has_more: false, seal_off_memory: seal }));
const result = await api.getMsgList('20001');
expect(core.apis.UserApi.getUidByUinV2).toHaveBeenCalledExactlyOnceWith('20001');
expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string)).toEqual({
host_uid: 'target-uid', host_uin: '20001', attach_info: '', feed_action_domain_type: 1,
});
expect(result).toEqual({ msglist: [], has_more: false, next_cursor: null, seal_off_memory: seal });
expect(result).not.toHaveProperty('total');
});
it('rejects malformed pages, malformed continuation and unresolved target accounts', async () => {
const { api, core } = createApi();
fetchMock.mockResolvedValueOnce(response({ has_more: false }));
await expect(api.getFriendFeeds()).rejects.toThrow('列表响应格式异常');
fetchMock.mockResolvedValueOnce(response({ feeds: [{ feed }], has_more: true }));
await expect(api.getFriendFeeds()).rejects.toThrow('续页信息无效');
core.apis.UserApi.getUidByUinV2.mockResolvedValueOnce('');
await expect(api.getMsgList('20001')).rejects.toThrow('无法解析目标QQ号');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('reads the exact detail nesting and preserves raw comments and feed identity', async () => {
const { api } = createApi();
const parent: QzoneComment = { id: '0', user: { uin: '20001', uid: 'peer-uid' }, custom: { keep: true } };
const detailFeed = { ...feed, cell_comment: { comments: [parent] } };
fetchMock.mockResolvedValueOnce(response({ feed: { feed: detailFeed } }));
const detail = await api.getMsgDetail(reference);
expect(detail.comments).toEqual([parent]);
expect(detail.feed).toEqual(detailFeed);
expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string)).toEqual({
union_id: unionId, cell_feed_transfer: { opaque: 'context' }, feed_action_domain_type: 1, from_page: 1,
});
fetchMock.mockResolvedValueOnce(response({ feed: detailFeed }));
await expect(api.getMsgDetail(reference)).rejects.toThrow('未返回说说详情');
});
it('publishes with session author and mapped privacy, and accepts only a returned server tid', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ feed }));
await expect(api.publishMsg('正文', 16, ['20001'])).resolves.toEqual({ tid: 'mood-tid', time: 0 });
const request = JSON.parse(fetchMock.mock.calls[0]![1]?.body as string);
expect(request).toMatchObject({
from: 3,
feed: {
cell_user_info: { user: { uin: '10001', uid: 'self-uid', nick: '当前账号' } },
cell_summary: { summary: [{ type: 0, content: '正文' }] },
cell_permission: { right: { flag: [3], white_uins: ['20001'] } },
},
});
fetchMock.mockResolvedValueOnce(response({ feed: { cell_common: { client_key: 'local-key-only' } } }));
await expect(api.publishMsg('第二条')).rejects.toThrow('结果未知');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('returns publish time only from the server feed without substituting the current clock', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ feed: { ...feed, cell_common: { ...feed.cell_common, time: '1700000123' } } }));
await expect(api.publishMsg('带服务端时间')).resolves.toEqual({ tid: 'mood-tid', time: 1700000123 });
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('does not turn a malformed supplied publish time into a missing-time sentinel', async () => {
const { api } = createApi();
for (const time of [-1, 'bad', Number.MAX_SAFE_INTEGER + 1]) {
fetchMock.mockResolvedValueOnce(response({ feed: { ...feed, cell_common: { ...feed.cell_common, time } } }));
await expect(api.publishMsg('仅发表一次')).rejects.toThrow('勿自动重试');
}
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it('uses distinct official like/unlike routes and requires the business result', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ like: { status: 1 } }));
fetchMock.mockResolvedValueOnce(response({ like: { status: 0 } }));
await api.setLike(reference, true);
await api.setLike(reference, false);
expect(String(fetchMock.mock.calls[0]![0])).toContain('/DoLike?');
expect(String(fetchMock.mock.calls[1]![0])).toContain('/UnLike?');
expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string)).toEqual({
like_key: 'like-key', union_id: unionId, like_type: 1, cell_feed_transfer: { opaque: 'context' },
});
fetchMock.mockResolvedValueOnce(response({}));
await expect(api.setLike(reference, true)).rejects.toThrow('未返回点赞结果');
await expect(api.setLike({ union_id: unionId }, true)).rejects.toThrow('缺少QQ空间点赞标识');
fetchMock.mockResolvedValueOnce(response({ like: {} }));
await api.setLike({ ...reference, like_key: 'k'.repeat(8192) }, true);
expect(JSON.parse(fetchMock.mock.calls[3]![1]?.body as string).like_key).toHaveLength(8192);
expect(fetchMock).toHaveBeenCalledTimes(4);
});
it('passes the full parent comment for replies and never trusts it as the acting author', async () => {
const { api } = createApi();
const parent: QzoneComment = {
id: '0',
user: { uin: '20001', uid: 'peer-uid', nick: '父评论作者' },
like: { id: 'parent-like' },
additional: { opaque: true },
};
const reply = { id: 'reply-id', user: { uin: '10001' }, opaque: 'returned' };
fetchMock.mockResolvedValueOnce(response({ reply }));
await expect(api.comment(reference, '回复正文', parent, { uin: '30001', uid: 'reply-target' })).resolves.toEqual({ comment_id: 'reply-id', comment: reply });
expect(String(fetchMock.mock.calls[0]![0])).toContain('/AddReply?');
expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string)).toMatchObject({
union_id: unionId,
comment: parent,
reply: { user: { uin: '10001', uid: 'self-uid' }, target_user: { uin: '30001', uid: 'reply-target' }, content: [{ content: '回复正文', type: 0 }] },
});
await expect(api.comment(reference, '回复', undefined, { uin: '30001' })).rejects.toThrow('必须与父评论');
await expect(api.comment(reference, '回复', { id: '0' })).rejects.toThrow('用户信息无效');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('accepts an empty optional UID on a returned parent while retaining the session actor UID', async () => {
const { api } = createApi();
const parent: QzoneComment = { id: 'parent', user: { uin: '20001', uid: '', nick: '' }, opaque: 'retained' };
fetchMock.mockResolvedValueOnce(response({ reply: { id: 'empty-uid-reply' } }));
await expect(api.comment(reference, '回复', parent)).resolves.toEqual({ comment_id: 'empty-uid-reply', comment: { id: 'empty-uid-reply' } });
expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string)).toMatchObject({
comment: parent,
reply: { target_user: { uin: '20001', uid: '', nick: '' }, user: { uin: '10001', uid: 'self-uid' } },
});
});
it('requires a nonempty server comment id and does not replay ambiguous writes', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ comment: { id: '0', additional: true } }));
await expect(api.comment(reference, '评论')).resolves.toEqual({ comment_id: '0', comment: { id: '0', additional: true } });
expect(String(fetchMock.mock.calls[0]![0])).toContain('/AddComment?');
fetchMock.mockResolvedValueOnce(response({ comment: {} }));
await expect(api.comment(reference, '评论')).rejects.toThrow('结果未知');
fetchMock.mockRejectedValueOnce(new Error('transport contains private cookie'));
await expect(api.publishMsg('正文')).rejects.toThrow('未能确认结果');
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it('accepts bounded parent and returned comment IDs that pass the public schema', async () => {
const { api } = createApi();
const id = 'c'.repeat(8192);
const parent = { id, user: { uin: '20001', uid: '' } };
fetchMock.mockResolvedValueOnce(response({ reply: { id } }));
await expect(api.comment(reference, '回复', parent)).resolves.toMatchObject({ comment_id: id });
expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string).comment.id).toBe(id);
});
it('preserves a real parent null UID while omitting it only from the normalized reply target', async () => {
const { api } = createApi();
const parent = { id: '0', user: { uin: '20001', uid: null, nick: '作者', extra: 'keep' }, content: [{ type: 0, content: '原评论' }], unknown: { keep: true } };
const saved = structuredClone(parent);
fetchMock.mockResolvedValueOnce(response({ reply: { id: 'new-reply' } }));
await expect(api.comment(reference, '回复', parent)).resolves.toMatchObject({ comment_id: 'new-reply' });
const request = JSON.parse(fetchMock.mock.calls[0]![1]?.body as string);
expect(request.comment).toEqual(saved);
expect(request.reply.target_user).toEqual({ uin: '20001', nick: '作者', extra: 'keep' });
expect(parent).toEqual(saved);
});
it('rejects HTTP errors, redirects, malformed JSON and outer RPC errors without returning server secrets', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(new Response('private response', { status: 302, headers: { Location: 'https://other.example' } }));
await expect(api.getFriendFeeds()).rejects.toThrow('QQ空间请求失败');
fetchMock.mockResolvedValueOnce(new Response('private response', { status: 500 }));
await expect(api.getFriendFeeds()).rejects.toThrow('QQ空间请求失败');
fetchMock.mockResolvedValueOnce(new Response('not json but private', { status: 200 }));
await expect(api.getFriendFeeds()).rejects.toThrow('响应格式异常');
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ retcode: 4003, message: 'private credential text', data: {} })));
try {
await api.getFriendFeeds();
expect.fail('must reject business failure');
} catch (error) {
expect(String(error)).not.toContain('private');
expect(String(error)).toContain('4003');
}
expect(fetchMock).toHaveBeenCalledTimes(4);
});
it('aborts a hanging request at the finite timeout and never retries a publish', async () => {
vi.useFakeTimers();
const { api } = createApi();
fetchMock.mockImplementation((_url, options) => new Promise((_resolve, reject) => {
options?.signal?.addEventListener('abort', () => reject(new Error('aborted')));
}));
const pending = api.publishMsg('正文');
const assertion = expect(pending).rejects.toThrow('未能确认结果');
await vi.advanceTimersByTimeAsync(15000);
await assertion;
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('bounds auth waits and streamed response size', async () => {
vi.useFakeTimers();
const { api, core } = createApi();
core.apis.UserApi.getSKey.mockImplementationOnce(() => new Promise(() => {}));
const pending = api.getFriendFeeds();
const assertion = expect(pending).rejects.toThrow('取票超时');
await vi.advanceTimersByTimeAsync(15000);
await assertion;
expect(fetchMock).not.toHaveBeenCalled();
vi.useRealTimers();
fetchMock.mockResolvedValueOnce(new Response(new Uint8Array(8 * 1024 * 1024 + 1)));
await expect(api.getFriendFeeds()).rejects.toThrow('QQ空间请求失败');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
+162
View File
@@ -0,0 +1,162 @@
import { describe, expect, test } from 'vitest';
import {
buildQzonePublishRequest,
buildQzoneText,
getQzoneGtk,
getQzoneTid,
normalizeQzoneFeed,
parseQzoneRpcResponse,
QZONE_REFERENCE_MAX_BYTES,
validateQzoneFeedReference,
type QzoneFeed,
} from '@/napcat-core/data/qzone-rpc';
describe('Qzone RPC response and feed identity', () => {
test('accepts only a successful object data envelope and preserves raw fields', () => {
const data = { feeds: [], extra: { server_field: true } };
expect(parseQzoneRpcResponse({ retcode: 0, data })).toBe(data);
for (const input of [null, [], {}, { retcode: '0', data }, { retcode: 0 }, { retcode: 0, data: [] }]) {
expect(() => parseQzoneRpcResponse(input)).toThrow();
}
});
test('does not echo credential-shaped server errors', () => {
expect(() => parseQzoneRpcResponse({ retcode: 4003, message: 'p_skey=private-value', data: null }))
.toThrow('QQ空间请求失败 (retcode=4003)');
expect(() => parseQzoneRpcResponse({ retcode: 'p_skey=private-value' }))
.toThrow('QQ空间请求失败');
});
test('uses an explicit mood extension ahead of ugc_id and never labels an album ID as a tid', () => {
expect(getQzoneTid({ cell_common: { feed_sub_type: 1, union_id: { ugc_id: 'fallback', ext_ids: [{ ext_id_type: 5, str: 'mood-tid' }] } } }))
.toBe('mood-tid');
expect(getQzoneTid({ cell_common: { app_id: 311, union_id: { ugc_id: 'fallback' } } })).toBe('fallback');
expect(getQzoneTid({ cell_common: { feed_sub_type: 2, union_id: { ugc_id: 'album-id' } } })).toBeNull();
expect(getQzoneTid({ cell_common: { union_id: { uf_key: 'feed-key', ugc_id: 'unclassified' } } })).toBeNull();
});
test('preserves numeric extension strings and rejects already-rounded numbers', () => {
expect(getQzoneTid({ cell_common: { union_id: { ext_ids: [{ ext_id_type: 5, unsigned_numeric: '9007199254740993' }] } } })).toBe('9007199254740993');
expect(getQzoneTid({ cell_common: { union_id: { ext_ids: [{ ext_id_type: 5, numeric: 9007199254740992 }] } } })).toBeNull();
});
test('retains complete references without rebuilding identities from tid', () => {
const reference = {
union_id: { uf_key: 'feed-key', ugc_id: 'mood-id', serialized_data: 'opaque', ext_ids: [{ ext_id_type: 5, str: 'mood-id', extra: 1 }] },
cell_feed_transfer: { cookie: 'opaque-server-transfer', nested: [1, true, null] },
feed_action_domain_type: 1,
like_key: 'server-like-key',
};
expect(validateQzoneFeedReference(reference)).toBe(reference);
const withEmptyDefaults = { union_id: { uf_key: 'issued-key', ugc_id: '', feed_id: '', serialized_data: '' } };
expect(validateQzoneFeedReference(withEmptyDefaults)).toBe(withEmptyDefaults);
expect(() => validateQzoneFeedReference({ tid: 'mood-id' })).toThrow();
expect(() => validateQzoneFeedReference({ union_id: {} })).toThrow();
expect(() => validateQzoneFeedReference({ union_id: { uf_key: '' } })).toThrow();
expect(() => validateQzoneFeedReference({ union_id: { uf_key: 'key' }, feed_action_domain_type: 4 })).toThrow();
});
test('bounds UTF-8 reference size and rejects non-JSON or cyclic transfer data', () => {
expect(() => validateQzoneFeedReference({ union_id: { uf_key: 'key' }, cell_feed_transfer: '中'.repeat(QZONE_REFERENCE_MAX_BYTES / 2) })).toThrow('64KiB');
expect(() => validateQzoneFeedReference({ union_id: { uf_key: 'key' }, cell_feed_transfer: 1n })).toThrow('JSON');
const cycle: Record<string, unknown> = {};
cycle['self'] = cycle;
expect(() => validateQzoneFeedReference({ union_id: { uf_key: 'key' }, cell_feed_transfer: cycle })).toThrow();
});
});
describe('Qzone RPC feed projections', () => {
test('keeps missing values unknown while retaining the original feed', () => {
const feed = { future_cell: { unknown: 'retained' } };
expect(normalizeQzoneFeed(feed)).toEqual({
tid: null,
user_id: null,
content: null,
time: null,
comment_num: null,
like_num: null,
images: null,
feed_ref: null,
feed,
});
expect(normalizeQzoneFeed(feed).feed).toBe(feed);
});
test('normalizes observed text, counts and image variants without including video covers', () => {
const feed: QzoneFeed = {
cell_common: { feed_sub_type: 1, time: '1700000000', union_id: { uf_key: 'key', ugc_id: 'tid' }, cur_like_key: 'like-key', domain_type: 1 },
cell_user_info: { user: { uin: '10001' } },
cell_summary: { summary: [{ type: 0, content: 'Hello ' }, { type: 1, name: 'Qiao' }, { type: 0, content: '[em]e100[/em]' }] },
cell_comment: { num: 0, comments: [] },
cell_like: { num: 2 },
cell_media: {
media_items: [
{ type: 0, image: { photo_url: [{ spec: 1, url: { url: 'https://example.com/big.jpg' } }, { spec: 6, url: { url: '//example.com/original.jpg' } }] } },
{ type: 1, video: { cover: { default_url: { url: 'https://example.com/video-cover.jpg' } } } },
],
},
cell_feed_transfer: { unknown: true },
};
const result = normalizeQzoneFeed(feed);
expect(result).toMatchObject({ tid: 'tid', user_id: '10001', content: 'Hello @Qiao[em]e100[/em]', time: 1700000000, comment_num: 0, like_num: 2, images: ['https://example.com/original.jpg'] });
expect(result.feed_ref).toEqual({ union_id: feed.cell_common!.union_id, like_key: 'like-key', feed_action_domain_type: 1, cell_feed_transfer: { unknown: true } });
expect(result.feed).toBe(feed);
});
test('distinguishes known empty values from unknown or malformed sections', () => {
expect(normalizeQzoneFeed({ cell_summary: { summary: [] }, cell_media: { media_items: [] } })).toMatchObject({ content: '', images: [] });
expect(normalizeQzoneFeed({ cell_summary: { summary: [{ type: 99, content: 'future' }] } }).content).toBeNull();
expect(normalizeQzoneFeed({ cell_media: { media_items: [{ type: 0, image: {} }] } }).images).toBeNull();
expect(normalizeQzoneFeed({ cell_comment: { num: -1 }, cell_like: { num: 'not-a-number' } })).toMatchObject({ comment_num: null, like_num: null });
});
test('declines unusable action handles while keeping their raw source', () => {
const feed = { cell_common: { union_id: { uf_key: '' } }, untouched: true };
const result = normalizeQzoneFeed(feed);
expect(result.feed_ref).toBeNull();
expect(result.feed).toBe(feed);
});
});
describe('Qzone RPC pure-text publish body', () => {
test('uses the official RichMsg shape and preserves text exactly', () => {
expect(buildQzoneText(' hello\n[em]e100[/em] ')).toEqual([
{ content: ' hello\n[em]e100[/em] ', media_items: [], name: '', type: 0, uid: '', uin: '', url: '', who: 0 },
]);
expect(() => buildQzoneText(' \n ')).toThrow();
expect(() => buildQzoneText('x'.repeat(2001))).toThrow('2000');
});
test.each([[1, 1], [4, 2], [16, 3], [128, 4], [64, 5]])('maps legacy permission %i to modern flag %i', (legacy, modern) => {
const result = buildQzonePublishRequest({ uin: '10001', uid: 'uid', nick: 'Qiao' }, 'post', legacy, ['10002'], 1700000000, 'client-key');
expect(result).toMatchObject({
from: 3,
feed: {
cell_common: { time: 1700000000, client_key: 'client-key', feed_type: 1, feed_sub_type: 1, feed_biz_type: 0, union_id: { uf_key: 'client-key', ugc_id: 'client-key', feed_id: 'client-key' } },
cell_user_info: { user: { uin: '10001', uid: 'uid', nick: 'Qiao' } },
cell_permission: { right: { flag: [modern] } },
},
});
const permission = result.feed['cell_permission'] as { right: Record<string, unknown>; };
expect(permission.right['white_uins']).toEqual(legacy === 16 ? ['10002'] : undefined);
expect(permission.right['black_uins']).toEqual(legacy === 128 ? ['10002'] : undefined);
expect(result.feed).not.toHaveProperty('cell_media');
});
test('rejects unsupported rights and incomplete target lists before publishing', () => {
for (const right of [0, 2, 3, 5, 256, NaN]) {
expect(() => buildQzonePublishRequest({ uin: '10001' }, 'post', right)).toThrow();
}
for (const right of [16, 128]) {
expect(() => buildQzonePublishRequest({ uin: '10001' }, 'post', right)).toThrow('target_uins');
expect(() => buildQzonePublishRequest({ uin: '10001' }, 'post', right, [])).toThrow('target_uins');
}
expect(() => buildQzonePublishRequest({ uin: '' }, 'post', 1)).toThrow();
expect(() => buildQzonePublishRequest({ uin: '10001' }, 'post', 1, ['bad-uin'])).toThrow();
});
test('matches known gtk values without needing an account key', () => {
expect(getQzoneGtk('')).toBe(5381);
expect(getQzoneGtk('abc')).toBe(193485963);
});
});
@@ -0,0 +1,347 @@
// StreamBasic must be evaluated before OneBotAction because of their circular import.
import '../napcat-onebot/action/stream/StreamBasic';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import { GetQzoneFeeds } from '@/napcat-onebot/action/extends/qzone/GetQzoneFeeds';
import { GetQzoneMsgList } from '@/napcat-onebot/action/extends/qzone/GetQzoneMsgList';
import { GetQzoneMsgDetail } from '@/napcat-onebot/action/extends/qzone/GetQzoneMsgDetail';
import { LikeQzone } from '@/napcat-onebot/action/extends/qzone/LikeQzone';
import { UnlikeQzone } from '@/napcat-onebot/action/extends/qzone/UnlikeQzone';
import { CommentQzone } from '@/napcat-onebot/action/extends/qzone/CommentQzone';
import { SendQzoneMsg } from '@/napcat-onebot/action/extends/SendQzoneMsg';
import { DeleteQzoneMsg } from '@/napcat-onebot/action/extends/DeleteQzoneMsg';
import { QzoneFeedItemExample, QzoneFeedReferenceExample } from '@/napcat-onebot/action/extends/qzone/common';
import { SlQzoneFeedsExample, SlQzoneMsgDetailExample, SlQzoneMsgListExample } from '@/napcat-onebot/action/extends/qzone/common-snowluma';
const tempDirs: string[] = [];
function createCore () {
const QzoneApi = {
getFriendFeeds: vi.fn().mockResolvedValue({ feeds: [QzoneFeedItemExample], has_more: false, next_cursor: null }),
getMsgList: vi.fn().mockResolvedValue({ msglist: [QzoneFeedItemExample], has_more: false, next_cursor: null }),
getMsgDetail: vi.fn().mockResolvedValue({ ...QzoneFeedItemExample, comments: [] }),
setLike: vi.fn().mockResolvedValue(undefined),
comment: vi.fn().mockResolvedValue({ comment_id: 'native-comment', comment: { id: 'native-comment', extra: 'raw' } }),
getSnowlumaFeeds: vi.fn().mockResolvedValue(SlQzoneFeedsExample),
getSnowlumaMsgList: vi.fn().mockResolvedValue(SlQzoneMsgListExample),
getSnowlumaMsgDetail: vi.fn().mockResolvedValue(SlQzoneMsgDetailExample),
setSnowlumaLike: vi.fn().mockResolvedValue(undefined),
commentSnowluma: vi.fn().mockResolvedValue({ comment_id: 'sl-comment' }),
uploadCommentImage: vi.fn().mockResolvedValue({ url: 'https://images.example.test/comment.png' }),
publishMsg: vi.fn().mockResolvedValue({ tid: 'published', time: 1700000000 }),
};
return {
NapCatTempPath: '',
selfInfo: { uin: '10001', uid: 'u_current' },
apis: {
QzoneApi,
WebApi: {
uploadImageToQzone: vi.fn().mockResolvedValue('published-richval'),
publishQzoneMsg: vi.fn().mockResolvedValue({ tid: 'published-image', time: 1700000001 }),
deleteQzoneMsg: vi.fn().mockResolvedValue(undefined),
},
},
context: { logger: { logError: vi.fn() } },
};
}
function withImageDirectory (core: ReturnType<typeof createCore>) {
const directory = mkdtempSync(join(tmpdir(), 'napcat-qzone-sl-actions-'));
tempDirs.push(directory);
core.NapCatTempPath = directory;
return directory;
}
afterEach(() => {
for (const directory of tempDirs.splice(0)) rmSync(directory, { recursive: true, force: true });
});
describe('QQ空间 SnowLuma action compatibility', () => {
it('defaults to SL feeds and routes old opaque cursors before applying SL defaults', async () => {
const core = createCore();
const action = new GetQzoneFeeds(undefined as never, core as never);
const result = await action.handle({}, 'test', {} as never);
await action.handle({ page_num: '2', count: '5', unrelated: 'ignored' } as never, 'test', {} as never);
await action.handle({ cursor: 'slqf:continuation' }, 'test', {} as never);
await action.handle({ cursor: 'old-native-cursor' }, 'test', {} as never);
await action.handle({ format: 'native' }, 'test', {} as never);
expect(result).toMatchObject({ status: 'ok', data: SlQzoneFeedsExample });
expect(core.apis.QzoneApi.getSnowlumaFeeds.mock.calls).toEqual([
[1, 10, undefined], [2, 5, undefined], [1, 10, 'slqf:continuation'],
]);
expect(core.apis.QzoneApi.getFriendFeeds.mock.calls).toEqual([['old-native-cursor'], [undefined]]);
});
it('defaults to SL list pagination while retaining native raw results and lossless target IDs', async () => {
const core = createCore();
const action = new GetQzoneMsgList(undefined as never, core as never);
const result = await action.handle({}, 'test', {} as never);
await action.handle({ target_uin: '9007199254740993', pos: '40', num: '10' }, 'test', {} as never);
const native = await action.handle({ format: 'native', target_uin: 10002 }, 'test', {} as never);
await action.handle({ target_uin: '10003', cursor: 'native-list-cursor' }, 'test', {} as never);
expect(result).toMatchObject({ status: 'ok', data: SlQzoneMsgListExample });
expect(core.apis.QzoneApi.getSnowlumaMsgList.mock.calls).toEqual([
[undefined, 0, 20], ['9007199254740993', 40, 10],
]);
expect(core.apis.QzoneApi.getMsgList.mock.calls).toEqual([['10002', undefined], ['10003', 'native-list-cursor']]);
expect(native).toHaveProperty('data.msglist.0.feed_ref', QzoneFeedReferenceExample);
expect(native).toHaveProperty('data.msglist.0.feed', QzoneFeedItemExample.feed);
});
it('routes detail by its explicit anchor and does not project native raw comments', async () => {
const core = createCore();
const action = new GetQzoneMsgDetail(undefined as never, core as never);
const reference = { ...QzoneFeedReferenceExample, cell_feed_transfer: { keep: [0, false, 'raw'] } };
const sl = await action.handle({ tid: 0, target_uin: 10002, pos: '2', num: '3' }, 'test', {} as never);
const native = await action.handle({ feed_ref: reference }, 'test', {} as never);
expect(sl).toMatchObject({ status: 'ok', data: SlQzoneMsgDetailExample });
expect(core.apis.QzoneApi.getSnowlumaMsgDetail).toHaveBeenCalledExactlyOnceWith('0', '10002', 2, 3);
expect(core.apis.QzoneApi.getMsgDetail).toHaveBeenCalledExactlyOnceWith(reference);
expect(native).toHaveProperty('data.feed', QzoneFeedItemExample.feed);
});
it('uses one like backend per anchor and returns explicit null for both SL operations', async () => {
const core = createCore();
for (const Action of [LikeQzone, UnlikeQzone]) {
const action = new Action(undefined as never, core as never);
const result = await action.handle({ tid: 'post', target_uin: '10002', abstime: '123' }, 'test', {} as never);
expect(JSON.parse(JSON.stringify(result))).toMatchObject({ status: 'ok', data: null });
await action.handle({ feed_ref: QzoneFeedReferenceExample }, 'test', {} as never);
}
expect(core.apis.QzoneApi.setSnowlumaLike.mock.calls).toEqual([
['post', '10002', true, 123], ['post', '10002', false, 123],
]);
expect(core.apis.QzoneApi.setLike.mock.calls).toEqual([[QzoneFeedReferenceExample, true], [QzoneFeedReferenceExample, false]]);
});
it('normalizes SL root comments and complete reply pairs while retaining native comments', async () => {
const core = createCore();
const action = new CommentQzone(undefined as never, core as never);
const root = await action.handle({ tid: 'post', content: false, ignored: true } as never, 'test', {} as never);
await action.handle({
tid: 'post',
target_uin: 10002,
content: '回复',
comment_id: 0,
comment_uin: 10003,
reply_uin: '10004',
reply_name: ' 回复目标 ',
images: [],
}, 'test', {} as never);
const native = await action.handle({ feed_ref: QzoneFeedReferenceExample, content: '原生评论' }, 'test', {} as never);
expect(root).toMatchObject({ status: 'ok', data: { comment_id: 'sl-comment' } });
expect(core.apis.QzoneApi.commentSnowluma.mock.calls).toEqual([
['post', 'false', undefined, undefined],
['post', '回复', '10002', { comment_id: '0', comment_uin: '10003', reply_uin: '10004', reply_name: ' 回复目标 ' }],
]);
expect(native).toMatchObject({ status: 'ok', data: { comment_id: 'native-comment', comment: { id: 'native-comment', extra: 'raw' } } });
expect(core.apis.QzoneApi.comment).toHaveBeenCalledExactlyOnceWith(QzoneFeedReferenceExample, '原生评论', undefined, undefined);
});
it('uploads root comment images in order and removes temporary sources while preserving user files', async () => {
const core = createCore();
const directory = withImageDirectory(core);
const localImage = join(directory, 'user-image.png');
writeFileSync(localImage, 'user image');
core.apis.QzoneApi.uploadCommentImage
.mockResolvedValueOnce({ url: 'https://images.example.test/first.png' })
.mockResolvedValueOnce({ url: 'https://images.example.test/second.png' });
await new CommentQzone(undefined as never, core as never)._handle({
tid: 'post', content: '图片评论', images: ['base64://aGVsbG8=', pathToFileURL(localImage).href],
});
expect(core.apis.QzoneApi.uploadCommentImage.mock.calls).toEqual([
[Buffer.from('hello').toString('base64')], [Buffer.from('user image').toString('base64')],
]);
expect(core.apis.QzoneApi.commentSnowluma).toHaveBeenCalledExactlyOnceWith('post', '图片评论', undefined, {
imageUrls: ['https://images.example.test/first.png', 'https://images.example.test/second.png'],
});
expect(readdirSync(directory)).toEqual(['user-image.png']);
expect(readFileSync(localImage, 'utf8')).toBe('user image');
expect(core.apis.QzoneApi.comment).not.toHaveBeenCalled();
});
it.each(['upload failure', 'invalid URL'])('stops comment publishing after %s and cleans temporary images', async (failure) => {
const core = createCore();
const directory = withImageDirectory(core);
if (failure === 'upload failure') core.apis.QzoneApi.uploadCommentImage.mockRejectedValue(new Error('upload failed'));
else core.apis.QzoneApi.uploadCommentImage.mockResolvedValue({ url: 'javascript:alert(1)' });
await expect(new CommentQzone(undefined as never, core as never)._handle({
tid: 'post', content: '图片评论', images: ['base64://aGVsbG8=', 'base64://d29ybGQ='],
})).rejects.toThrow();
expect(core.apis.QzoneApi.uploadCommentImage).toHaveBeenCalledTimes(1);
expect(core.apis.QzoneApi.commentSnowluma).not.toHaveBeenCalled();
expect(core.apis.QzoneApi.comment).not.toHaveBeenCalled();
expect(readdirSync(directory)).toEqual([]);
});
it('stops the image comment chain when either account identifier changes during upload', async () => {
for (const change of [{ uin: '10002' }, { uid: 'u_other' }]) {
const core = createCore();
const directory = withImageDirectory(core);
core.apis.QzoneApi.uploadCommentImage.mockImplementationOnce(async () => {
Object.assign(core.selfInfo, change);
return { url: 'https://images.example.test/uploaded.png' };
});
await expect(new CommentQzone(undefined as never, core as never)._handle({
tid: 'post', content: '图片评论', images: ['base64://aGVsbG8=', 'base64://d29ybGQ='],
})).rejects.toThrow('QQ账号已切换');
expect(core.apis.QzoneApi.uploadCommentImage).toHaveBeenCalledTimes(1);
expect(core.apis.QzoneApi.commentSnowluma).not.toHaveBeenCalled();
expect(readdirSync(directory)).toEqual([]);
}
});
it('rejects ambiguous routing and malformed known parameters before any API call', async () => {
const cases = [
[GetQzoneFeeds, { format: 'native', page_num: 1 }],
[GetQzoneFeeds, { cursor: 'native-cursor', count: 10 }],
[GetQzoneFeeds, { format: 'native', cursor: 'slqf:cursor' }],
[GetQzoneFeeds, { format: 'snowluma', cursor: 'native-cursor' }],
[GetQzoneFeeds, { page_num: false }],
[GetQzoneFeeds, { count: 51 }],
[GetQzoneFeeds, { target_uin: '10002' }],
[GetQzoneMsgList, { format: 'native', pos: 0 }],
[GetQzoneMsgList, { cursor: 'native-cursor', num: 20 }],
[GetQzoneMsgList, { format: 'snowluma', cursor: 'native-cursor' }],
[GetQzoneMsgList, { cursor: 'slqf:cursor' }],
[GetQzoneMsgList, { target_uin: Number.MAX_SAFE_INTEGER + 1 }],
[GetQzoneMsgList, { pos: null }],
[GetQzoneMsgList, { num: 0 }],
[GetQzoneMsgDetail, {}],
[GetQzoneMsgDetail, { feed_ref: QzoneFeedReferenceExample, tid: 'post' }],
[GetQzoneMsgDetail, { feed_ref: QzoneFeedReferenceExample, pos: 0 }],
[GetQzoneMsgDetail, { tid: true }],
[GetQzoneMsgDetail, { tid: Number.MAX_SAFE_INTEGER + 1 }],
[LikeQzone, { tid: 'post', abstime: -1 }],
[LikeQzone, { tid: 'post', abstime: true }],
[UnlikeQzone, { feed_ref: QzoneFeedReferenceExample, target_uin: '10002' }],
[CommentQzone, { tid: 'post', content: 'x', comment_id: 0 }],
[CommentQzone, { tid: 'post', content: 'x', comment_uin: '10002' }],
[CommentQzone, { tid: 'post', content: 'x', reply_uin: '10002' }],
[CommentQzone, { tid: 'post', content: 'x', reply_name: 'name' }],
[CommentQzone, { tid: 'post', content: 'x', reply_uin: '10002', reply_name: 'name' }],
[CommentQzone, { tid: 'post', content: 'x', comment_id: 0, comment_uin: '9007199254740993' }],
[CommentQzone, { tid: 'post', content: 'x', comment: { id: 'native-parent', user: { uin: '10002' } } }],
[CommentQzone, { feed_ref: QzoneFeedReferenceExample, content: 'x', images: [] }],
[CommentQzone, { tid: 'post', content: null }],
[CommentQzone, { tid: 'post', content: 'x', images: [''] }],
[DeleteQzoneMsg, { tid: Number.MAX_SAFE_INTEGER + 1 }],
[DeleteQzoneMsg, { tid: 'post', target_uin: '10002' }],
[SendQzoneMsg, { content: 'x', ugc_right: true }],
[SendQzoneMsg, { content: 'x', target_uins: [Number.MAX_SAFE_INTEGER + 1] }],
] as const;
for (const [Action, payload] of cases) {
const core = createCore();
const result = await new Action(undefined as never, core as never).handle(payload as never, 'test', {} as never);
expect(result.status, JSON.stringify(payload)).toBe('failed');
for (const method of [...Object.values(core.apis.QzoneApi), ...Object.values(core.apis.WebApi)]) {
expect(method, JSON.stringify(payload)).not.toHaveBeenCalled();
}
}
});
it('validates all reply and identity fields before any image upload', async () => {
const core = createCore();
const action = new CommentQzone(undefined as never, core as never);
const cases = [
{ tid: 'post', comment_id: 0, comment_uin: 10002 },
{ tid: 'post', comment_id: 0 },
{ tid: 'post', reply_uin: 10002, reply_name: 'name' },
{ tid: 'post\n' },
{ tid: 'post', comment_uin: false },
{ tid: 'post', reply_name: ['invalid'] },
{ tid: 'post', images: ['base64://aGVsbG8=', 1] },
];
for (const payload of cases) {
const result = await action.handle({ content: 'x', images: ['base64://aGVsbG8='], ...payload } as never, 'test', {} as never);
expect(result.status).toBe('failed');
}
expect(core.apis.QzoneApi.uploadCommentImage).not.toHaveBeenCalled();
expect(core.apis.QzoneApi.commentSnowluma).not.toHaveBeenCalled();
});
it('does not retry uncertain SL writes through any native backend', async () => {
const core = createCore();
core.apis.QzoneApi.setSnowlumaLike.mockRejectedValue(new Error('写入结果未知'));
core.apis.QzoneApi.commentSnowluma.mockRejectedValue(new Error('写入结果未知'));
expect((await new LikeQzone(undefined as never, core as never).handle({ tid: 'post' }, 'test', {} as never)).status).toBe('failed');
expect((await new CommentQzone(undefined as never, core as never).handle({ tid: 'post', content: 'x' }, 'test', {} as never)).status).toBe('failed');
expect(core.apis.QzoneApi.setSnowlumaLike).toHaveBeenCalledExactlyOnceWith('post', undefined, true, 0);
expect(core.apis.QzoneApi.commentSnowluma).toHaveBeenCalledExactlyOnceWith('post', 'x', undefined, undefined);
expect(core.apis.QzoneApi.setLike).not.toHaveBeenCalled();
expect(core.apis.QzoneApi.comment).not.toHaveBeenCalled();
});
it('keeps server publish times, preserves empty image captions, and marks missing times as unknown', async () => {
const core = createCore();
const directory = withImageDirectory(core);
const action = new SendQzoneMsg(undefined as never, core as never);
await expect(action._handle({ content: false })).resolves.toEqual({ tid: 'published', time: 1700000000 });
await expect(action._handle({ content: '', images: ['base64://aGVsbG8='] }))
.resolves.toEqual({ tid: 'published-image', time: 1700000001 });
core.apis.QzoneApi.publishMsg.mockResolvedValue({ tid: 'old-mock' } as never);
await expect(action._handle({ content: 'x' })).resolves.toEqual({ tid: 'old-mock', time: 0 });
expect(core.apis.QzoneApi.publishMsg).toHaveBeenNthCalledWith(1, 'false', 1, undefined);
expect(core.apis.WebApi.publishQzoneMsg).toHaveBeenCalledExactlyOnceWith('', ['published-richval'], 1, undefined);
expect(readdirSync(directory)).toEqual([]);
});
it('normalizes safe numeric delete IDs and serializes success with explicit null', async () => {
const core = createCore();
const result = await new DeleteQzoneMsg(undefined as never, core as never).handle({ tid: 0 }, 'test', {} as never);
expect(core.apis.WebApi.deleteQzoneMsg).toHaveBeenCalledExactlyOnceWith('0');
expect(JSON.parse(JSON.stringify(result))).toMatchObject({ status: 'ok', data: null });
});
it('requires a complete initial account identity before starting image publishing', async () => {
const core = createCore();
const directory = withImageDirectory(core);
core.selfInfo.uid = '';
await expect(new SendQzoneMsg(undefined as never, core as never)._handle({
content: '带图', images: ['base64://aGVsbG8='],
})).rejects.toThrow('需要已登录');
expect(core.apis.WebApi.uploadImageToQzone).not.toHaveBeenCalled();
expect(core.apis.WebApi.publishQzoneMsg).not.toHaveBeenCalled();
expect(core.apis.QzoneApi.publishMsg).not.toHaveBeenCalled();
expect(readdirSync(directory)).toEqual([]);
});
it('publishes schema-valid SL examples and accepts the documented unknown-total metadata', () => {
const core = createCore();
const actions = [
new GetQzoneFeeds(undefined as never, core as never), new GetQzoneMsgList(undefined as never, core as never),
new GetQzoneMsgDetail(undefined as never, core as never), new LikeQzone(undefined as never, core as never),
new UnlikeQzone(undefined as never, core as never), new CommentQzone(undefined as never, core as never),
new SendQzoneMsg(undefined as never, core as never), new DeleteQzoneMsg(undefined as never, core as never),
];
for (const action of actions) {
expect(TypeCompiler.Compile(action.payloadSchema).Check(action.payloadExample)).toBe(true);
expect(TypeCompiler.Compile(action.returnSchema).Check(action.returnExample)).toBe(true);
}
expect(TypeCompiler.Compile(actions[1]!.returnSchema).Check({ total: 0, total_known: false, msglist: [] })).toBe(true);
});
});
@@ -0,0 +1,221 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { NTQQQzoneApi } from '@/napcat-core/apis/qzone';
import { NTQQWebApi } from '@/napcat-core/apis/webapi';
import { RequestUtil } from '@/napcat-common/src/request';
function createApi () {
const core = {
selfInfo: { uin: '10001', uid: 'self-uid', nick: '本人' },
apis: {
UserApi: {
getSKey: vi.fn().mockResolvedValue('s'),
getPSkey: vi.fn().mockResolvedValue({ result: 0, domainPskeyMap: new Map([['qzone.qq.com', 'p']]) }),
},
},
};
return { api: new NTQQQzoneApi({} as never, core as never), core };
}
function response (data: Record<string, unknown>): Response {
return new Response(`_preloadCallback(${JSON.stringify(data)});`);
}
function feedPage (key: string, hasMore: boolean, state: Record<string, unknown> = {}): Record<string, unknown> {
return { code: 0, data: { data: [{ uin: 20002, nickname: '好友', abstime: 1700000000, appid: 311, key, html: '' }], main: { hasMoreFeeds: hasMore, ...state } } };
}
describe('SnowLuma Qzone compatibility transport', () => {
let fetchMock: ReturnType<typeof vi.fn<typeof fetch>>;
beforeEach(() => {
fetchMock = vi.fn<typeof fetch>();
vi.stubGlobal('fetch', fetchMock);
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it('reads the requested legacy list offset/count and keeps a real total', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ code: 0, total: 100, msglist: [{ tid: 'post', content: '正文', created_time: 1700000000, cmtnum: 5, secret: 1 }] }));
await expect(api.getSnowlumaMsgList('20002', 40, 10)).resolves.toMatchObject({
total: 100, total_known: true, msglist: [{ tid: 'post', content: '正文', time: 1700000000, comment_num: 5, is_private: true, images: [] }],
});
const url = new URL(String(fetchMock.mock.calls[0]![0]));
expect(url.pathname).toBe('/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_msglist_v6');
expect(Object.fromEntries(url.searchParams)).toMatchObject({ uin: '20002', pos: '40', num: '10', replynum: '100', g_tk: '177685' });
expect(fetchMock.mock.calls[0]![1]).toMatchObject({ method: 'GET', redirect: 'error' });
});
it('uses the alternate fixed read route only for explicit code -10000', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ code: -10000 })).mockResolvedValueOnce(response({ code: 0, total: 0, msglist: [] }));
await expect(api.getSnowlumaMsgList()).resolves.toMatchObject({ total: 0, msglist: [] });
const [url, options] = fetchMock.mock.calls[1]!;
expect(new URL(String(url)).origin).toBe('https://user.qzone.qq.com');
expect(new URL(String(url)).pathname).toBe('/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6');
expect(options?.headers).toMatchObject({ Referer: 'https://user.qzone.qq.com/10001' });
fetchMock.mockResolvedValueOnce(response({ code: -3000 }));
await expect(api.getSnowlumaMsgList()).rejects.toThrow('-3000');
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it('reads a tid and one flat comment page without synthesizing a modern feed reference', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ code: 0, tid: 'post', content: '正文', cmtnum: 90, commentlist: [{ tid: 0, uin: 20002, name: '甲', create_time: 1700000000, content: '评论', list_3: [{ tid: 1, uin: 20003, name: '乙', create_time: 1700000001, content: '回复' }] }] }));
const page = await api.getSnowlumaMsgDetail('post', '20002', 20, 5);
expect(page).toMatchObject({ tid: 'post', comment_num: 90, comments: [{ comment_id: '0', replies: [{ comment_id: '1', parent_comment_id: '0', parent_comment_uin: 20002 }] }] });
const url = new URL(String(fetchMock.mock.calls[0]![0]));
expect(Object.fromEntries(url.searchParams)).toMatchObject({ tid: 'post', uin: '20002', pos: '20', num: '5', not_trunc_con: '1' });
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('rejects invalid identities and pagination before ticket acquisition', async () => {
const { api, core } = createApi();
await expect(api.getSnowlumaMsgList('bad')).rejects.toThrow();
await expect(api.getSnowlumaMsgList(undefined, -1)).rejects.toThrow();
await expect(api.getSnowlumaMsgDetail('post', undefined, 0, 101)).rejects.toThrow();
await expect(api.getSnowlumaFeeds(21)).rejects.toThrow('预算');
await expect(api.getSnowlumaFeeds(1, 51)).rejects.toThrow();
await expect(api.uploadCommentImage('not base64')).rejects.toThrow();
expect(core.apis.UserApi.getSKey).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
});
it('posts each tid-based like/unlike exactly once with owner and timestamp', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ code: 0 })).mockResolvedValueOnce(response({ code: 0 }));
await api.setSnowlumaLike('post', '20002', true, 1700000000);
await api.setSnowlumaLike('post', '20002', false, 1700000000);
expect(new URL(String(fetchMock.mock.calls[0]![0])).pathname).toContain('internal_dolike_app');
expect(new URL(String(fetchMock.mock.calls[1]![0])).pathname).toContain('internal_unlike_app');
expect(Object.fromEntries(new URLSearchParams(fetchMock.mock.calls[0]![1]?.body as string))).toMatchObject({
opuin: '10001', fid: 'post', abstime: '1700000000', unikey: 'http://user.qzone.qq.com/20002/mood/post',
});
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('uploads a comment image using native tickets and the returned real URL', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(new Response('frameElement.callback({"code":0,"data":{"url":"https://photo.example/image?a=1&b=2"}});</script>'));
await expect(api.uploadCommentImage('aGVsbG8=')).resolves.toEqual({ url: 'https://photo.example/image?a=1&b=2' });
const [url, options] = fetchMock.mock.calls[0]!;
expect(String(url)).toBe('https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=177685');
expect(options).toMatchObject({ method: 'POST', redirect: 'error' });
expect(new URLSearchParams(options?.body as string).get('picfile')).toBe('aGVsbG8=');
fetchMock.mockResolvedValueOnce(response({ code: 0, data: { url: 'javascript:private()' } }));
await expect(api.uploadCommentImage('aGVsbG8=')).rejects.toThrow('图片地址无效');
for (const url of [' https://photo.example/a ', 'https://photo.example/a' + String.fromCharCode(0)]) {
fetchMock.mockResolvedValueOnce(response({ code: 0, data: { url } }));
await expect(api.uploadCommentImage('aGVsbG8=')).rejects.toThrow('可用图片地址');
}
});
it('accepts the observed FormSender upload envelope with ret acknowledgement and rejects conflicting codes', async () => {
const { api } = createApi();
const html = (body: Record<string, unknown>) => '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/></head><body><script type="text/javascript">document.domain="h5.qzone.qq.com";frameElement.callback(' + JSON.stringify(body) + ');</script></body></html>';
fetchMock.mockResolvedValueOnce(new Response(html({ ret: 0, data: { url: 'https://photo.example/test.png' } })));
await expect(api.uploadCommentImage('aGVsbG8=')).resolves.toEqual({ url: 'https://photo.example/test.png' });
fetchMock.mockResolvedValueOnce(new Response(html({ ret: 0, code: -1, data: { url: 'https://photo.example/test.png' } })));
await expect(api.uploadCommentImage('aGVsbG8=')).rejects.toThrow('勿自动重试');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('posts image comments with URLs and preserves the real parent for replies', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ code: 0, commentid: 0 }));
await expect(api.commentSnowluma('post', '图片', '20002', { imageUrls: ['https://photo.example/a'] })).resolves.toEqual({ comment_id: '0' });
const commentBody = new URLSearchParams(fetchMock.mock.calls[0]![1]?.body as string);
expect(Object.fromEntries(commentBody)).toMatchObject({ hostUin: '20002', uin: '10001', topicId: '20002_post__1', richtype: '1', richval: 'https://photo.example/a' });
fetchMock.mockResolvedValueOnce(response({ code: 0, data: { id: 'new-reply' } }));
await expect(api.commentSnowluma('post', '回复', '20002', { comment_id: '0', comment_uin: '20003', reply_uin: '20004', reply_name: '丙' })).resolves.toEqual({ comment_id: 'new-reply', parent_comment_id: '0', parent_comment_uin: 20003 });
const replyBody = new URLSearchParams(fetchMock.mock.calls[1]![1]?.body as string);
expect(Object.fromEntries(replyBody)).toMatchObject({ uin: '10001', hostUin: '20002', commentId: '0', commentUin: '20003' });
expect(replyBody.get('content')).toContain('20004');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('never replays an uncertain write and rejects image replies before network IO', async () => {
const { api } = createApi();
await expect(api.commentSnowluma('post', '回复', '20002', { comment_id: '0', comment_uin: '20003', imageUrls: ['https://photo.example/a'] })).rejects.toThrow();
expect(fetchMock).not.toHaveBeenCalled();
fetchMock.mockRejectedValueOnce(new Error('private transport detail'));
await expect(api.commentSnowluma('post', '正文')).rejects.toThrow('勿自动重试');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('stops the existing image publisher if the account changes during either native ticket lookup', async () => {
const request = vi.spyOn(RequestUtil, 'HttpGetText').mockRejectedValue(new Error('unexpected network request'));
for (const stage of ['skey', 'pskey']) {
const { core } = createApi();
const web = new NTQQWebApi({} as never, core as never);
if (stage === 'skey') {
core.apis.UserApi.getSKey.mockImplementationOnce(async () => { core.selfInfo.uid = 'switched'; return 's'; });
} else {
core.apis.UserApi.getPSkey.mockImplementationOnce(async () => {
core.selfInfo.uid = 'switched';
return { result: 0, domainPskeyMap: new Map([['qzone.qq.com', 'p']]) };
});
}
await expect(web.uploadImageToQzone('aGVsbG8=')).rejects.toThrow('QQ账号已切换');
}
expect(request).not.toHaveBeenCalled();
});
it('gets HTML feeds with bounded opaque continuation and actual server state', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response(feedPage('first', true, { pagenum: '2', begintime: '123', aisortNextTime: '456', externparam: 'opaque' })));
fetchMock.mockResolvedValueOnce(response(feedPage('second', false)));
const first = await api.getSnowlumaFeeds();
expect(first.next_cursor).toMatch(/^slqf:/);
expect(first.feeds[0]?.key).toBe('first');
const next = await api.getSnowlumaFeeds(1, 5, first.next_cursor!);
expect(next.feeds[0]?.key).toBe('second');
expect(next.next_cursor).toBeNull();
const url = new URL(String(fetchMock.mock.calls[1]![0]));
expect(Object.fromEntries(url.searchParams)).toMatchObject({ count: '5', pagenum: '2', begintime: '123', getAisort: '456', externparam: 'opaque', outputhtmlfeed: '1' });
expect(url.searchParams.has('aisortNextTime')).toBe(false);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('walks server continuations for explicit page numbers and stops at the actual end', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response(feedPage('skip', true, { pagenum: '2' }))).mockResolvedValueOnce(response(feedPage('wanted', false)));
const page = await api.getSnowlumaFeeds(2);
expect(page.feeds.map(item => item.key)).toEqual(['wanted']);
fetchMock.mockResolvedValueOnce(response(feedPage('last', false)));
await expect(api.getSnowlumaFeeds(3)).resolves.toEqual({ feeds: [], has_more: false, next_cursor: null });
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it('binds feed cursors to account, page, lifetime and prevents clock-only continuation', async () => {
const { api, core } = createApi();
const clock = vi.spyOn(Date, 'now').mockReturnValue(1000);
fetchMock.mockResolvedValueOnce(response(feedPage('first', true, { pagenum: '2' })));
const first = await api.getSnowlumaFeeds();
await expect(api.getSnowlumaFeeds(3, 10, first.next_cursor!)).rejects.toThrow('不匹配');
core.selfInfo.uid = 'other-account';
await expect(api.getSnowlumaFeeds(1, 10, first.next_cursor!)).rejects.toThrow('游标');
core.selfInfo.uid = 'self-uid';
clock.mockReturnValue(601000);
await expect(api.getSnowlumaFeeds(1, 10, first.next_cursor!)).rejects.toThrow('已过期');
clock.mockReturnValue(1000);
fetchMock.mockResolvedValueOnce(response(feedPage('stuck', true, { icServerTime: '999' })));
await expect(api.getSnowlumaFeeds()).rejects.toThrow('未推进');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('enforces a shared 45-second read budget while skipping feed pages', async () => {
const { api } = createApi();
let now = 1000;
let pages = 0;
vi.spyOn(Date, 'now').mockImplementation(() => now);
fetchMock.mockImplementation(async () => {
now += 16000;
return response(feedPage('page', true, { pagenum: String(++pages + 1) }));
});
await expect(api.getSnowlumaFeeds(4)).rejects.toThrow('预算');
expect(fetchMock).toHaveBeenCalledTimes(3);
});
});
@@ -0,0 +1,183 @@
import { describe, expect, test } from 'vitest';
import {
buildSlQzoneCommentBody,
buildSlQzoneLikeBody,
parseSlQzoneComment,
parseSlQzoneMsgDetail,
parseSlQzoneMsgList,
} from '@/napcat-core/data/qzone-snowluma';
describe('SnowLuma-compatible mood list projections', () => {
test('maps wire fields and photo preference while retaining exact body text', () => {
const result = parseSlQzoneMsgList({
code: 0,
total: '23',
msglist: [{
tid: 'post-local-x',
content: ' independently written\ntext ',
created_time: '31',
cmtnum: '8',
secret: '1',
pic: [{ smallurl: 'https://cdn.example.test/tiny', url2: 'https://cdn.example.test/medium', url3: 'https://cdn.example.test/full' }],
}],
});
expect(result).toEqual({
total: 23,
total_known: true,
msglist: [{
tid: 'post-local-x', content: ' independently written\ntext ', time: 31, comment_num: 8, is_private: true, images: ['https://cdn.example.test/full'],
}],
});
});
test('labels the page-length total fallback and preserves the declared legacy sentinels', () => {
expect(parseSlQzoneMsgList({ msglist: [{}] })).toEqual({
total: 1, total_known: false, msglist: [{ tid: '', content: '', time: 0, comment_num: 0, is_private: false, images: [] }],
});
expect(parseSlQzoneMsgList({ total: 0, msglist: [] })).toEqual({ total: 0, total_known: true, msglist: [] });
expect(parseSlQzoneMsgList({ total: null, msglist: [] }).total_known).toBe(false);
});
test('rejects missing arrays, unsafe identities and malformed supplied values rather than inventing success', () => {
for (const response of [
{}, { msglist: null }, { msglist: [null] }, { msglist: [{}], total: 'bad' },
{ msglist: [{ tid: Number.MAX_SAFE_INTEGER + 1 }] }, { msglist: [{ created_time: -1 }] },
{ msglist: [{ cmtnum: 'bad' }] }, { msglist: [{ content: false }] }, { msglist: [{ pic: 'bad' }] },
{ code: -10000, subcode: 0, msglist: [] }, { code: 0, subcode: '0', msglist: [] },
]) expect(() => parseSlQzoneMsgList(response)).toThrow();
});
});
function detail (overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
code: 0,
tid: 'discussion-local-z',
content: 'discussion text',
cmtnum: '41',
commentlist: [{
tid: 0,
uin: '135790',
name: 'parent author',
create_time: '7',
content: 'parent text',
list_3: [
{ tid: 'nested-local-b', uin: 246810, name: 'reply author', create_time: 9, content: 'reply text' },
],
}],
...overrides,
};
}
describe('SnowLuma-compatible tid detail', () => {
test('normalizes legacy create_time and parent identities while preserving comment ID zero', () => {
expect(parseSlQzoneMsgDetail(detail(), 'discussion-local-z')).toEqual({
tid: 'discussion-local-z',
content: 'discussion text',
comment_num: 41,
comments: [{
comment_id: '0',
uin: 135790,
name: 'parent author',
time: 7,
content: 'parent text',
replies: [{
comment_id: 'nested-local-b', uin: 246810, name: 'reply author', time: 9, content: 'reply text', parent_comment_id: '0', parent_comment_uin: 135790,
}],
}],
});
});
test('treats only missing or null comment batches as no supplied inline comments', () => {
expect(parseSlQzoneMsgDetail(detail({ commentlist: null }), 'discussion-local-z').comments).toEqual([]);
expect(parseSlQzoneMsgDetail(detail({ commentlist: undefined }), 'discussion-local-z').comment_num).toBe(41);
expect(parseSlQzoneMsgDetail(detail({ commentlist: [{ tid: 'parent-only', uin: 135790, name: '', create_time: 0, content: '', list_3: null }] }), 'discussion-local-z').comments[0]?.replies).toEqual([]);
});
test('requires matching post identity, measured total and complete comment fields', () => {
for (const value of [
detail({ tid: 'different-post' }), detail({ content: undefined }), detail({ cmtnum: undefined }),
detail({ commentlist: {} }), detail({ commentlist: [{ tid: 0, uin: 135790, name: 'author', time: 10, content: 'wrong timestamp field' }] }),
detail({ commentlist: [{ tid: Number.MAX_SAFE_INTEGER + 1, uin: 135790, name: 'author', create_time: 10, content: '' }] }),
detail({ commentlist: [{ tid: 'parent', uin: '9007199254740993', name: 'author', create_time: 10, content: '' }] }),
detail({ code: 0, subcode: -99 }),
]) expect(() => parseSlQzoneMsgDetail(value, 'discussion-local-z')).toThrow();
});
});
describe('SnowLuma-compatible like and comment forms', () => {
test('builds tid-based like resources with distinct operator and post owner', () => {
const enabled = new URLSearchParams(buildSlQzoneLikeBody('246810', '135790', 'post-local-x', true, 42));
const disabled = new URLSearchParams(buildSlQzoneLikeBody('246810', '135790', 'post-local-x', false, 42));
expect(enabled.get('unikey')).toBe('http://user.qzone.qq.com/135790/mood/post-local-x');
expect(enabled.get('curkey')).toBe(enabled.get('unikey'));
expect(Object.fromEntries(enabled)).toMatchObject({ opuin: '246810', fid: 'post-local-x', abstime: '42', appid: '311', qzreferrer: 'https://user.qzone.qq.com/246810' });
expect([...disabled]).toEqual([...enabled]);
expect(() => buildSlQzoneLikeBody('246810', 'bad-owner', 'post-local-x', true, 0)).toThrow();
expect(() => buildSlQzoneLikeBody('246810', '135790', 'post-local-x', true, -1)).toThrow();
expect(() => buildSlQzoneLikeBody('246810', '135790', 'post-local-x', 'false' as never, 0)).toThrow();
});
test('uses direct uploaded URLs for ordinary image comments and keeps whitespace unchanged', () => {
const body = new URLSearchParams(buildSlQzoneCommentBody('246810', '135790', 'post-local-x', ' image comment\n ', {
imageUrls: ['https://cdn.example.test/comment-a', 'https://cdn.example.test/comment-b'],
}));
expect(Object.fromEntries(body)).toMatchObject({
uin: '246810',
hostUin: '135790',
topicId: '135790_post-local-x__1',
content: ' image comment\n ',
richtype: '1',
richval: 'https://cdn.example.test/comment-a\thttps://cdn.example.test/comment-b',
format: 'json',
ref: 'feeds',
feedsType: '100',
});
expect(body.has('commentId')).toBe(false);
expect(new URLSearchParams(buildSlQzoneCommentBody('246810', '135790', 'post-local-x', 'text')).get('richtype')).toBe('');
});
test('separates parent author from addressed recipient and escapes mention grammar before form encoding', () => {
const options = { comment_id: '0', comment_uin: '135790', reply_uin: '112233', reply_name: ' recipient%,} ' };
const body = new URLSearchParams(buildSlQzoneCommentBody('246810', '135790', 'post-local-x', 'reply body', options));
expect(Object.fromEntries(body)).toMatchObject({ uin: '246810', hostUin: '135790', hostuin: '246810', topicId: '135790_post-local-x', commentId: '0', commentUin: '135790', format: 'fs', ref: '' });
expect(body.get('content')).toBe('@{uin:112233,nick:recipient%25%2C%7D,auto:1} reply body');
expect(body.has('replyId')).toBe(false);
expect(body.has('richval')).toBe(false);
expect(new URLSearchParams(buildSlQzoneCommentBody('246810', '135790', 'post-local-x', 'reply body', { comment_id: '0', comment_uin: '135790' })).get('content')).toBe('reply body');
});
test('rejects mismatched parent/recipient pairs, unsafe authors and any image reply before returning a body', () => {
for (const options of [
{ comment_id: '0' }, { comment_uin: '135790' }, { reply_uin: '112233', reply_name: 'recipient' },
{ comment_id: '0', comment_uin: '135790', reply_uin: '112233' },
{ comment_id: '0', comment_uin: '9007199254740993' },
{ comment_id: '0', comment_uin: '135790', imageUrls: ['https://cdn.example.test/picture'] },
{ imageUrls: ['javascript:alert(1)'] }, { imageUrls: ['https://user:password@cdn.example.test/picture'] },
]) expect(() => buildSlQzoneCommentBody('246810', '135790', 'post-local-x', 'body', options)).toThrow();
expect(() => buildSlQzoneCommentBody('246810', '135790', 'post-local-x', ' ', { comment_id: '0', comment_uin: '135790' })).toThrow();
});
});
describe('SnowLuma-compatible comment acknowledgements', () => {
test('supports both ordinary ID casings and the documented empty-ID sentinel only after acknowledgement', () => {
expect(parseSlQzoneComment({ code: 0, commentid: 0 })).toEqual({ comment_id: '0' });
expect(parseSlQzoneComment({ subcode: 0, commentId: 'fresh-comment' })).toEqual({ comment_id: 'fresh-comment' });
expect(parseSlQzoneComment({ code: 0 })).toEqual({ comment_id: '' });
expect(parseSlQzoneComment({ code: 0, data: { id: 'another-endpoint-shape' } })).toEqual({ comment_id: '' });
expect(() => parseSlQzoneComment({})).toThrow('成功状态');
expect(() => parseSlQzoneComment({ code: 0, commentid: Number.MAX_SAFE_INTEGER + 1 })).toThrow();
});
test('requires a real reply identity and returns the supplied safe parent identity', () => {
const options = { comment_id: 'parent-local-c', comment_uin: '135790' };
expect(parseSlQzoneComment({ code: 0, data: { id: 0 } }, options)).toEqual({ comment_id: '0', parent_comment_id: 'parent-local-c', parent_comment_uin: 135790 });
for (const response of [{ code: 0 }, { code: 0, data: {} }, { code: 0, data: { id: '' } }, { subcode: 0, data: { id: 'not-acknowledged' } }]) {
expect(() => parseSlQzoneComment(response, options)).toThrow();
}
});
test('rejects either error code without echoing server message text', () => {
expect(() => parseSlQzoneComment({ code: 0, subcode: -9, message: 'private response text' })).toThrow('QQ空间兼容接口拒绝请求 (subcode=-9)');
expect(() => parseSlQzoneComment({ code: '0', commentid: 'ignored' })).toThrow('QQ空间兼容接口拒绝请求');
});
});
@@ -0,0 +1,213 @@
import { describe, expect, it } from 'vitest';
import {
advanceSlQzoneFeedState,
initialSlQzoneFeedState,
parseSlQzoneFeeds,
slQzoneFeedPosition,
type SlQzoneFeedState,
} from '@/napcat-core/data/qzone-snowluma-feeds';
// All payloads here are newly synthesized protocol data, not reference-project fixtures.
function packet (items: unknown[], main: Record<string, unknown> = { hasMoreFeeds: false }): string {
return `_preloadCallback(${JSON.stringify({ code: 0, subcode: 0, data: { main, data: items } })});`;
}
function post (html: string, extra: Record<string, unknown> = {}) {
return { uin: '330003', nickname: '林', abstime: '1800000123', appid: '311', key: 'entry-nine', html, ...extra };
}
function ownHtml (body: string, footer = ''): string {
return `<article class="f-single"><div class="user-pto"><img src="https://example.test/portrait.png"></div><div class="f-item" data-key="entry-nine"><input name="feed_data" data-uin="330003" data-fkey="entry-nine" data-tid="tid-nine">${body}</div>${footer}</article>`;
}
describe('independent SL feed data-literal parsing', () => {
it('accepts the required JS data subset without evaluating it', () => {
const input = '_preloadCallback({code:0,subcode:0,data:{main:{hasMoreFeeds:false},data:[undefined,,{uin:\'330003\',nickname:\'云\\u2601\',abstime:1800000123,appid:\'311\',key:\'entry-nine\',html:\'\\x3Cdiv class="f-item" data-key="entry-nine"\\x3E\\x3Cdiv class="f-info"\\x3E文字 undefined, } )\\x3C/div\\x3E\\x3C/div\\x3E\',},],},});';
const result = parseSlQzoneFeeds(input);
expect(result.has_more).toBe(false);
expect(result.feeds).toHaveLength(1);
expect(result.feeds[0]).toMatchObject({ uin: 330003, nickname: '云☁', time: 1800000123, appid: 311, content: '文字 undefined, } )', content_complete: true });
expect(result.feeds[0]?.html).toContain('<div');
});
it('accepts JSON and recognized complete wrappers, including comments inside data only', () => {
const data = { code: 0, data: { data: [], hasmore: '0' } };
for (const text of [JSON.stringify(data), `_Callback(${JSON.stringify(data)})`, `callback(${JSON.stringify(data)});`, '{/* data-only */code:0,data:{main:{hasMoreFeeds:false},data:[],},}']) {
expect(parseSlQzoneFeeds(text)).toMatchObject({ feeds: [], has_more: false });
}
});
it('does not interpret undefined in strings or as a property name', () => {
const result = parseSlQzoneFeeds('{code:0,data:{main:{hasMoreFeeds:false,undefined:\'ordinary key\',externparam:undefined},data:[{uin:330003,appid:311,key:\'entry-nine\',html:\'undefined\',nickname:\'undefined\',abstime:0}]}}');
expect(result.feeds[0]?.nickname).toBe('undefined');
expect(result.feeds[0]?.html).toBe('undefined');
expect(result.main?.['undefined']).toBe('ordinary key');
expect(result.main).not.toHaveProperty('externparam');
expect(advanceSlQzoneFeedState({ ...initialSlQzoneFeedState(), externparam: 'retained' }, result.main!).externparam).toBe('retained');
});
it.each([
'_preloadCallback({code:0,data:{main:{hasMoreFeeds:false},data:[]}});danger();',
'danger();_preloadCallback({code:0,data:{main:{hasMoreFeeds:false},data:[]}});',
'unknownCallback({code:0,data:{main:{hasMoreFeeds:false},data:[]}});',
'<script>_preloadCallback({code:0,data:{main:{hasMoreFeeds:false},data:[]}});</script>',
'{code:0,data:(function(){throw new Error("private");})()}',
'{code:0,data:{get main(){return {hasMoreFeeds:false}},data:[]}}',
'{code:0,data:{main:{hasMoreFeeds:false},data:[],x:new Date()}}',
'{code:0,data:{main:{hasMoreFeeds:false},data:[],x:Infinity}}',
'{code:0,data:{main:{hasMoreFeeds:false},data:[],x:NaN}}',
'{code:0,data:{main:{hasMoreFeeds:false},data:[],"__proto__":{"polluted":true}}}',
'{code:0,data:{main:{hasMoreFeeds:false},data:[],"constr\\u0075ctor":{}}}',
'{code:0,data:{main:{hasMoreFeeds:false},data:[],x:/regex/}}',
])('rejects executable or unsupported bodies without echoing their text (%#)', (text) => {
let error: unknown;
try {
parseSlQzoneFeeds(text);
} catch (caught) {
error = caught;
}
expect(error).toBeInstanceOf(Error);
expect(String(error)).not.toMatch(/private|danger|polluted|function/);
expect(({} as { polluted?: boolean; }).polluted).toBeUndefined();
});
it('requires explicit numeric success and a recognizable page structure', () => {
for (const body of [
{}, { code: '0', data: { data: [], hasmore: 0 } }, { code: 0, subcode: -1 },
{ code: -7, subcode: 0 }, { code: 0, subcode: '0' },
{ code: 0, data: {} }, { code: 0, data: { data: [] } },
{ code: 0, data: { data: [], main: null } },
{ code: 0, data: { data: [], main: { hasMoreFeeds: 'false' } } },
{ code: 0, data: { data: [], main: { hasMoreFeeds: false, error: 'private failure' } } },
{ code: 0, data: { data: [], hasmore: true } },
]) expect(() => parseSlQzoneFeeds(JSON.stringify(body))).toThrow();
});
it('rejects duplicate root success keys even when quoted or escaped, without rejecting ordinary unknown duplicates', () => {
const data = 'data:{main:{hasMoreFeeds:false},data:[]}';
for (const keys of [
'code:-1,code:0',
'code:-1,"code":0',
'"co\\u0064e":-1,code:0',
'co\\u0064e:-1,code:0',
'code:0,subcode:-9,"sub\\u0063ode":0',
'code:0,subcode:0,subcode:0',
]) expect(() => parseSlQzoneFeeds(`_preloadCallback({${keys},${data}});`)).toThrow();
expect(parseSlQzoneFeeds('{code:0,message:\'old\',message:\'new\',data:{main:{hasMoreFeeds:false,code:-9,code:0},data:[]}}').feeds).toEqual([]);
});
it('uses main.hasMoreFeeds before the legacy fallback and keeps the raw main state', () => {
const main = { hasMoreFeeds: '1', pagenum: '7', externparam: 'sort=chronological&opaque=a%26b', icServerTime: '1800001000' };
const result = parseSlQzoneFeeds(packet([], main));
expect(result).toEqual({ feeds: [], has_more: true, main });
expect(() => parseSlQzoneFeeds(JSON.stringify({ code: 0, data: { main: {}, hasmore: 0, data: [] } }))).toThrow('结束标志');
});
it('bounds input and nesting before passing data to JSON5', () => {
expect(() => parseSlQzoneFeeds(' '.repeat(8 * 1024 * 1024 + 1))).toThrow('过大');
expect(() => parseSlQzoneFeeds(`{code:0,data:${'['.repeat(66)}0${']'.repeat(66)}}`)).toThrow();
expect(() => parseSlQzoneFeeds('{code:0,data:{main:{hasMoreFeeds:false},data:[/* never closed')).toThrow();
expect(() => parseSlQzoneFeeds('{code:0,data:{main:{hasMoreFeeds:false},data:["unterminated]}}')).toThrow();
});
it('rejects malformed real entries rather than dropping them along with padding', () => {
for (const item of [12, 'bad', [], post('', { uin: 'not-a-number' }), post('', { abstime: Number.MAX_SAFE_INTEGER + 1 }), post('', { html: {} }), post('', { key: {} })]) {
expect(() => parseSlQzoneFeeds(packet([null, item]))).toThrow();
}
expect(parseSlQzoneFeeds(packet([null, null])).feeds).toEqual([]);
});
});
describe('independent passive HTML feed projection', () => {
it('extracts own text, matching tid, original images and explicit counters while retaining HTML exactly', () => {
const html = ownHtml('<div class="f-info">测试 &amp; 文字<br>第二行<img alt="[云]" src="https://example.test/face.gif"></div><a class="img-item" data-originurl="//cdn.example.test/full.webp?a=1&amp;b=2"><img src="https://example.test/thumb.webp"></a>', '<div class="f-single-foot"><a class="qz_like_btn_v3" data-likecnt="17">赞</a></div>');
const feed = parseSlQzoneFeeds(packet([post(html, { commentcnt: '6' })])).feeds[0]!;
expect(feed).toEqual({
uin: 330003,
nickname: '林',
time: 1800000123,
appid: 311,
key: 'entry-nine',
html,
tid: 'tid-nine',
content: '测试 & 文字\n第二行[云]',
content_complete: true,
images: ['https://cdn.example.test/full.webp?a=1&b=2'],
like_count: 17,
comment_count: 6,
});
});
it('distinguishes truncated text from hidden complete text without including expand controls', () => {
const partial = ownHtml('<div class="f-info">短内容<a data-cmd="qz_toggle">阅读全文</a></div>');
expect(parseSlQzoneFeeds(packet([post(partial)])).feeds[0]).toMatchObject({ content: '短内容', content_complete: false });
const full = ownHtml('<div class="f-info">短内容<a data-cmd="qz_toggle">展开</a></div><div class="f-info qz_info_complete" style="display:none">完整内容<p>下一段</p><a data-cmd="qz_toggle">收起</a></div>');
expect(parseSlQzoneFeeds(packet([post(full)])).feeds[0]).toMatchObject({ content: '完整内容\n下一段', content_complete: true });
});
it('keeps avatars, comments, repost bodies, scripts and video covers out of the original post', () => {
const html = ownHtml(`<div class="f-info">原帖<script>dangerous()</script></div>
<div class="mod-comments"><div class="f-info">评论内容</div><a class="img-item"><img src="https://example.test/comment.png"></a><a class="qz_like_btn_v3" data-likecnt="9999"></a></div>
<div class="f-item-passive"><div class="f-info">转发正文</div><a class="img-item"><img src="https://example.test/repost.png"></a></div>
<div class="f-ct-video"><a class="img-item"><img src="https://example.test/video-cover.png"></a></div>
<a class="img-item" data-v_itemid="v"><img src="https://example.test/another-cover.png"></a>
<a class="img-item"><img truesrc="https://example.test/photo.png" src="https://example.test/loading.png"></a>`);
const feed = parseSlQzoneFeeds(packet([post(html)])).feeds[0]!;
expect(feed.content).toBe('原帖');
expect(feed.images).toEqual(['https://example.test/photo.png']);
expect(feed.like_count).toBeNull();
});
it('does not derive a mood tid from a feed key, another author or a non-mood app', () => {
const mismatched = ownHtml('<div class="f-info">文字</div>').replace('data-uin="330003"', 'data-uin="440004"');
expect(parseSlQzoneFeeds(packet([post(mismatched)])).feeds[0]?.tid).toBeNull();
expect(parseSlQzoneFeeds(packet([post(ownHtml('<div class="f-info">相册说明</div>'), { appid: 4 })])).feeds[0]?.tid).toBeNull();
const absent = parseSlQzoneFeeds(packet([post('<div class="unrecognized">没有可确认的正文</div>')])).feeds[0]!;
expect(absent).toMatchObject({ tid: null, content: null, content_complete: null, images: null, like_count: null, comment_count: null });
});
it('handles normal void tags/entities and deduplicates images without accepting unsafe URLs', () => {
const html = ownHtml('<div class="f-info"><p>段落一&nbsp;文字</p><p>段落二</p></div><a class="img-item" data-url3="https://example.test/a.png"><img src="https://example.test/ignored.png"></a><a class="img-item"><img src="https://example.test/a.png"></a><a class="img-item" data-originurl="javascript:alert(1)"><img src="data:image/png;base64,AAAA"></a>');
const feed = parseSlQzoneFeeds(packet([post(html, { likecnt: '4', commentcnt: 0 })])).feeds[0]!;
expect(feed.content).toBe('段落一 文字\n\n段落二');
expect(feed.images).toEqual(['https://example.test/a.png']);
expect(feed.like_count).toBe(4);
expect(feed.comment_count).toBe(0);
});
it('declines ambiguous content roots and bounds excessive HTML structure', () => {
const duplicate = '<div class="f-item" data-key="entry-nine"><div class="f-info">A</div></div><div class="f-item" data-key="entry-nine"><div class="f-info">B</div></div>';
expect(parseSlQzoneFeeds(packet([post(duplicate)])).feeds[0]?.content).toBeNull();
expect(() => parseSlQzoneFeeds(packet([post(`<div>${'<span>'.repeat(70)}deep${'</span>'.repeat(70)}</div>`)]))).toThrow('HTML');
expect(() => parseSlQzoneFeeds(packet([post('x'.repeat(2 * 1024 * 1024 + 1))]))).toThrow('HTML过大');
});
});
describe('SL feed server state helpers', () => {
it('uses explicit initial fields and updates only values actually supplied by the server', () => {
const first = initialSlQzoneFeedState();
expect(first).toEqual({ begintime: '0', dayspac: '0', pagenum: '1', aisortEndTime: '0', aisortOffset: '0', aisortBeginTime: '0', aisortNextTime: '0', icServerTime: '0', externparam: '', daylist: '', uinlist: '' });
const next = advanceSlQzoneFeedState(first, { pagenum: '0007', begintime: '1800000000', aisortNextTime: 3, externparam: 'opaque=%26&sort=x', daylist: 'day-a', uinlist: '330003', ignored: 'never put into query state' });
expect(next).toMatchObject({ pagenum: '7', begintime: '1800000000', aisortNextTime: '3', externparam: 'opaque=%26&sort=x', daylist: 'day-a', uinlist: '330003' });
expect(first.pagenum).toBe('1');
const partial = advanceSlQzoneFeedState(next, { externparam: '', daylist: '', uinlist: '', aisortOffset: '8' });
expect(partial).toMatchObject({ pagenum: '7', externparam: next.externparam, daylist: 'day-a', uinlist: '', aisortOffset: '8' });
expect(partial).not.toHaveProperty('ignored');
});
it('does not count clock-only changes or property order as pagination progress', () => {
const state = advanceSlQzoneFeedState(initialSlQzoneFeedState(), { externparam: 'p=2', pagenum: '2' });
const changedClock = advanceSlQzoneFeedState(state, { icServerTime: '1800000123' });
expect(slQzoneFeedPosition(changedClock)).toBe(slQzoneFeedPosition(state));
const reordered = Object.fromEntries(Object.entries(state).reverse()) as unknown as SlQzoneFeedState;
expect(slQzoneFeedPosition(reordered)).toBe(slQzoneFeedPosition(state));
expect(slQzoneFeedPosition(advanceSlQzoneFeedState(state, { externparam: 'p=3' }))).not.toBe(slQzoneFeedPosition(state));
});
it('preserves large digit strings without rounding and rejects unsafe numeric or oversized state', () => {
expect(advanceSlQzoneFeedState(initialSlQzoneFeedState(), { icServerTime: '9007199254740993' }).icServerTime).toBe('9007199254740993');
for (const update of [{ pagenum: 0 }, { pagenum: '-2' }, { dayspac: 1.5 }, { begintime: Number.MAX_SAFE_INTEGER + 1 }, { externparam: {} }, { daylist: 'x'.repeat(32769) }]) {
expect(() => advanceSlQzoneFeedState(initialSlQzoneFeedState(), update)).toThrow();
}
});
});
+225
View File
@@ -0,0 +1,225 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { NTQQQzoneApi } from '@/napcat-core/apis/qzone';
function createApi () {
const core = {
selfInfo: { uin: '10001', uid: 'self-uid', nick: '当前账号' },
apis: {
UserApi: {
getSKey: vi.fn().mockResolvedValue('s'),
getPSkey: vi.fn().mockResolvedValue({ result: 0, domainPskeyMap: new Map([['qzone.qq.com', 'p']]) }),
},
},
};
return { api: new NTQQQzoneApi({} as never, core as never), core };
}
function response (value: Record<string, unknown>): Response {
return new Response(`_Callback(${JSON.stringify(value)});`, { status: 200 });
}
const ownDetail = { code: 0, tid: 'post-tid', uin: '10001', content: ' 原始正文\n ', ugc_right: 1 };
describe('Qzone profile, visibility and blacklist HTTP integration', () => {
let fetchMock: ReturnType<typeof vi.fn<typeof fetch>>;
beforeEach(() => {
fetchMock = vi.fn<typeof fetch>();
vi.stubGlobal('fetch', fetchMock);
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it.each([undefined, '20002'])('reads profile %s using the current account ticket without exposing other fields', async (target) => {
const { api, core } = createApi();
fetchMock.mockResolvedValueOnce(response({ code: 0, data: { spacename: '名称 & +', desc: '空间说明', private_field: 'secret' } }));
await expect(api.getProfile(target)).resolves.toEqual({ name: '名称 & +', description: '空间说明' });
const [rawUrl, options] = fetchMock.mock.calls[0]!;
const url = new URL(String(rawUrl));
expect(url.origin + url.pathname).toBe('https://h5.qzone.qq.com/proxy/domain/base.qzone.qq.com/cgi-bin/user/cgi_userinfo_get_all');
expect(Object.fromEntries(url.searchParams)).toMatchObject({ uin: target ?? '10001', vuin: '10001', fupdate: '1', g_tk: '177685' });
expect(options).toMatchObject({ method: 'GET', redirect: 'error', headers: { Cookie: 'uin=o10001; p_uin=o10001; skey=s; p_skey=p' } });
expect(options?.body).toBeUndefined();
expect(core.apis.UserApi.getPSkey).toHaveBeenCalledExactlyOnceWith(['qzone.qq.com']);
});
it('preserves empty profile values and rejects incomplete data', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ code: 0, data: { spacename: '', desc: '' } }));
await expect(api.getProfile()).resolves.toEqual({ name: '', description: '' });
fetchMock.mockResolvedValueOnce(response({ code: 0, data: { spacename: 'Name' } }));
await expect(api.getProfile()).rejects.toThrow();
});
it.each([
{ patch: { name: '新空间 & +' }, bitmap: '2048', fields: { spacename: '新空间 & +' } },
{ patch: { description: '' }, bitmap: '4096', fields: { desc: '' } },
{ patch: { name: '', description: '第一行\r\n第二行' }, bitmap: '6144', fields: { spacename: '', desc: '第一行\n第二行' } },
])('updates only supplied profile fields (bitmap $bitmap)', async ({ patch, bitmap, fields }) => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ code: 0 }));
await expect(api.setProfile(patch)).resolves.toBeUndefined();
const [rawUrl, options] = fetchMock.mock.calls[0]!;
expect(new URL(String(rawUrl)).pathname).toBe('/proxy/domain/w.qzone.qq.com/cgi-bin/user/cgi_apply_updateuserinfo_new');
expect(options).toMatchObject({ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
expect(Object.fromEntries(new URLSearchParams(options?.body as string))).toEqual({ uin: '10001', pageindex: '3', fupdate: '1', mb: bitmap, ...fields });
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('rejects invalid management arguments before acquiring tickets or making requests', async () => {
const { api, core } = createApi();
await expect(api.getProfile('invalid')).rejects.toThrow();
await expect(api.setProfile({})).rejects.toThrow();
await expect(api.setProfile({ name: [] } as never)).rejects.toThrow();
await expect(api.setMsgRight('post-tid', 2)).rejects.toThrow();
await expect(api.setMsgRight('post-tid', 16, [])).rejects.toThrow();
await expect(api.setMsgRight('post-tid', 128, ['20002', 'bad'])).rejects.toThrow();
await expect(api.setBan('bad')).rejects.toThrow();
await expect(api.setBan('20002', 'false' as never)).rejects.toThrow();
expect(fetchMock).not.toHaveBeenCalled();
expect(core.apis.UserApi.getSKey).not.toHaveBeenCalled();
});
it('reads the complete own post before changing visibility without changing content', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response(ownDetail)).mockResolvedValueOnce(response({ code: 0, subcode: 0, ugc_right: 16 }));
await expect(api.setMsgRight('post-tid', 16, ['20002', '20002', '9007199254740993'])).resolves.toEqual({ ugc_right: 16 });
const detailUrl = new URL(String(fetchMock.mock.calls[0]![0]));
expect(detailUrl.pathname).toBe('/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msgdetail_v6');
expect(Object.fromEntries(detailUrl.searchParams)).toMatchObject({
tid: 'post-tid', uin: '10001', not_trunc_con: '1', need_right: '1', not_adapt_outpic: '1',
});
expect(fetchMock.mock.calls[0]![1]?.method).toBe('GET');
const [updateUrl, options] = fetchMock.mock.calls[1]!;
expect(new URL(String(updateUrl)).pathname).toBe('/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_update');
expect(options?.method).toBe('POST');
const body = new URLSearchParams(options?.body as string);
expect(body.get('con')).toBe(ownDetail.content);
expect(body.get('tid')).toBe('post-tid');
expect(body.get('hostuin')).toBe('10001');
expect(body.get('ugc_right')).toBe('16');
expect(body.get('allow_uins')).toBe('20002|9007199254740993');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it.each([
{ ...ownDetail, tid: 'other-tid' },
{ ...ownDetail, uin: '20002' },
{ code: 0, tid: 'post-tid', content: 'no verified owner' },
{ ...ownDetail, richtype: 1, pic: [{ pic_id: 'unusable' }] },
{ ...ownDetail, richtype: 1, pic: [{ pic_id: 'X, ,L', height: 100, width: 100 }] },
{ ...ownDetail, richtype: 1, pic: [{ pic_id: 'X,A, ', height: 100, width: 100 }] },
{ ...ownDetail, video: [{ video_id: 'not-safe-to-rebuild' }] },
{ code: -3000, subcode: 0, private_message: 'secret' },
])('does not submit a destructive or unverified permission update (%j)', async (detail) => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response(detail));
await expect(api.setMsgRight('post-tid', 64)).rejects.toThrow();
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0]![1]?.method).toBe('GET');
});
it('prevents overlapping writes to the same post and releases the lock afterward', async () => {
const { api } = createApi();
let resolveDetail!: (value: Response) => void;
fetchMock.mockImplementationOnce(() => new Promise(resolve => { resolveDetail = resolve; }));
fetchMock.mockResolvedValueOnce(response({ code: 0 }));
const first = api.setMsgRight('post-tid', 64);
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
await expect(api.setMsgRight('post-tid', 4)).rejects.toThrow('正在修改权限');
resolveDetail(response(ownDetail));
await expect(first).resolves.toEqual({ ugc_right: 64 });
fetchMock.mockResolvedValueOnce(response(ownDetail)).mockResolvedValueOnce(response({ code: 0, ugc_right: '4' }));
await expect(api.setMsgRight('post-tid', 4)).resolves.toEqual({ ugc_right: 4 });
expect(fetchMock).toHaveBeenCalledTimes(4);
});
it('does not write after the active account changes while reading the post', async () => {
const { api, core } = createApi();
fetchMock.mockImplementationOnce(async () => {
core.selfInfo.uin = '20002';
core.selfInfo.uid = 'other-uid';
return response(ownDetail);
});
await expect(api.setMsgRight('post-tid', 64)).rejects.toThrow('QQ账号已切换');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('does not report success when the server echoes a different visibility', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response(ownDetail)).mockResolvedValueOnce(response({ code: 0, ugc_right: 1 }));
await expect(api.setMsgRight('post-tid', 64)).rejects.toThrow('返回权限与请求不一致');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('does not rewrite a post whose response contains malformed UTF-8 content', async () => {
const { api } = createApi();
const bytes = Buffer.concat([
Buffer.from('{"code":0,"tid":"post-tid","uin":"10001","content":"'),
Buffer.from([255]),
Buffer.from('","ugc_right":1}'),
]);
fetchMock.mockResolvedValueOnce(new Response(bytes));
await expect(api.setMsgRight('post-tid', 64)).rejects.toThrow('QQ空间请求失败');
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0]![1]?.method).toBe('GET');
});
it.each([{ enable: undefined, action: '1' }, { enable: true, action: '1' }, { enable: false, action: '2' }])('updates only the current account blacklist (enable=$enable)', async ({ enable, action }) => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(response({ code: 0, subcode: 0 }));
await expect(api.setBan('9007199254740993', enable)).resolves.toBeUndefined();
const [url, options] = fetchMock.mock.calls[0]!;
expect(new URL(String(url)).pathname).toBe('/proxy/domain/w.qzone.qq.com/cgi-bin/right/cgi_black_action_new');
expect(Object.fromEntries(new URLSearchParams(options?.body as string))).toEqual({
uin: '10001', act_uin: '9007199254740993', action, fupdate: '1', qzreferrer: 'https://user.qzone.qq.com/10001/main',
});
});
it.each([
'{}',
'_Callback({"code":0,"subcode":-1,"message":"private-response"});',
'<html>private login page</html>',
'_Callback({"code":0});window.privateSideEffect();',
])('rejects unconfirmed writes without exposing or executing a response (%s)', async (text) => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(new Response(text));
let error: unknown;
try {
await api.setProfile({ name: 'Name' });
} catch (caught) {
error = caught;
}
expect(error).toBeInstanceOf(Error);
expect(String(error)).not.toMatch(/private|window\./);
expect(String(error)).toContain('勿自动重试');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('never replays an ambiguous write or follows a redirect with credentials', async () => {
const { api } = createApi();
fetchMock.mockResolvedValueOnce(new Response('private redirect', { status: 302 }));
await expect(api.setBan('20002')).rejects.toThrow('未能确认结果');
expect(fetchMock.mock.calls[0]![1]?.redirect).toBe('error');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
+302
View File
@@ -0,0 +1,302 @@
import { describe, expect, test } from 'vitest';
import {
buildQzoneBanBody,
buildQzoneProfileBody,
buildQzoneRightBody,
normalizeQzoneRight,
parseQzoneProfile,
parseQzoneWebResponse,
} from '@/napcat-core/data/qzone-web';
describe('Qzone management response parsing', () => {
test.each([
'{"code":0,"subcode":0,"data":{"field":"raw"}}',
'_Callback({"code":0,"subcode":0,"data":{"field":"raw"}});',
'callback({"code":0,"subcode":0,"data":{"field":"raw"}})',
'_preloadCallback({"code":0,"subcode":0,"data":{"field":"raw"}});',
'back({"code":0,"subcode":0,"data":{"field":"raw"}});',
'frameElement.callback({"code":0,"subcode":0,"data":{"field":"raw"}});',
'<script>frameElement.callback({"code":0,"subcode":0,"data":{"field":"raw"}});</script>',
])('parses only an inert known response envelope (%s)', (text) => {
expect(parseQzoneWebResponse(text, true)).toEqual({ code: 0, subcode: 0, data: { field: 'raw' } });
});
test('repairs observed name string fragments without treating a name alone as success', () => {
expect(parseQzoneWebResponse('frameElement.callback({"code":0,"subcode":0,"data":{name:"Ack"}});'))
.toEqual({ code: 0, subcode: 0, data: { name: 'Ack' } });
expect(() => parseQzoneWebResponse('frameElement.callback({name:"Ack"});')).toThrow('成功状态');
expect(parseQzoneWebResponse('callback({"code":0,"data":{name:"Other"}});'))
.toEqual({ code: 0, data: { name: 'Other' } });
expect(parseQzoneWebResponse('frameElement.callback({name:"Ack","code":0,"subcode":0});'))
.toEqual({ name: 'Ack', code: 0, subcode: 0 });
expect(parseQzoneWebResponse('frameElement.callback({"code":0,"data":{name:"Ack","extra":true}});'))
.toEqual({ code: 0, data: { name: 'Ack', extra: true } });
expect(parseQzoneWebResponse('frameElement.callback({name:"Other","code":0});'))
.toEqual({ name: 'Other', code: 0 });
});
test.each([
'{}',
'null',
'[]',
'{"code":"0"}',
'{"code":0,"subcode":null}',
'{"code":-1,"subcode":0}',
'{"code":0,"subcode":-1}',
'{"code":0,"retcode":-1}',
'{"code":-1,"code":0}',
'{"code":-1,"\\u0063ode":0}',
'unknownCallback({"code":0});',
'alert("prefix");callback({"code":0});',
'callback({"code":0});alert("suffix");',
'<html><script>callback({"code":0});</script></html>',
'<html>login</html>',
'<script>{"code":0}</script>',
'<script>alert("prefix");callback({"code":0});</script>',
])('rejects ambiguous, failed or executable wrappers (%s)', (text) => {
expect(() => parseQzoneWebResponse(text)).toThrow();
});
test('requires explicit code=0 for profile routes and never exposes private response text', () => {
expect(parseQzoneWebResponse('{"subcode":0}')).toEqual({ subcode: 0 });
expect(() => parseQzoneWebResponse('{"subcode":0}', true)).toThrow('成功状态');
let error: unknown;
try {
parseQzoneWebResponse('{"code":-3000,"message":"p_skey=private-secret"}');
} catch (value) {
error = value;
}
expect(error).toBeInstanceOf(Error);
expect((error as Error).message).toBe('QQ空间接口拒绝请求 (code=-3000)');
expect((error as Error).message).not.toContain('private-secret');
});
test('preserves exact profile text and does not invent missing fields', () => {
expect(parseQzoneProfile({ code: 0, data: { spacename: '', desc: ' 第一行\n第二行 ', signature: 'not-returned' } }))
.toEqual({ name: '', description: ' 第一行\n第二行 ' });
for (const response of [{}, { code: 0 }, { code: 0, data: {} }, { code: 0, data: { spacename: 1, desc: '' } }]) {
expect(() => parseQzoneProfile(response)).toThrow();
}
});
});
describe('Qzone profile and blacklist form bodies', () => {
test.each([
{ profile: { name: '名称 & +' }, fields: { spacename: '名称 & +' }, bitmap: '2048' },
{ profile: { description: '' }, fields: { desc: '' }, bitmap: '4096' },
{ profile: { name: '', description: '一\r\n二\r' }, fields: { spacename: '', desc: '一\n二' }, bitmap: '6144' },
])('only submits supplied profile fields (%j)', ({ profile, fields, bitmap }) => {
const body = new URLSearchParams(buildQzoneProfileBody('10001', profile));
expect(Object.fromEntries(body)).toEqual({ uin: '10001', pageindex: '3', fupdate: '1', mb: bitmap, ...fields });
expect(body.has('signature')).toBe(false);
});
test('rejects invalid profile input and preserves omitted fields', () => {
expect(() => buildQzoneProfileBody('10001', {})).toThrow();
expect(() => buildQzoneProfileBody('10001', { name: undefined })).toThrow();
expect(() => buildQzoneProfileBody('10001', { name: 'x'.repeat(8193) })).toThrow();
expect(() => buildQzoneProfileBody('10001', { name: 42 } as never)).toThrow();
expect(() => buildQzoneProfileBody('10001', { description: null } as never)).toThrow();
expect(() => buildQzoneProfileBody('invalid', { name: 'space' })).toThrow();
expect(() => buildQzoneProfileBody('10001', { signature: 'not-a-supported-field' } as never)).toThrow();
expect(new URLSearchParams(buildQzoneProfileBody('10001', { name: 'space' })).has('desc')).toBe(false);
});
test('builds ban and unban independently with an exact decimal target', () => {
for (const enable of [true, false]) {
expect(Object.fromEntries(new URLSearchParams(buildQzoneBanBody('10001', '9007199254740993', enable)))).toEqual({
uin: '10001', act_uin: '9007199254740993', action: enable ? '1' : '2', fupdate: '1', qzreferrer: 'https://user.qzone.qq.com/10001/main',
});
}
expect(() => buildQzoneBanBody('10001', 'bad', true)).toThrow();
expect(() => buildQzoneBanBody('10001', '10002', 'false' as never)).toThrow();
});
});
function detail (overrides: Record<string, unknown> = {}): Record<string, unknown> {
return { code: 0, subcode: 0, tid: 'T1', uin: '10001', content: ' original\ntext ', ...overrides };
}
function observedEmptyForwardFields (): Record<string, unknown> {
return { rt_tid: '', rt_uin: 0, rt_con: { conlist: null, content: '' }, rt_source: 0 };
}
describe('Qzone permission update preflight', () => {
test('validates rights and all target IDs without lossy conversion or silent omission', () => {
expect(normalizeQzoneRight(16, ['10002', '10002', '9007199254740993']))
.toEqual({ right: 16, targetUins: ['10002', '9007199254740993'] });
for (const right of [0, 2, 3, 5, 256, NaN, Infinity]) expect(() => normalizeQzoneRight(right)).toThrow();
expect(() => normalizeQzoneRight(16)).toThrow('target_uins');
expect(() => normalizeQzoneRight(128, [])).toThrow('target_uins');
expect(() => normalizeQzoneRight(128, ['10002', 'bad'])).toThrow();
expect(() => normalizeQzoneRight(1, [10002] as never)).toThrow();
});
test('rebuilds pure text with exact content, ownership, defaults and selective visibility', () => {
const body = new URLSearchParams(buildQzoneRightBody(detail(), '10001', 'T1', 128, ['10002', '10002']));
expect(Object.fromEntries(body)).toEqual({
syn_tweet_verson: '1',
tid: 'T1',
paramstr: '1',
pic_template: '',
richtype: '',
richval: '',
special_url: '',
subrichtype: '',
pic_bo: '',
con: ' original\ntext ',
feedversion: '1',
ver: '1',
ugc_right: '128',
to_sign: '0',
ugcright_id: 'T1',
hostuin: '10001',
code_version: '1',
format: 'fs',
qzreferrer: 'https://user.qzone.qq.com/10001',
allow_uins: '10002',
});
expect(new URLSearchParams(buildQzoneRightBody(detail(), '10001', 'T1', 64, ['10002'])).has('allow_uins')).toBe(false);
expect(new URLSearchParams(buildQzoneRightBody(detail({ richtype: '', subrichtype: '' }), '10001', 'T1', 4)).get('richtype')).toBe('');
});
test('accepts the observed plain-text forward placeholder and retains subtype 2', () => {
const value = detail({ ...observedEmptyForwardFields(), t1_subtype: 2 });
const body = new URLSearchParams(buildQzoneRightBody(value, '10001', 'T1', 4));
expect(Object.fromEntries(body)).toMatchObject({ con: ' original\ntext ', richtype: '', richval: '', subrichtype: '2' });
expect(value['rt_con']).toEqual({ conlist: null, content: '' });
});
test('accepts the same observed placeholder on complete image posts without dropping image data', () => {
const value = detail({
...observedEmptyForwardFields(),
t1_subtype: 1,
pic: [{ pic_id: ',SYNTHETIC-ALBUM,SYNTHETIC-LOCATION', pictype: 3, height: 96, width: 128, smallurl: 'https://photo.example/a?bo=metadata' }],
});
const body = new URLSearchParams(buildQzoneRightBody(value, '10001', 'T1', 64));
expect(Object.fromEntries(body)).toMatchObject({
con: ' original\ntext ',
richtype: '1',
subrichtype: '1',
richval: ',SYNTHETIC-ALBUM,SYNTHETIC-LOCATION,SYNTHETIC-LOCATION,3,96,128,,0,0',
pic_bo: 'metadata\tmetadata',
});
});
test.each([
{ rt_con: { conlist: null, content: ' ' } },
{ rt_con: { conlist: null, content: 'forwarded text' } },
{ rt_con: { conlist: [], content: '' } },
{ rt_con: { conlist: [{}], content: '' } },
{ rt_con: { content: '' } },
{ rt_con: { conlist: null } },
{ rt_con: { conlist: null, content: '', unknown: 0 } },
{ rt_con: [{ conlist: null, content: '' }] },
{ rt_con: 'nonempty' },
{ rt_tid: 'forwarded' },
{ rt_uin: 10002 },
{ rt_source: 1 },
{ rt_tid: undefined },
{ rt_uin: '0' },
{ rt_source: undefined },
{ video: { vid: 'video-id' } },
{ music: { url: 'https://music.example/song' } },
{ forward: { tid: 'forwarded' } },
{ origin: { tid: 'original' } },
])('does not generalize the observed empty forward object to other content (%j)', (overrides) => {
const value = detail({ ...observedEmptyForwardFields(), t1_subtype: 1, ...overrides });
expect(() => buildQzoneRightBody(value, '10001', 'T1', 4)).toThrow('媒体或转发内容');
});
test.each([
{ pic: [{ pic_id: ',ALBUM,LOCATION', pictype: 3, height: 96, width: 128 }] },
{ richtype: 1 },
{ richtype: 2 },
{ richtype: '' },
{ subrichtype: 2 },
{ t1_subtype: 9 },
{ rt_con: undefined },
])('restricts subtype 2 to the observed ordinary text layout (%j)', (overrides) => {
const value = detail({ ...observedEmptyForwardFields(), t1_subtype: 2, ...overrides });
expect(() => buildQzoneRightBody(value, '10001', 'T1', 4)).toThrow();
});
test('preserves all conlist segments including whitespace instead of using a truncated summary', () => {
const value = detail({ content: 'summary', conlist: [{ con: ' \nfirst' }, { con: ' ' }, { con: 'last\n ' }] });
expect(new URLSearchParams(buildQzoneRightBody(value, '10001', 'T1', 4)).get('con')).toBe(' \nfirst last\n ');
expect(new URLSearchParams(buildQzoneRightBody(detail({ content: '' }), '10001', 'T1', 4)).get('con')).toBe('');
expect(() => buildQzoneRightBody(detail({ conlist: [{ con: 'kept' }, {}] }), '10001', 'T1', 4)).toThrow('分段不完整');
expect(() => buildQzoneRightBody(detail({ content: undefined }), '10001', 'T1', 4)).toThrow('完整正文');
});
test('preserves image order, complete richvals, bo alignment and version metadata', () => {
const value = detail({
conlist: [{ con: 'image text' }],
richtype: 1,
t1_subtype: 1,
pic_template: 'template',
feedversion: 3,
ver: '2',
code_version: 5,
to_sign: 1,
ugcright_id: 'right-key',
pic: [
{ pic_id: 'X,ALBUM1,LLOC1,extra', pictype: 22, height: 800, width: 600, url1: 'https://photo.example/a?bo=abc%2Cdef' },
{ pic_id: 'X,ALBUM2,LLOC2,extra', type: '23', b_height: '400', b_width: '300', smallurl: 'https://photo.example/b?bo=second' },
],
});
const body = new URLSearchParams(buildQzoneRightBody(value, '10001', 'T1', 64));
expect(body.get('richval')).toBe(',ALBUM1,LLOC1,LLOC1,22,800,600,,0,0\t,ALBUM2,LLOC2,LLOC2,23,400,300,,0,0');
expect(body.get('pic_bo')).toBe('abc,def,second\tabc,def,second');
expect(Object.fromEntries(body)).toMatchObject({ con: 'image text', pic_template: 'template', feedversion: '3', ver: '2', code_version: '5', to_sign: '1', ugcright_id: 'right-key' });
expect(value['ugc_right']).toBeUndefined();
});
test.each([
{ pic: [{ pic_id: 'X,A,L', height: 100, width: 100 }, {}], richtype: 1 },
{ pic: [{ pic_id: 'broken' }], richtype: 1 },
{ pic: [{ pic_id: 'X, ,L', height: 100, width: 100 }], richtype: 1 },
{ pic: [{ pic_id: 'X,A, ', height: 100, width: 100 }], richtype: 1 },
{ pic: [], richtype: 1 },
{ pic: [{ pic_id: 'X,A,L' }], richtype: 0 },
{ pic: [{ pic_id: 'X,A,L', height: 'unknown', width: 100 }], richtype: 1 },
{ pic: [{ pic_id: 'X,A,L', height: null, b_height: 100, width: 100 }], richtype: 1 },
{ pic: [{ pic_id: 'X,A,L', height: 100, width: 100, url1: 'https://photo.example/a?bo=one' }, { pic_id: 'X,A,L2', height: 100, width: 100 }], richtype: 1 },
{ pic: [{ pic_id: 'X,A,L', height: 100, width: 100, url1: 'https://photo.example/a?bo=%GG' }], richtype: 1 },
{ richval: 'unknown-media' },
{ richtype: 2 },
{ t1_subtype: 9 },
{ video: { vid: 'video-id' } },
{ music: { url: 'https://music.example/song' } },
{ rt_tid: 'forwarded-tid' },
{ special_url: 'https://example.com/shared' },
])('rejects incomplete or unsupported media instead of partially resubmitting it (%j)', (overrides) => {
expect(() => buildQzoneRightBody(detail(overrides), '10001', 'T1', 64)).toThrow();
});
test('requires every existing image to retain positive known dimensions', () => {
for (const picture of [
{ pic_id: 'X,A,L', width: 100 },
{ pic_id: 'X,A,L', height: 100 },
{ pic_id: 'X,A,L', height: 0, width: 100 },
{ pic_id: 'X,A,L', height: 100, width: '0' },
]) {
expect(() => buildQzoneRightBody(detail({ richtype: 1, pic: [picture] }), '10001', 'T1', 64)).toThrow();
}
expect(() => buildQzoneRightBody(detail({
richtype: 1,
pic: [
{ pic_id: 'X,A,L1', height: 100, width: 100 },
{ pic_id: 'X,A,L2', width: 100 },
],
}), '10001', 'T1', 64)).toThrow('尺寸不完整');
});
test('requires the exact requested tid and current-account owner before returning a body', () => {
expect(() => buildQzoneRightBody(detail({ tid: 'other-tid' }), '10001', 'T1', 64)).toThrow('不匹配');
expect(() => buildQzoneRightBody(detail({ uin: '10002' }), '10001', 'T1', 64)).toThrow('自己的说说');
expect(() => buildQzoneRightBody(detail({ uin: undefined }), '10001', 'T1', 64)).toThrow('自己的说说');
expect(() => buildQzoneRightBody(detail({ code: -1, subcode: 0 }), '10001', 'T1', 64)).toThrow();
expect(new URLSearchParams(buildQzoneRightBody(detail({ uin: 10001 }), '10001', 'T1', 4)).get('hostuin')).toBe('10001');
});
});