feat(onebot): add public Qzone feeds and interactions (#587)

Add public Qzone discovery, pagination, and interactions with SDK and MCP support.
This commit is contained in:
Qiao authored and GitHub committed 2026-10-25 23:20:14 +08:00
1 parent 1ff2c08765
commit 2f1aadffbe
20 files changed
+4997 -6

No files matched your search

+120 -2
View File
@@ -1,3 +1,4 @@
import type { JsonObject } from '@snowluma/common/json';
import {
commentQzoneMsg,
deleteQzoneMsg,
@@ -23,11 +24,29 @@ import {
type QzoneUpdateRightResult,
type QzoneUploadImageResult,
} from '@snowluma/protocol/web/qzone';
import {
getQzonePublicCapabilities,
getQzonePublicFeeds,
getQzonePublicFeedDetail,
getQzonePublicComments,
getQzonePublicReplies,
setQzonePublicUpvote,
setQzonePublicLike,
setQzonePublicCommentLike,
commentQzonePublicFeed,
replyQzonePublicFeed,
deleteQzonePublicComment,
deleteQzonePublicReply,
setQzonePublicFollow,
forwardQzonePublicFeed,
type QzonePublicContent,
type QzonePublicFeedsPage,
} from '@snowluma/protocol/web/qzone-public';
import type { BridgeContext } from '../bridge-context';
/**
* Personal QQ-Zone (个人空间) web API: 说说 (feed) read/write, likes,
* comments, image upload — all over the cookie-backed qzone.qq.com CGIs,
* Personal QQ-Zone (个人空间) web API: 说说, public recommendations, likes,
* comments and image upload over the cookie-backed Qzone web interfaces,
* reusing the same `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi.
* Distinct from the group-album surface, which lives on GroupAlbumApi.
*/
@@ -44,6 +63,105 @@ export class QzoneApi {
await setQzoneProfile(cookieObject, this.ctx.identity.uin, profile);
}
async getPublicCapabilities(): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzonePublicCapabilities(cookies, this.ctx.identity.uin);
}
async getPublicFeeds(cursor?: string): Promise<QzonePublicFeedsPage> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzonePublicFeeds(cookies, this.ctx.identity.uin, cursor);
}
async getPublicFeedDetail(feed: JsonObject): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzonePublicFeedDetail(cookies, feed);
}
async getPublicComments(feed: JsonObject, cursor: string): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzonePublicComments(cookies, feed, cursor);
}
async getPublicReplies(
feed: JsonObject,
comment: JsonObject,
cursor = '',
pageSize = 20,
): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzonePublicReplies(cookies, feed, comment, cursor, pageSize);
}
async setPublicUpvote(feed: JsonObject, enable = true): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return setQzonePublicUpvote(cookies, feed, enable);
}
async setPublicLike(feed: JsonObject, enable = true): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return setQzonePublicLike(cookies, feed, enable);
}
async setPublicCommentLike(
feed: JsonObject,
comment: JsonObject,
enable = true,
reply?: JsonObject,
): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return setQzonePublicCommentLike(cookies, feed, comment, enable, reply);
}
async commentPublicFeed(feed: JsonObject, content: QzonePublicContent): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
const user = {
uin: this.ctx.identity.uin,
uid: this.ctx.identity.selfUid ?? '',
nick: this.ctx.identity.nickname,
};
return commentQzonePublicFeed(cookies, feed, user, content);
}
async replyPublicFeed(
feed: JsonObject,
comment: JsonObject,
content: QzonePublicContent,
reply?: JsonObject,
): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
const user = {
uin: this.ctx.identity.uin,
uid: this.ctx.identity.selfUid ?? '',
nick: this.ctx.identity.nickname,
};
return replyQzonePublicFeed(cookies, feed, user, comment, content, reply);
}
async deletePublicComment(feed: JsonObject, comment: JsonObject): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return deleteQzonePublicComment(cookies, feed, comment);
}
async deletePublicReply(
feed: JsonObject,
comment: JsonObject,
reply: JsonObject,
): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return deleteQzonePublicReply(cookies, feed, comment, reply);
}
async setPublicFollow(feed: JsonObject, enable = true): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return setQzonePublicFollow(cookies, feed, enable);
}
async forwardPublicFeed(feed: JsonObject, reason = ''): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return forwardQzonePublicFeed(cookies, feed, reason);
}
/**
* 获取说说列表。`targetUin` 省略时取机器人自己的空间。
* `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。
@@ -0,0 +1,173 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import * as qzonePublic from '@snowluma/protocol/web/qzone-public';
import { QzoneApi } from '../../src/bridge/apis/qzone';
import { mockApiHub, mockBridge } from './_helpers';
const cookies = { p_skey: 'PSK' };
const feed = {
cell_common: { union_id: { feed_id: 'opaque-id' } },
cell_feed_transfer: { future: true },
};
const comment = { id: 'comment-id', user: { uid: 'commenter' }, unknown: [1, 2] };
const reply = { id: 'reply-id', user: { uid: 'recipient' } };
const content = [{ type: 0, content: 'text', future: { enabled: true } }];
const user = { uin: '10001', uid: 'self-uid', nick: 'self-nick' };
const result = { feeds: [], has_more: false, next_cursor: null, unknown: { preserved: true } };
function makeApi() {
const getCookies = vi.fn().mockResolvedValue(cookies);
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
return { api: new QzoneApi(bridge as never), bridge, getCookies };
}
const cases = [
{
method: 'getQzonePublicCapabilities',
invoke: (api: QzoneApi) => api.getPublicCapabilities(),
args: [cookies, '10001'],
},
{
method: 'getQzonePublicFeeds',
invoke: (api: QzoneApi) => api.getPublicFeeds('cursor'),
args: [cookies, '10001', 'cursor'],
},
{
method: 'getQzonePublicFeedDetail',
invoke: (api: QzoneApi) => api.getPublicFeedDetail(feed),
args: [cookies, feed],
},
{
method: 'getQzonePublicComments',
invoke: (api: QzoneApi) => api.getPublicComments(feed, 'cursor'),
args: [cookies, feed, 'cursor'],
},
{
method: 'getQzonePublicReplies',
invoke: (api: QzoneApi) => api.getPublicReplies(feed, comment, 'cursor', 5),
args: [cookies, feed, comment, 'cursor', 5],
},
{
method: 'setQzonePublicUpvote',
invoke: (api: QzoneApi) => api.setPublicUpvote(feed, false),
args: [cookies, feed, false],
},
{
method: 'setQzonePublicLike',
invoke: (api: QzoneApi) => api.setPublicLike(feed, false),
args: [cookies, feed, false],
},
{
method: 'setQzonePublicCommentLike',
invoke: (api: QzoneApi) => api.setPublicCommentLike(feed, comment, false, reply),
args: [cookies, feed, comment, false, reply],
},
{
method: 'commentQzonePublicFeed',
invoke: (api: QzoneApi) => api.commentPublicFeed(feed, content),
args: [cookies, feed, user, content],
},
{
method: 'replyQzonePublicFeed',
invoke: (api: QzoneApi) => api.replyPublicFeed(feed, comment, content, reply),
args: [cookies, feed, user, comment, content, reply],
},
{
method: 'deleteQzonePublicComment',
invoke: (api: QzoneApi) => api.deletePublicComment(feed, comment),
args: [cookies, feed, comment],
},
{
method: 'deleteQzonePublicReply',
invoke: (api: QzoneApi) => api.deletePublicReply(feed, comment, reply),
args: [cookies, feed, comment, reply],
},
{
method: 'setQzonePublicFollow',
invoke: (api: QzoneApi) => api.setPublicFollow(feed, false),
args: [cookies, feed, false],
},
{
method: 'forwardQzonePublicFeed',
invoke: (api: QzoneApi) => api.forwardPublicFeed(feed, 'reason'),
args: [cookies, feed, 'reason'],
},
] as const;
describe('apis/qzone public', () => {
afterEach(() => vi.restoreAllMocks());
it.each(cases)(
'$method uses current-account cookies and preserves upstream objects',
async ({ method, invoke, args }) => {
const { api, getCookies } = makeApi();
const request = vi.spyOn(qzonePublic, method).mockResolvedValue(result);
expect(await invoke(api)).toBe(result);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(request).toHaveBeenCalledExactlyOnceWith(...args);
},
);
it.each(cases)(
'$method propagates cookie and upstream failures without replay',
async ({ method, invoke }) => {
const { api, getCookies } = makeApi();
const request = vi
.spyOn(qzonePublic, method)
.mockRejectedValue(new Error('upstream denied'));
await expect(invoke(api)).rejects.toThrow('upstream denied');
getCookies.mockRejectedValueOnce(new Error('cookie failure'));
await expect(invoke(api)).rejects.toThrow('cookie failure');
expect(request).toHaveBeenCalledTimes(1);
},
);
it('keeps documented defaults and omits an optional reply target', async () => {
const { api } = makeApi();
const feeds = vi.spyOn(qzonePublic, 'getQzonePublicFeeds').mockResolvedValue(result);
const replies = vi.spyOn(qzonePublic, 'getQzonePublicReplies').mockResolvedValue(result);
const upvote = vi.spyOn(qzonePublic, 'setQzonePublicUpvote').mockResolvedValue(result);
const like = vi.spyOn(qzonePublic, 'setQzonePublicLike').mockResolvedValue(result);
const commentLike = vi
.spyOn(qzonePublic, 'setQzonePublicCommentLike')
.mockResolvedValue(result);
const follow = vi.spyOn(qzonePublic, 'setQzonePublicFollow').mockResolvedValue(result);
const forward = vi.spyOn(qzonePublic, 'forwardQzonePublicFeed').mockResolvedValue(result);
const replyRequest = vi
.spyOn(qzonePublic, 'replyQzonePublicFeed')
.mockResolvedValue(result);
await api.getPublicFeeds();
await api.getPublicReplies(feed, comment);
await api.setPublicUpvote(feed);
await api.setPublicLike(feed);
await api.setPublicCommentLike(feed, comment);
await api.setPublicFollow(feed);
await api.forwardPublicFeed(feed);
await api.replyPublicFeed(feed, comment, 'text');
expect(feeds).toHaveBeenCalledWith(cookies, '10001', undefined);
expect(replies).toHaveBeenCalledWith(cookies, feed, comment, '', 20);
expect(upvote).toHaveBeenCalledWith(cookies, feed, true);
expect(like).toHaveBeenCalledWith(cookies, feed, true);
expect(commentLike).toHaveBeenCalledWith(cookies, feed, comment, true, undefined);
expect(follow).toHaveBeenCalledWith(cookies, feed, true);
expect(forward).toHaveBeenCalledWith(cookies, feed, '');
expect(replyRequest).toHaveBeenCalledWith(cookies, feed, user, comment, 'text', undefined);
});
it('binds comment authors to the current account even when its uid is unavailable', async () => {
const { api, bridge } = makeApi();
Object.assign(bridge.identity, { selfUid: undefined });
const request = vi.spyOn(qzonePublic, 'commentQzonePublicFeed').mockResolvedValue(result);
await api.commentPublicFeed(feed, 'text');
expect(request).toHaveBeenCalledWith(
cookies,
feed,
{ uin: '10001', uid: '', nick: 'self-nick' },
'text',
);
});
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+14
View File
@@ -491,6 +491,20 @@ export const f = {
{ type: 'bool', required: true, schema: { type: 'boolean' } },
);
},
/** JSON object, preserving unknown fields without coercing scalars or arrays. */
object(): Field<JsonObject> {
return new FieldImpl<JsonObject>(
(raw, field) =>
typeof raw === 'object' && raw !== null && !Array.isArray(raw)
? ok(raw)
: err(field, 'expected an object'),
{
type: 'object',
required: true,
schema: { type: 'object', additionalProperties: true },
},
);
},
/** OneBot message union: string | segment[] | object. A string that looks
* like a JSON array is parsed (matches legacy `asMessage`); otherwise the
* value passes through. Output stays `JsonValue` — downstream ctx.* accept it. */
+2 -1
View File
@@ -18,6 +18,7 @@ import { actions as requestActions } from './request';
import { actions as extendedActions } from './extended';
import { actions as groupAlbumActions } from './group-album';
import { actions as qzoneActions } from './qzone';
import { actions as qzonePublicActions } from './qzone-public';
import { actions as streamFileActions } from './stream-file';
import { actions as streamDownloadActions } from './stream-download';
import { actions as systemFaceActions } from './system-face';
@@ -295,7 +296,7 @@ export const ACTION_GROUPS: readonly ActionGroup[] = [
{ category: '请求', actions: requestActions },
{ category: '扩展', actions: extendedActions },
{ category: '群相册', actions: groupAlbumActions },
{ category: '空间', actions: qzoneActions },
{ category: '空间', actions: [...qzoneActions, ...qzonePublicActions] },
{ category: '系统表情', actions: systemFaceActions },
{ category: '流式接口', actions: [...streamFileActions, ...streamDownloadActions] },
];
+372
View File
@@ -0,0 +1,372 @@
import { defineAction, f } from '../action-kit';
import { okResponse, type JsonObject, type JsonValue } from '../types';
const feed = f
.object()
.describe('get_qzone_public_feeds 返回的完整 feeds 条目,保留所有原始 cell 字段');
const comment = f.object().describe('详情或评论页返回的完整评论对象,保留 user 等原始字段');
const reply = f.object().describe('评论或回复页返回的完整回复对象,保留 user 等原始字段');
const content = f.message().describe('非空文本,或非空上游 RichItem 对象数组;不是 OneBot 消息段');
const objectResult = { type: 'object', additionalProperties: true };
const feedSource =
'feed 必须原样取自 get_qzone_public_feeds 的 feeds 数组,不能用旧说说 tid 拼造;示例中的占位字段须整体替换。';
const commentSource =
'comment 可取 get_qzone_public_feed_detail 返回的 feed.feed.cell_comment.comments,或后续评论页;保留完整对象。';
const feedExample: JsonObject = {
cell_common: {
union_id: {
uf_key: '<uf_key-from-get_qzone_public_feeds>',
ugc_id: '<ugc_id>',
feed_id: '<feed_id>',
ext_ids: [],
},
cur_like_key: '<like-key>',
domain_type: 3,
},
cell_feed_transfer: {},
cell_user_info: { user: { uin: '10001', uid: '<uid>', nick: '<nick>' } },
};
const commentExample: JsonObject = {
id: '<comment-id-from-detail-or-comments>',
user: { uin: '<uin>', uid: '<uid>', nick: '<nick>' },
like: { id: '<like-id-from-comment>', count: 0, status: 0 },
reply_attach_info: '',
};
const replyExample: JsonObject = {
id: '<reply-id-from-comments-or-replies>',
user: { uin: '<uin>', uid: '<uid>', nick: '<nick>' },
like: { id: '<like-id-from-reply>', count: 0, status: 0 },
};
function validContent(value: JsonValue): value is string | JsonObject[] {
return typeof value === 'string'
? value.length > 0
: Array.isArray(value) &&
value.length > 0 &&
value.every(
(item) => typeof item === 'object' && item !== null && !Array.isArray(item),
);
}
export const actions = [
defineAction({
name: 'get_qzone_public_capabilities',
summary: '读取当前账号的空友爱看入口与推权限',
readOnly: true,
examples: [{ summary: '查询当前账号是否有空友爱看入口及推能力', params: {} }],
returns: '当前账号的上游入口能力对象,保留未知字段。',
returnsSchema: objectResult,
params: {},
run: async (_p, ctx) => okResponse(await ctx.bridge.apis.qzone.getPublicCapabilities()),
}),
defineAction({
name: 'get_qzone_public_feeds',
summary: '读取空友爱看推荐动态,支持独立游标分页',
readOnly: true,
examples: [
{ summary: '读取空友爱看推荐首页', params: {} },
{
summary: '继续读取推荐动态',
params: { cursor: '<next_cursor-from-get_qzone_public_feeds>' },
notes: 'cursor 原样使用上次返回的 next_cursor,仅适用于同一账号;has_more=false 时停止。',
},
],
returns: '推荐动态原始 cell 对象及分页状态,保留其余上游页面字段。',
returnsSchema: {
type: 'object',
additionalProperties: true,
properties: {
feeds: {
type: 'array',
items: objectResult,
description: '原始动态 cell 对象,后续详情和互动需原样传入',
},
has_more: { type: 'boolean', description: '服务端是否报告还有下一页' },
next_cursor: {
type: ['string', 'null'],
description: '下一页游标;无下一页时为 null',
},
},
required: ['feeds', 'has_more', 'next_cursor'],
},
params: {
cursor: f
.string({ allowEmpty: false, maxLen: 65536 })
.describe('上次返回的 next_cursor,省略则刷新首页')
.optional(),
},
run: async (p, ctx) => okResponse(await ctx.bridge.apis.qzone.getPublicFeeds(p.cursor)),
}),
defineAction({
name: 'get_qzone_public_feed_detail',
summary: '读取推荐动态详情及初始评论',
readOnly: true,
examples: [
{ summary: '读取推荐动态详情', params: { feed: feedExample }, notes: feedSource },
],
returns:
'上游详情 data;初始评论位于 feed.feed.cell_comment.comments,续页使用 attach_info。',
returnsSchema: objectResult,
params: { feed },
run: async (p, ctx) => okResponse(await ctx.bridge.apis.qzone.getPublicFeedDetail(p.feed)),
}),
defineAction({
name: 'get_qzone_public_comments',
summary: '继续读取推荐动态评论',
readOnly: true,
examples: [
{
summary: '读取详情之后的下一页评论',
params: { feed: feedExample, cursor: '<attach_info-from-detail-or-comments>' },
notes: `${feedSource} 先读详情获取初始评论及 attach_info,再原样传入 cursor。`,
},
],
returns: '上游评论页对象,保留评论、分页和未知字段。',
returnsSchema: objectResult,
params: {
feed,
cursor: f.string({ allowEmpty: false }).describe('详情或上一评论页返回的 attach_info'),
},
run: async (p, ctx) =>
okResponse(await ctx.bridge.apis.qzone.getPublicComments(p.feed, p.cursor)),
}),
defineAction({
name: 'get_qzone_public_replies',
summary: '继续读取指定评论的回复',
readOnly: true,
examples: [
{
summary: '读取某条评论的后续回复',
params: { feed: feedExample, comment: commentExample },
notes: `${feedSource} ${commentSource} 首次续读使用评论自带的 reply_attach_info;之后传上一回复页的游标。`,
},
],
returns: '上游回复页对象,保留回复、分页和未知字段。',
returnsSchema: objectResult,
params: {
feed,
comment,
cursor: f
.string()
.describe('上一回复页的 reply_attach_info;省略则使用评论自带游标')
.default(''),
page_size: f.int({ min: 1 }).describe('请求的回复数量').default(20),
},
run: async (p, ctx) =>
okResponse(
await ctx.bridge.apis.qzone.getPublicReplies(
p.feed,
p.comment,
p.cursor,
p.page_size,
),
),
}),
defineAction({
name: 'set_qzone_public_upvote',
summary: '推或取消推空友爱看动态(独立于普通赞)',
readOnly: false,
examples: [
{
summary: '推一条推荐动态',
params: { feed: feedExample, enable: true },
notes: feedSource,
},
],
returns: '上游推操作结果,保留未知字段。',
returnsSchema: objectResult,
params: { feed, enable: f.bool().describe('true 推,false 取消推').default(true) },
run: async (p, ctx) =>
okResponse(await ctx.bridge.apis.qzone.setPublicUpvote(p.feed, p.enable)),
}),
defineAction({
name: 'set_qzone_public_like',
summary: '点赞或取消赞推荐动态',
readOnly: false,
examples: [
{
summary: '点赞推荐动态',
params: { feed: feedExample, enable: true },
notes: feedSource,
},
],
returns: '上游普通赞操作结果,保留未知字段。',
returnsSchema: objectResult,
params: { feed, enable: f.bool().describe('true 点赞,false 取消赞').default(true) },
run: async (p, ctx) =>
okResponse(await ctx.bridge.apis.qzone.setPublicLike(p.feed, p.enable)),
}),
defineAction({
name: 'set_qzone_public_comment_like',
summary: '点赞或取消赞推荐动态中的评论或回复',
readOnly: false,
examples: [
{
summary: '点赞一条评论',
params: { feed: feedExample, comment: commentExample },
notes: `${feedSource} ${commentSource} 必须保留评论原始 like.id。`,
},
{
summary: '取消赞某条回复',
params: {
feed: feedExample,
comment: commentExample,
reply: replyExample,
enable: false,
},
notes: `${feedSource} reply 使用该评论下的完整回复对象,保留其原始 like.id。`,
},
],
returns: '上游普通赞操作结果,保留未知字段。',
returnsSchema: objectResult,
params: {
feed,
comment,
enable: f.bool().describe('true 点赞,false 取消赞').default(true),
reply: reply.optional(),
},
run: async (p, ctx) =>
okResponse(
await ctx.bridge.apis.qzone.setPublicCommentLike(
p.feed,
p.comment,
p.enable,
p.reply,
),
),
}),
defineAction({
name: 'comment_qzone_public_feed',
summary: '评论推荐动态,支持文本或上游富文本条目',
readOnly: false,
examples: [
{
summary: '评论推荐动态',
params: { feed: feedExample, content: '感谢分享' },
notes: feedSource,
},
],
returns: '上游评论结果,包含新评论,保留未知字段。',
returnsSchema: objectResult,
params: { feed, content },
rules: (r) => [
r.rule('content must be non-empty text or a non-empty array of RichItem objects', (p) =>
validContent(p.content),
),
],
run: async (p, ctx) =>
okResponse(
await ctx.bridge.apis.qzone.commentPublicFeed(
p.feed,
p.content as string | JsonObject[],
),
),
}),
defineAction({
name: 'reply_qzone_public_feed',
summary: '回复推荐动态的评论或其中某条回复',
readOnly: false,
examples: [
{
summary: '回复一条评论',
params: { feed: feedExample, comment: commentExample, content: '感谢回复' },
notes: `${feedSource} ${commentSource}`,
},
{
summary: '回复评论中的某条回复',
params: {
feed: feedExample,
comment: commentExample,
content: [{ type: 0, content: '我也这么认为' }],
reply: replyExample,
},
notes: `${feedSource} ${commentSource} reply 使用该评论下的完整回复对象。`,
},
],
returns: '上游回复结果,包含新回复,保留未知字段。',
returnsSchema: objectResult,
params: { feed, comment, content, reply: reply.optional() },
rules: (r) => [
r.rule('content must be non-empty text or a non-empty array of RichItem objects', (p) =>
validContent(p.content),
),
],
run: async (p, ctx) =>
okResponse(
await ctx.bridge.apis.qzone.replyPublicFeed(
p.feed,
p.comment,
p.content as string | JsonObject[],
p.reply,
),
),
}),
defineAction({
name: 'delete_qzone_public_comment',
summary: '删除推荐动态的一条评论(需有权限)',
readOnly: false,
examples: [
{
summary: '删除一条评论',
params: { feed: feedExample, comment: commentExample },
notes: `${feedSource} ${commentSource}`,
},
],
returns: '上游删除结果,保留未知字段。',
returnsSchema: objectResult,
params: { feed, comment },
run: async (p, ctx) =>
okResponse(await ctx.bridge.apis.qzone.deletePublicComment(p.feed, p.comment)),
}),
defineAction({
name: 'delete_qzone_public_reply',
summary: '删除推荐动态评论下的一条回复(需有权限)',
readOnly: false,
examples: [
{
summary: '删除一条回复',
params: { feed: feedExample, comment: commentExample, reply: replyExample },
notes: `${feedSource} ${commentSource} reply 使用该评论下的完整回复对象。`,
},
],
returns: '上游删除结果,保留未知字段。',
returnsSchema: objectResult,
params: { feed, comment, reply },
run: async (p, ctx) =>
okResponse(await ctx.bridge.apis.qzone.deletePublicReply(p.feed, p.comment, p.reply)),
}),
defineAction({
name: 'set_qzone_public_follow',
summary: '蹲或取消蹲推荐动态作者',
readOnly: false,
examples: [
{
summary: '蹲这条推荐动态的作者',
params: { feed: feedExample, enable: true },
notes: `${feedSource} feed 需保留作者 cell_user_info。`,
},
],
returns: '上游关系操作结果,保留未知字段。',
returnsSchema: objectResult,
params: { feed, enable: f.bool().describe('true 蹲,false 取消蹲').default(true) },
run: async (p, ctx) =>
okResponse(await ctx.bridge.apis.qzone.setPublicFollow(p.feed, p.enable)),
}),
defineAction({
name: 'forward_qzone_public_feed',
summary: '将推荐动态转发到当前账号空间',
readOnly: false,
examples: [
{
summary: '转发推荐动态到我的空间',
params: { feed: feedExample, reason: '分享这条动态' },
notes: `${feedSource} 只转发,不同时评论或发送给 QQ 联系人。`,
},
],
returns: '上游转发结果,保留未知字段。',
returnsSchema: objectResult,
params: { feed, reason: f.string().describe('转发附言,可为空').default('') },
run: async (p, ctx) =>
okResponse(await ctx.bridge.apis.qzone.forwardPublicFeed(p.feed, p.reason)),
}),
];
+29
View File
@@ -114,6 +114,35 @@ describe('f.array(...).nonEmpty — per-element + non-empty', () => {
});
});
describe('f.object — open JSON object', () => {
const spec = defineAction({
name: 't',
params: { value: f.object() },
run: () => okResponse(),
});
it('preserves nested and unknown fields', () => {
const value = { identity: { id: 'opaque' }, future: [1, null, { enabled: true }] };
expect(expectOk(spec.parse({ value })).value).toBe(value);
expect(f.object().toJsonSchema()).toEqual({ type: 'object', additionalProperties: true });
});
it.each([null, [], 'text', 1, false])('rejects non-object %j', (value) => {
expect(expectErr(spec.parse({ value })).field).toBe('value');
});
it('uses the normal required and optional field policies', () => {
expect(expectErr(spec.parse({})).reason).toBe('is required');
const optional = defineAction({
name: 't',
params: { value: f.object().optional() },
run: () => okResponse(),
});
expect(expectOk(optional.parse({}))).toEqual({ value: undefined });
expect(expectErr(optional.parse({ value: null })).field).toBe('value');
});
});
describe('f.message — union passthrough + JSON-array string', () => {
const spec = defineAction({ name: 't', params: { m: f.message() }, run: () => okResponse() });
it('parses a JSON-array string, passes plain string / array through', () => {
@@ -0,0 +1,326 @@
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import { ACTION_GROUPS } from '../src/actions';
import { actions } from '../src/actions/qzone-public';
import type { JsonObject } from '../src/types';
const feed = {
cell_common: {
union_id: { feed_id: 'opaque-id', ext_ids: [{ future: true }] },
cur_like_key: 'like-key',
},
cell_feed_transfer: { opaque: [1, 'token'] },
cell_future: { kept: true },
};
const comment = {
id: 'comment-id',
user: { uid: 'commenter' },
reply_attach_info: 'comment-cursor',
};
const reply = { id: 'reply-id', user: { uid: 'recipient' }, future: true };
const result = { unknown: { preserved: [1, 2] } };
function makeHandler(qzone: Record<string, unknown>): ApiHandler {
const bridge = { apis: { qzone } } as unknown as BridgeInterface;
return new ApiHandler({ bridge } as ApiActionContext);
}
const cases: {
action: string;
method: string;
params: JsonObject;
args: unknown[];
readOnly: boolean;
}[] = [
{
action: 'get_qzone_public_capabilities',
method: 'getPublicCapabilities',
params: {},
args: [],
readOnly: true,
},
{
action: 'get_qzone_public_feeds',
method: 'getPublicFeeds',
params: {},
args: [undefined],
readOnly: true,
},
{
action: 'get_qzone_public_feed_detail',
method: 'getPublicFeedDetail',
params: { feed },
args: [feed],
readOnly: true,
},
{
action: 'get_qzone_public_comments',
method: 'getPublicComments',
params: { feed, cursor: 'comments-cursor' },
args: [feed, 'comments-cursor'],
readOnly: true,
},
{
action: 'get_qzone_public_replies',
method: 'getPublicReplies',
params: { feed, comment },
args: [feed, comment, '', 20],
readOnly: true,
},
{
action: 'set_qzone_public_upvote',
method: 'setPublicUpvote',
params: { feed },
args: [feed, true],
readOnly: false,
},
{
action: 'set_qzone_public_like',
method: 'setPublicLike',
params: { feed },
args: [feed, true],
readOnly: false,
},
{
action: 'set_qzone_public_comment_like',
method: 'setPublicCommentLike',
params: { feed, comment },
args: [feed, comment, true, undefined],
readOnly: false,
},
{
action: 'comment_qzone_public_feed',
method: 'commentPublicFeed',
params: { feed, content: 'hello' },
args: [feed, 'hello'],
readOnly: false,
},
{
action: 'reply_qzone_public_feed',
method: 'replyPublicFeed',
params: { feed, comment, content: 'reply' },
args: [feed, comment, 'reply', undefined],
readOnly: false,
},
{
action: 'delete_qzone_public_comment',
method: 'deletePublicComment',
params: { feed, comment },
args: [feed, comment],
readOnly: false,
},
{
action: 'delete_qzone_public_reply',
method: 'deletePublicReply',
params: { feed, comment, reply },
args: [feed, comment, reply],
readOnly: false,
},
{
action: 'set_qzone_public_follow',
method: 'setPublicFollow',
params: { feed },
args: [feed, true],
readOnly: false,
},
{
action: 'forward_qzone_public_feed',
method: 'forwardPublicFeed',
params: { feed },
args: [feed, ''],
readOnly: false,
},
];
describe('qzone public actions', () => {
it.each(cases)(
'$action preserves upstream objects and applies documented defaults',
async ({ action, method, params, args }) => {
const invoke = vi.fn().mockResolvedValue(result);
expect(await makeHandler({ [method]: invoke }).handle(action, params)).toMatchObject({
status: 'ok',
retcode: 0,
data: result,
});
expect(invoke).toHaveBeenCalledExactlyOnceWith(...args);
},
);
it('registers all public actions under the existing space category with valid examples and read/write modes', () => {
const registered = ACTION_GROUPS.find((group) => group.category === '空间')!.actions;
expect(actions).toHaveLength(cases.length);
for (const { action, readOnly } of cases) {
const spec = actions.find((entry) => entry.names.includes(action))!;
const doc = spec.describe();
expect(registered).toContain(spec);
expect(doc.readOnly).toBe(readOnly);
expect(doc.returnsSchema).toBeDefined();
expect(doc.examples!.length).toBeGreaterThan(0);
for (const example of doc.examples!) {
expect(spec.parse(example.params)).toMatchObject({ ok: true });
}
}
});
it('keeps list metadata and explicit cursor values intact', async () => {
const page = {
feeds: [feed],
has_more: true,
next_cursor: 'next-cursor',
server_metadata: { future: 1 },
};
const getPublicFeeds = vi.fn().mockResolvedValue(page);
expect(
await makeHandler({ getPublicFeeds }).handle('get_qzone_public_feeds', {
cursor: 'current-cursor',
}),
).toMatchObject({ status: 'ok', data: page });
expect(getPublicFeeds).toHaveBeenCalledWith('current-cursor');
});
it.each(['set_qzone_public_upvote', 'set_qzone_public_like', 'set_qzone_public_follow'])(
'%s accepts false without replacing it with the true default',
async (action) => {
const { method } = cases.find((entry) => entry.action === action)!;
const invoke = vi.fn().mockResolvedValue(result);
await makeHandler({ [method]: invoke }).handle(action, { feed, enable: 'false' });
expect(invoke).toHaveBeenCalledWith(feed, false);
},
);
it('normalizes query-string reply pagination and preserves the parent object', async () => {
const getPublicReplies = vi.fn().mockResolvedValue(result);
await makeHandler({ getPublicReplies }).handle('get_qzone_public_replies', {
feed,
comment,
cursor: 'reply-cursor',
page_size: '5',
});
expect(getPublicReplies).toHaveBeenCalledWith(feed, comment, 'reply-cursor', 5);
});
it('routes a reply unlike with its original target and parent context', async () => {
const setPublicCommentLike = vi.fn().mockResolvedValue(result);
const originalReply = { ...reply, like: { id: 'reply-like-key', future: true } };
await makeHandler({ setPublicCommentLike }).handle('set_qzone_public_comment_like', {
feed,
comment,
reply: originalReply,
enable: 'false',
});
expect(setPublicCommentLike).toHaveBeenCalledExactlyOnceWith(
feed,
comment,
false,
originalReply,
);
});
it.each(['comment_qzone_public_feed', 'reply_qzone_public_feed'])(
'%s preserves every rich item and optional reply recipient',
async (action) => {
const { method } = cases.find((entry) => entry.action === action)!;
const invoke = vi.fn().mockResolvedValue(result);
const rich = [
{ type: 0, content: 'hello', future: { unknown: true } },
{ type: 1, unknown: [1, 2] },
];
const params = { feed, comment, content: rich, reply };
await makeHandler({ [method]: invoke }).handle(action, params);
expect(invoke).toHaveBeenCalledWith(
...(action === 'comment_qzone_public_feed'
? [feed, rich]
: [feed, comment, rich, reply]),
);
},
);
it('accepts a JSON-array string through the existing message coercer', async () => {
const commentPublicFeed = vi.fn().mockResolvedValue(result);
await makeHandler({ commentPublicFeed }).handle('comment_qzone_public_feed', {
feed,
content: '[{"type":0,"content":"hello"}]',
});
expect(commentPublicFeed).toHaveBeenCalledWith(feed, [{ type: 0, content: 'hello' }]);
});
it.each(['comment_qzone_public_feed', 'reply_qzone_public_feed'])(
'%s rejects missing, empty, scalar or mixed content without effects',
async (action) => {
const { method } = cases.find((entry) => entry.action === action)!;
const invoke = vi.fn();
const handler = makeHandler({ [method]: invoke });
const invalid: JsonObject[] = [
{},
{ content: '' },
{ content: [] },
{ content: 1 },
{ content: null },
{ content: {} },
{ content: [{ type: 0 }, null] },
{ content: [{ type: 0 }, 'invalid'] },
];
for (const params of invalid) {
expect(await handler.handle(action, { feed, comment, ...params })).toMatchObject({
status: 'failed',
retcode: 1400,
});
}
expect(invoke).not.toHaveBeenCalled();
},
);
it.each([
{ action: 'get_qzone_public_feeds', params: { cursor: '' } },
{ action: 'get_qzone_public_feeds', params: { cursor: 'a'.repeat(65537) } },
{ action: 'get_qzone_public_feed_detail', params: {} },
{ action: 'get_qzone_public_feed_detail', params: { feed: [] } },
{ action: 'get_qzone_public_comments', params: { feed } },
{ action: 'get_qzone_public_comments', params: { feed, cursor: '' } },
{ action: 'get_qzone_public_replies', params: { feed, comment: null } },
{ action: 'get_qzone_public_replies', params: { feed, comment, page_size: 0 } },
{ action: 'delete_qzone_public_comment', params: { feed } },
{ action: 'set_qzone_public_comment_like', params: { feed } },
{ action: 'set_qzone_public_comment_like', params: { feed, comment, reply: [] } },
{ action: 'delete_qzone_public_reply', params: { feed, comment, reply: 'bad' } },
{
action: 'reply_qzone_public_feed',
params: { feed, comment, content: 'reply', reply: [] },
},
])('$action rejects invalid parameters before dispatch', async ({ action, params }) => {
const { method } = cases.find((entry) => entry.action === action)!;
const invoke = vi.fn();
expect(
await makeHandler({ [method]: invoke }).handle(action, params as JsonObject),
).toMatchObject({ status: 'failed', retcode: 1400 });
expect(invoke).not.toHaveBeenCalled();
});
it.each(['get_qzone_public_feed_detail', 'set_qzone_public_upvote'])(
'%s exposes upstream errors without retry',
async (action) => {
const { method, params } = cases.find((entry) => entry.action === action)!;
const invoke = vi.fn().mockRejectedValue(new Error('public qzone denied'));
expect(await makeHandler({ [method]: invoke }).handle(action, params)).toMatchObject({
status: 'failed',
wording: 'public qzone denied',
});
expect(invoke).toHaveBeenCalledTimes(1);
},
);
});
@@ -4,10 +4,19 @@ import { actions as extended } from '../src/actions/extended';
import { actions as albums } from '../src/actions/group-album';
import { actions as groupAdmin } from '../src/actions/group-admin';
import { actions as qzone } from '../src/actions/qzone';
import { actions as qzonePublic } from '../src/actions/qzone-public';
import { actions as streamDownload } from '../src/actions/stream-download';
import { actions as streamFile } from '../src/actions/stream-file';
const actions = [...extended, ...albums, ...groupAdmin, ...qzone, ...streamDownload, ...streamFile];
const actions = [
...extended,
...albums,
...groupAdmin,
...qzone,
...qzonePublic,
...streamDownload,
...streamFile,
];
const examples = Object.entries(actionParams).filter(
([name]) => name !== '.handle_quick_operation_async',
);
+455
View File
@@ -0,0 +1,455 @@
import type { JsonObject } from '@snowluma/common/json';
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
export type QzonePublicContent = string | JsonObject[];
export interface QzonePublicFeedsPage extends JsonObject {
feeds: JsonObject[];
has_more: boolean;
next_cursor: string | null;
}
interface PublicFeedCursor {
version: 1;
uin: string;
refresh_id: string;
attach_info: string;
last_client_feed_union_id: JsonObject | null;
}
const reader = 'trpc.qzone.feeds_reader.FeedsReader';
const interaction = 'trpc.qzone.interaction_writer.InteractionWriter';
const upvote = 'trpc.public_qzone.interaction.UFOComment';
const relation = 'trpc.public_qzone.relation.RelationService';
function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
async function request(
cookies: Record<string, string>,
service: string,
method: string,
oidb: string,
params: JsonObject,
): Promise<JsonObject> {
const [command, serviceType] = oidb.split('_');
const result = await RequestUtil.HttpGetJson<unknown>(
`https://h5.qzone.qq.com/http2rpc/gotrpc/v1/${service}/${method}?g_tk=${getBknFromCookie(cookies)}`,
'POST',
params,
{
Cookie: cookieToString(cookies),
'Content-Type': 'application/json',
Referer: 'https://h5.qzone.qq.com/pc-qzone/index.html',
'x-web-qua': 'V1_HT5_QZ_9.9.32_001_IDC_B',
'x-oidb': JSON.stringify({
uint32_command: command,
uint32_service_type: serviceType,
}),
},
);
if (!isObject(result) || result.retcode !== 0 || !isObject(result.data)) {
const code = isObject(result) ? result.retcode : 'invalid response';
const message =
isObject(result) && typeof result.message === 'string' ? result.message : '';
throw new Error(`qzone public ${method} failed: retcode=${code} ${message}`.trim());
}
return result.data;
}
function feedParams(feed: JsonObject): JsonObject {
const common = feed.cell_common;
if (!isObject(common) || !isObject(common.union_id) || !Object.keys(common.union_id).length) {
throw new Error('空友动态缺少 cell_common.union_id,请使用推荐列表或详情返回的完整动态');
}
return {
union_id: common.union_id,
...(feed.cell_feed_transfer === undefined
? {}
: { cell_feed_transfer: feed.cell_feed_transfer }),
};
}
function encodeCursor(state: PublicFeedCursor): string {
const cursor = Buffer.from(JSON.stringify(state)).toString('base64url');
if (cursor.length > 65_536) {
throw new Error('空友推荐分页游标过大');
}
return cursor;
}
function decodeCursor(cursor: string, uin: string): PublicFeedCursor {
if (!cursor || cursor.length > 65_536 || !/^[A-Za-z0-9_-]+$/.test(cursor)) {
throw new Error('无效的空友推荐 cursor');
}
let value: unknown;
try {
const bytes = Buffer.from(cursor, 'base64url');
if (bytes.toString('base64url') !== cursor) {
throw new Error('non-canonical encoding');
}
value = JSON.parse(bytes.toString('utf8'));
} catch {
throw new Error('无效的空友推荐 cursor');
}
if (
!isObject(value) ||
value.version !== 1 ||
value.uin !== uin ||
typeof value.refresh_id !== 'string' ||
!value.refresh_id ||
typeof value.attach_info !== 'string' ||
!(value.last_client_feed_union_id === null || isObject(value.last_client_feed_union_id))
) {
throw new Error('空友推荐 cursor 无效或不属于当前账号');
}
return {
version: 1,
uin,
refresh_id: value.refresh_id,
attach_info: value.attach_info,
last_client_feed_union_id: value.last_client_feed_union_id,
};
}
export async function getQzonePublicCapabilities(
cookies: Record<string, string>,
selfUin: string,
): Promise<JsonObject> {
const data = await request(
cookies,
'trpc.public_qzone.entrance_ctrl.EntranceCtrl',
'BatchEntranceWhitelist',
'0x9741_0',
{
uins: [selfUin],
entrance_types: [1, 15],
},
);
const result = Array.isArray(data.results)
? data.results.find((entry) => isObject(entry) && String(entry.uin) === selfUin)
: undefined;
if (!isObject(result) || !isObject(result.entrances)) {
throw new Error('qzone public BatchEntranceWhitelist 缺少当前账号的 entrances');
}
return result.entrances;
}
export async function getQzonePublicFeeds(
cookies: Record<string, string>,
selfUin: string,
cursor?: string,
): Promise<QzonePublicFeedsPage> {
const state: PublicFeedCursor =
cursor === undefined
? {
version: 1,
uin: selfUin,
refresh_id: `${selfUin}_${Date.now()}`,
attach_info: '',
last_client_feed_union_id: null,
}
: decodeCursor(cursor, selfUin);
const data = await request(cookies, reader, 'GetPublicRecomFeeds', '0x9a38_0', {
refresh_id: state.refresh_id,
...(cursor === undefined
? {}
: {
attach_info: state.attach_info,
...(state.last_client_feed_union_id === null
? {}
: { last_client_feed_union_id: state.last_client_feed_union_id }),
}),
});
if (!Array.isArray(data.feeds) || typeof data.has_more !== 'boolean') {
throw new Error('qzone public GetPublicRecomFeeds 分页响应异常');
}
const feeds = data.feeds.map((entry) => {
if (!isObject(entry) || !isObject(entry.feed)) {
throw new Error('qzone public GetPublicRecomFeeds 动态响应异常');
}
return entry.feed;
});
let lastUnion = state.last_client_feed_union_id;
// The web client carries the last non-ad feed across pages, including ad-only pages.
for (const feed of feeds) {
const common = feed.cell_common;
if (isObject(common) && common.feed_type !== 3 && isObject(common.union_id)) {
lastUnion = common.union_id;
}
}
let nextCursor: string | null = null;
if (data.has_more) {
if (typeof data.attach_info !== 'string') {
throw new Error('qzone public GetPublicRecomFeeds 缺少 attach_info');
}
nextCursor = encodeCursor({
...state,
attach_info: data.attach_info,
last_client_feed_union_id: lastUnion,
});
}
return { ...data, feeds, has_more: data.has_more, next_cursor: nextCursor };
}
export function getQzonePublicFeedDetail(
cookies: Record<string, string>,
feed: JsonObject,
): Promise<JsonObject> {
return request(cookies, reader, 'GetFeedDetail', '0x97b1_1', {
...feedParams(feed),
feed_action_domain_type: 3,
from_page: 1,
});
}
export function getQzonePublicComments(
cookies: Record<string, string>,
feed: JsonObject,
cursor: string,
): Promise<JsonObject> {
return request(cookies, reader, 'GetComment', '0x9bfd_1', {
...feedParams(feed),
attach_info: cursor,
});
}
export function getQzonePublicReplies(
cookies: Record<string, string>,
feed: JsonObject,
comment: JsonObject,
cursor: string,
pageSize: number,
): Promise<JsonObject> {
return request(cookies, reader, 'GetReplies', '0x9bfe_1', {
...feedParams(feed),
cur_comment: comment,
comment_attach_info: '',
reply_attach_info: cursor || comment.reply_attach_info || '',
page_size: pageSize,
});
}
export async function setQzonePublicUpvote(
cookies: Record<string, string>,
feed: JsonObject,
enable: boolean,
): Promise<JsonObject> {
const data = await request(
cookies,
upvote,
enable ? 'Upvote' : 'Downvote',
enable ? '0x9d18_1' : '0x9d19_1',
feedParams(feed),
);
if (!data.upvote) {
throw new Error('qzone public upvote 响应缺少 upvote');
}
return data;
}
async function setLike(
cookies: Record<string, string>,
feed: JsonObject,
likeKey: unknown,
likeType: number,
enable: boolean,
): Promise<JsonObject> {
if (typeof likeKey !== 'string' || !likeKey) {
throw new Error('空友点赞目标缺少 like_key');
}
const data = await request(
cookies,
interaction,
enable ? 'DoLike' : 'UnLike',
enable ? '0x9699_1' : '0x969c_1',
{
...feedParams(feed),
like_key: likeKey,
like_type: likeType,
},
);
if (!data.like) {
throw new Error('qzone public like 响应缺少 like');
}
return data;
}
export function setQzonePublicLike(
cookies: Record<string, string>,
feed: JsonObject,
enable: boolean,
): Promise<JsonObject> {
const common = feed.cell_common;
return setLike(cookies, feed, isObject(common) ? common.cur_like_key : undefined, 1, enable);
}
export function setQzonePublicCommentLike(
cookies: Record<string, string>,
feed: JsonObject,
comment: JsonObject,
enable: boolean,
reply?: JsonObject,
): Promise<JsonObject> {
const like = (reply ?? comment).like;
return setLike(cookies, feed, isObject(like) ? like.id : undefined, reply ? 3 : 2, enable);
}
function richContent(content: QzonePublicContent): JsonObject[] {
return typeof content === 'string' ? [{ type: 0, content }] : content;
}
export async function commentQzonePublicFeed(
cookies: Record<string, string>,
feed: JsonObject,
user: JsonObject,
content: QzonePublicContent,
): Promise<JsonObject> {
const data = await request(cookies, interaction, 'AddComment', '0x9676_1', {
...feedParams(feed),
comment: { user, content: richContent(content) },
});
if (!data.comment) {
throw new Error('qzone public AddComment 响应缺少 comment');
}
return data;
}
export async function replyQzonePublicFeed(
cookies: Record<string, string>,
feed: JsonObject,
user: JsonObject,
comment: JsonObject,
content: QzonePublicContent,
reply?: JsonObject,
): Promise<JsonObject> {
const targetUser = reply?.user ?? comment.user;
if (!isObject(targetUser)) {
throw new Error('空友评论或回复缺少 user');
}
const data = await request(cookies, interaction, 'AddReply', '0x9677_1', {
...feedParams(feed),
comment,
reply: { content: richContent(content), target_user: targetUser, user },
});
if (!data.reply) {
throw new Error('qzone public AddReply 响应缺少 reply');
}
return data;
}
export function deleteQzonePublicComment(
cookies: Record<string, string>,
feed: JsonObject,
comment: JsonObject,
): Promise<JsonObject> {
return request(cookies, interaction, 'DeleteComment', '0x9989_0', {
...feedParams(feed),
comment,
});
}
export function deleteQzonePublicReply(
cookies: Record<string, string>,
feed: JsonObject,
comment: JsonObject,
reply: JsonObject,
): Promise<JsonObject> {
return request(cookies, interaction, 'DeleteReply', '0x998a_0', {
...feedParams(feed),
comment,
reply,
});
}
export async function setQzonePublicFollow(
cookies: Record<string, string>,
feed: JsonObject,
enable: boolean,
): Promise<JsonObject> {
const params = feedParams(feed);
const common = feed.cell_common as JsonObject;
const user = isObject(feed.cell_user_info) ? feed.cell_user_info.user : undefined;
const uid = isObject(user) && typeof user.uid === 'string' ? user.uid.trim() : '';
const uin = isObject(user) && typeof user.uin === 'string' ? user.uin.trim() : '';
const useUid = (common.domain_type === 3 && !!uid) || !uin;
if (useUid ? !uid : !uin) {
throw new Error('空友动态缺少作者 uid/uin');
}
const union = params.union_id as JsonObject;
const data = await request(
cookies,
relation,
enable ? 'Follow' : 'Unfollow',
enable ? '0x9d1a_1' : '0x9d1b_1',
{
follow_from_type: 1,
...(useUid ? { target_uid: uid } : { target_uin: uin }),
...(union.uf_key ? { follow_feed_id: union.uf_key } : {}),
...(feed.cell_feed_transfer === undefined
? {}
: { cell_feed_transfer: feed.cell_feed_transfer }),
},
);
if (
data.ret_code !== undefined &&
data.ret_code !== null &&
data.ret_code !== 0 &&
data.ret_code !== '0'
) {
throw new Error(
`qzone public follow failed: ret_code=${data.ret_code} ${data.ret_msg ?? ''}`.trim(),
);
}
return data;
}
export function forwardQzonePublicFeed(
cookies: Record<string, string>,
feed: JsonObject,
reason: string,
): Promise<JsonObject> {
return request(cookies, 'trpc.qzone.feeds_writer.FeedsWriter', 'ForwardFeed', '0x969a_1', {
...feedParams(feed),
reason,
});
}
@@ -0,0 +1,341 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { JsonObject } from '@snowluma/common/json';
import * as qzone from '@snowluma/protocol/web/qzone-public';
import { RequestUtil, getBknFromCookie } from '@snowluma/protocol/web/request-util';
const cookies = { p_skey: 'test-pskey', uin: 'o10001' };
const union: JsonObject = {
uf_key: 'feed-1',
ugc_id: '9007199254740999',
feed_id: 'feed-id',
ext_ids: [{ numeric: '9007199254740999' }],
};
const feed: JsonObject = {
cell_common: { union_id: union, feed_type: 1, domain_type: 3, cur_like_key: 'like-key' },
cell_feed_transfer: { opaque: 'transfer' },
cell_user_info: { user: { uid: 'author-uid', uin: '20002', nick: '作者' } },
cell_unknown: { keep: true },
};
const user = { uin: '10001', uid: 'self-uid', nick: '我' };
const comment = {
id: 'comment-1',
user: { uin: '20002', uid: 'comment-uid', nick: '' },
reply_attach_info: 'reply-first',
opaque: true,
};
const reply = { id: 'reply-1', user: { uin: '30003', uid: 'reply-uid', nick: '' } };
const baseParams = { union_id: union, cell_feed_transfer: feed.cell_feed_transfer };
function mockRequest(data: JsonObject = {}) {
return vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ retcode: 0, data });
}
function body(request: ReturnType<typeof mockRequest>, index = 0): JsonObject {
return request.mock.calls[index]![2] as JsonObject;
}
afterEach(() => vi.restoreAllMocks());
describe('public Qzone reader', () => {
it('uses the JSON gateway with the current account cookies and the method oidb headers', async () => {
const flags = { public_qzone_entrance_switch: true, can_upvote: true, unknown_flag: false };
const request = mockRequest({
results: [
{ uin: '20002', entrances: {} },
{ uin: '10001', entrances: flags },
],
});
await expect(qzone.getQzonePublicCapabilities(cookies, '10001')).resolves.toEqual(flags);
const [url, method, , headers] = request.mock.calls[0]!;
expect(url).toBe(
`https://h5.qzone.qq.com/http2rpc/gotrpc/v1/trpc.public_qzone.entrance_ctrl.EntranceCtrl/BatchEntranceWhitelist?g_tk=${getBknFromCookie(cookies)}`,
);
expect(method).toBe('POST');
expect(body(request)).toEqual({ uins: ['10001'], entrance_types: [1, 15] });
expect(headers).toEqual({
Cookie: 'p_skey=test-pskey; uin=o10001',
'Content-Type': 'application/json',
Referer: 'https://h5.qzone.qq.com/pc-qzone/index.html',
'x-web-qua': 'V1_HT5_QZ_9.9.32_001_IDC_B',
'x-oidb': JSON.stringify({ uint32_command: '0x9741', uint32_service_type: '0' }),
});
});
it('continues short and ad-only pages using the full last non-ad union and server has_more', async () => {
vi.spyOn(Date, 'now').mockReturnValue(12345);
const ad = { cell_common: { feed_type: 3, union_id: { uf_key: 'ad' } } };
const request = mockRequest()
.mockResolvedValueOnce({
retcode: 0,
data: { feeds: [{ feed }], has_more: true, attach_info: 'page-2', extra: 'keep' },
})
.mockResolvedValueOnce({
retcode: 0,
data: { feeds: [{ feed: ad }], has_more: true, attach_info: 'page-3' },
})
.mockResolvedValueOnce({ retcode: 0, data: { feeds: [], has_more: false } });
const first = await qzone.getQzonePublicFeeds(cookies, '10001');
expect(first).toMatchObject({ feeds: [feed], has_more: true, extra: 'keep' });
expect(body(request)).toEqual({ refresh_id: '10001_12345' });
const second = await qzone.getQzonePublicFeeds(cookies, '10001', first.next_cursor!);
expect(body(request, 1)).toEqual({
refresh_id: '10001_12345',
attach_info: 'page-2',
last_client_feed_union_id: union,
});
const last = await qzone.getQzonePublicFeeds(cookies, '10001', second.next_cursor!);
expect(body(request, 2)).toEqual({
refresh_id: '10001_12345',
attach_info: 'page-3',
last_client_feed_union_id: union,
});
expect(last).toEqual({ feeds: [], has_more: false, next_cursor: null });
expect(request).toHaveBeenCalledTimes(3);
});
it('preserves unknown feed cells without using them as pagination anchors', async () => {
const unknown = { cell_common: { feed_type: 4 }, cell_unknown: { keep: true } };
const request = mockRequest({
feeds: [{ feed }, { feed: unknown }],
has_more: true,
attach_info: 'next',
});
const first = await qzone.getQzonePublicFeeds(cookies, '10001');
expect(first.feeds).toEqual([feed, unknown]);
request.mockResolvedValueOnce({
retcode: 0,
data: { feeds: [{ feed: unknown }], has_more: true, attach_info: 'after-unknown' },
});
const next = await qzone.getQzonePublicFeeds(cookies, '10001', first.next_cursor!);
request.mockResolvedValueOnce({ retcode: 0, data: { feeds: [], has_more: false } });
await qzone.getQzonePublicFeeds(cookies, '10001', next.next_cursor!);
expect(body(request, 2).last_client_feed_union_id).toEqual(union);
});
it('rejects malformed or cross-account cursors before a network request', async () => {
const request = mockRequest({ feeds: [{ feed }], has_more: true, attach_info: 'next' });
const first = await qzone.getQzonePublicFeeds(cookies, '10001');
request.mockClear();
for (const cursor of [
'',
'!',
'a'.repeat(65537),
Buffer.from('{}').toString('base64url'),
first.next_cursor!,
]) {
await expect(qzone.getQzonePublicFeeds(cookies, '20002', cursor)).rejects.toThrow(
/cursor/,
);
}
expect(request).not.toHaveBeenCalled();
});
it.each([
{ feeds: [], has_more: true },
{ feeds: [{ feed: null }], has_more: false },
{ feeds: null, has_more: false },
{ feeds: [], has_more: 1 },
])('reports invalid upstream page data (%j)', async (data) => {
mockRequest(data);
await expect(qzone.getQzonePublicFeeds(cookies, '10001')).rejects.toThrow(
/GetPublicRecomFeeds/,
);
});
it('preserves detail/comment/reply result fields and forwards their separate pagination state', async () => {
const detail = {
feed: { feed: { ...feed, cell_comment: { comments: [comment] } } },
attach_info: 'comments-next',
has_more: true,
};
const request = mockRequest(detail);
await expect(qzone.getQzonePublicFeedDetail(cookies, feed)).resolves.toEqual(detail);
expect(body(request)).toEqual({ ...baseParams, feed_action_domain_type: 3, from_page: 1 });
request.mockResolvedValueOnce({
retcode: 0,
data: {
cell_comment: { comments: [comment] },
attach_info: 'comments-end',
has_more: false,
},
});
await qzone.getQzonePublicComments(cookies, feed, 'comments-next');
expect(body(request, 1)).toEqual({ ...baseParams, attach_info: 'comments-next' });
request.mockResolvedValue({
retcode: 0,
data: { replys: [reply], reply_attach_info: 'reply-next', has_more: true },
});
await qzone.getQzonePublicReplies(cookies, feed, comment, '', 20);
expect(body(request, 2)).toEqual({
...baseParams,
cur_comment: comment,
comment_attach_info: '',
reply_attach_info: 'reply-first',
page_size: 20,
});
await qzone.getQzonePublicReplies(cookies, feed, comment, 'reply-next', 5);
expect(body(request, 3).reply_attach_info).toBe('reply-next');
});
});
describe('public Qzone interactions', () => {
it.each([
[true, 'Upvote', '0x9d18', qzone.setQzonePublicUpvote, { upvote: { num: 1 } }],
[false, 'Downvote', '0x9d19', qzone.setQzonePublicUpvote, { upvote: { num: 0 } }],
[true, 'DoLike', '0x9699', qzone.setQzonePublicLike, { like: { num: 1 } }],
[false, 'UnLike', '0x969c', qzone.setQzonePublicLike, { like: { num: 0 } }],
] as const)(
'sends %s to %s with its own success field',
async (enable, method, command, invoke, result) => {
const request = mockRequest(result);
await expect(invoke(cookies, feed, enable)).resolves.toEqual(result);
expect(request.mock.calls[0]![0]).toContain(`/${method}?`);
expect(JSON.parse(request.mock.calls[0]![3]!['x-oidb']!)).toEqual({
uint32_command: command,
uint32_service_type: '1',
});
expect(body(request)).toEqual(
method.includes('Like')
? { ...baseParams, like_key: 'like-key', like_type: 1 }
: baseParams,
);
},
);
it('encodes text as plain RichItem and retains rich arrays and reply target identities', async () => {
const request = mockRequest({ comment });
await qzone.commentQzonePublicFeed(cookies, feed, user, '中文 & +\n第二行');
expect(body(request)).toEqual({
...baseParams,
comment: { user, content: [{ type: 0, content: '中文 & +\n第二行' }] },
});
const rich = [
{ type: 0, content: '文字' },
{ type: 2, unknown: { keep: true } },
];
request.mockResolvedValue({ retcode: 0, data: { reply } });
await qzone.replyQzonePublicFeed(cookies, feed, user, comment, rich);
expect(body(request, 1)).toEqual({
...baseParams,
comment,
reply: { user, target_user: comment.user, content: rich },
});
await qzone.replyQzonePublicFeed(cookies, feed, user, comment, '回复', reply);
expect((body(request, 2).reply as JsonObject).target_user).toEqual(reply.user);
});
it('likes comments and replies using their upstream like.id rather than comment IDs', async () => {
const request = mockRequest({ like: { count: 1 } });
await qzone.setQzonePublicCommentLike(
cookies,
feed,
{ ...comment, like: { id: 'comment-like-key' } },
true,
);
expect(body(request)).toEqual({
...baseParams,
like_key: 'comment-like-key',
like_type: 2,
});
await qzone.setQzonePublicCommentLike(cookies, feed, comment, false, {
...reply,
like: { id: 'reply-like-key' },
});
expect(body(request, 1)).toEqual({
...baseParams,
like_key: 'reply-like-key',
like_type: 3,
});
await expect(qzone.setQzonePublicCommentLike(cookies, feed, comment, true)).rejects.toThrow(
/like_key/,
);
expect(request).toHaveBeenCalledTimes(2);
});
it('passes complete comment/reply objects for deletion and forwards without a second comment', async () => {
const request = mockRequest({ unknown: 'keep' });
await qzone.deleteQzonePublicComment(cookies, feed, comment);
expect(body(request)).toEqual({ ...baseParams, comment });
await qzone.deleteQzonePublicReply(cookies, feed, comment, reply);
expect(body(request, 1)).toEqual({ ...baseParams, comment, reply });
await qzone.forwardQzonePublicFeed(cookies, feed, '');
expect(body(request, 2)).toEqual({ ...baseParams, reason: '' });
expect(request.mock.calls[2]![0]).toContain(
'/trpc.qzone.feeds_writer.FeedsWriter/ForwardFeed?',
);
expect(request).toHaveBeenCalledTimes(3);
});
it('follows public authors by uid and other authors by uin, exposing nested relation failures', async () => {
const request = mockRequest({ ret_code: '0' });
await qzone.setQzonePublicFollow(cookies, feed, true);
expect(body(request)).toEqual({
follow_from_type: 1,
target_uid: 'author-uid',
follow_feed_id: 'feed-1',
cell_feed_transfer: feed.cell_feed_transfer,
});
const other = {
...feed,
cell_common: { ...(feed.cell_common as JsonObject), domain_type: 1 },
};
await qzone.setQzonePublicFollow(cookies, other, false);
expect(body(request, 1).target_uin).toBe('20002');
expect(request.mock.calls[1]![0]).toContain('/Unfollow?');
request.mockResolvedValueOnce({ retcode: 0, data: { ret_code: 403, ret_msg: 'denied' } });
await expect(qzone.setQzonePublicFollow(cookies, feed, true)).rejects.toThrow(
'ret_code=403 denied',
);
});
it('rejects missing operation identities before writing', async () => {
const request = mockRequest();
expect(() => qzone.forwardQzonePublicFeed(cookies, {}, '')).toThrow(/union_id/);
await expect(
qzone.setQzonePublicLike(cookies, { cell_common: { union_id: union } }, true),
).rejects.toThrow(/like_key/);
await expect(
qzone.setQzonePublicFollow(cookies, { cell_common: { union_id: union } }, true),
).rejects.toThrow(/uid\/uin/);
await expect(qzone.replyQzonePublicFeed(cookies, feed, user, {}, 'text')).rejects.toThrow(
/user/,
);
expect(request).not.toHaveBeenCalled();
});
});
describe('public Qzone errors', () => {
it.each([
null,
{},
{ retcode: 0 },
{ retcode: 0, data: [] },
{ retcode: 4003, message: 'need login' },
])('does not report malformed or failed envelopes as success (%j)', async (response) => {
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue(response);
await expect(qzone.getQzonePublicFeedDetail(cookies, feed)).rejects.toThrow(
/qzone public GetFeedDetail failed/,
);
expect(request).toHaveBeenCalledTimes(1);
});
it('propagates transport errors and does not retry writes or accept missing success fields', async () => {
const request = mockRequest().mockRejectedValueOnce(new Error('connection closed'));
await expect(qzone.commentQzonePublicFeed(cookies, feed, user, 'text')).rejects.toThrow(
'connection closed',
);
await expect(qzone.setQzonePublicLike(cookies, feed, true)).rejects.toThrow(/缺少 like/);
await expect(qzone.setQzonePublicUpvote(cookies, feed, false)).rejects.toThrow(
/缺少 upvote/,
);
await expect(qzone.commentQzonePublicFeed(cookies, feed, user, 'text')).rejects.toThrow(
/缺少 comment/,
);
await expect(
qzone.replyQzonePublicFeed(cookies, feed, user, comment, 'text'),
).rejects.toThrow(/缺少 reply/);
expect(request).toHaveBeenCalledTimes(5);
});
});
+46
View File
@@ -181,6 +181,52 @@ for (const comment of detail.comments) {
分页参数及 `commentlist` / `list_3` 字段参考 [Qzone-API](https://github.com/SmartHypercube/Qzone-API/blob/master/qzone.py)。实际分页和可见内容取决于 QQ 空间服务端。
### 空友爱看与公共空间
公共空间动作使用推荐域 `3` 的 JSON 接口,与上面的旧空间 CGI 动作分开。先读取 `get_qzone_public_feeds`,再把返回的完整 `feed` 对象传给详情和互动动作,保留其中的身份、传递数据及未知字段;不要用旧说说 `tid` 拼造。
| 动作 | 主要参数 |
| --- | --- |
| `get_qzone_public_capabilities` | 无;读取当前账号的入口能力 |
| `get_qzone_public_feeds` | 可选 `cursor` |
| `get_qzone_public_feed_detail` | `feed` |
| `get_qzone_public_comments` | `feed`、`cursor` |
| `get_qzone_public_replies` | `feed`、完整 `comment`,可选 `cursor`、`page_size`(默认 20) |
| `set_qzone_public_upvote` / `set_qzone_public_like` / `set_qzone_public_follow` | `feed`,可选 `enable`(默认 `true`,`false` 取消) |
| `set_qzone_public_comment_like` | `feed`、完整 `comment`,可选完整 `reply`、`enable`(默认 `true`) |
| `comment_qzone_public_feed` | `feed`、`content` |
| `reply_qzone_public_feed` | `feed`、完整 `comment`、`content`,可选完整 `reply` |
| `delete_qzone_public_comment` / `delete_qzone_public_reply` | `feed`、完整 `comment`;删除回复还需完整 `reply` |
| `forward_qzone_public_feed` | `feed`,可选 `reason`(默认空字符串) |
“推”与“赞”是不同的互动,分别使用 `set_qzone_public_upvote` 和 `set_qzone_public_like`。评论或回复的 `content` 接受非空文本或非空的上游富文本对象数组。详情、评论、回复及写操作保留上游结果字段,`raw` 返回这些 JSON 对象;列表的 `feeds` 已去掉上游每项的 `.feed` 包装,其余字段保持开放。
QQ 上游会对评论换行做归一化,返回的富文本保持上游格式。
`set_qzone_public_comment_like` 为评论点赞;提供 `reply` 时改为给该回复点赞,`enable: false` 取消。保留评论或回复自带的 `like.id`,不要将它替换成评论 ID。
```ts
const page = await bot.raw('get_qzone_public_feeds', {});
if (page.has_more && page.next_cursor) {
const next = await bot.raw('get_qzone_public_feeds', { cursor: page.next_cursor });
console.log(next.feeds);
}
const feed = page.feeds[0];
if (feed) {
const detail = await bot.raw('get_qzone_public_feed_detail', { feed });
if (detail.has_more === true && typeof detail.attach_info === 'string') {
const comments = await bot.raw('get_qzone_public_comments', {
feed,
cursor: detail.attach_info,
});
console.log(comments);
}
}
```
列表续页必须原样传回 `next_cursor`,根据 `has_more` 判断结束,不能因本页不足 10 条而停止。详情中的首批评论位于 `feed.feed.cell_comment.comments`;后续评论使用详情或上一评论页的 `attach_info` 作为 `cursor`。读取回复时,首次可省略 `cursor` 使用完整评论自带的 `reply_attach_info`,之后传上一回复页的 `reply_attach_info`。这些游标各有用途,列表游标还绑定当前账号。登录或访问权限失败会抛出 `SnowLumaApiError`。
## Message Builder
```ts
+14
View File
@@ -144,12 +144,15 @@ export const SNOWLUMA_ACTIONS = [
'cancel_group_album_media_like',
'clean_stream_temp_file',
'comment_qzone',
'comment_qzone_public_feed',
'create_flash_task',
'del_group_album_media',
'delete_custom_face',
'delete_flash_file',
'delete_group_tag',
'delete_qzone_msg',
'delete_qzone_public_comment',
'delete_qzone_public_reply',
'do_group_album_comment',
'download_file_image_stream',
'download_file_record_stream',
@@ -162,6 +165,7 @@ export const SNOWLUMA_ACTIONS = [
'get_record_text',
'fetch_super_face_id',
'fetch_sys_faces',
'forward_qzone_public_feed',
'get_doubt_friends_add_request',
'get_fileset_id',
'get_fileset_info',
@@ -180,6 +184,11 @@ export const SNOWLUMA_ACTIONS = [
'get_qzone_msg_detail',
'get_qzone_msg_list',
'get_qzone_profile',
'get_qzone_public_capabilities',
'get_qzone_public_comments',
'get_qzone_public_feed_detail',
'get_qzone_public_feeds',
'get_qzone_public_replies',
'get_rkey_server',
'get_share_link',
'like_qzone',
@@ -187,6 +196,7 @@ export const SNOWLUMA_ACTIONS = [
'modify_custom_face',
'move_custom_face_to_front',
'rename_flash_file',
'reply_qzone_public_feed',
'request_decrypt_key',
'search_sys_faces',
'send_ark_share',
@@ -205,6 +215,10 @@ export const SNOWLUMA_ACTIONS = [
'set_qzone_ban',
'set_qzone_msg_right',
'set_qzone_profile',
'set_qzone_public_comment_like',
'set_qzone_public_follow',
'set_qzone_public_like',
'set_qzone_public_upvote',
'share_group_ex',
'share_peer',
'test_download_stream',
+26
View File
@@ -84,6 +84,7 @@ import type {
ActionUserIdParams,
AddCustomFaceParams,
CommentQzoneParams,
CommentQzonePublicFeedParams,
CreateFlashTaskParams,
CustomFaceIdParams,
DownloadFileStreamParams,
@@ -98,12 +99,22 @@ import type {
GetQzoneFeedsParams,
GetQzoneMsgListParams,
GetQzoneProfileParams,
GetQzonePublicFeedsParams,
GetQzonePublicCommentsParams,
GetQzonePublicRepliesParams,
GroupAlbumCommentParams,
GroupAlbumMediaLikeParams,
GroupAlbumMediaParams,
LikeQzoneParams,
ModifyCustomFaceParams,
QzoneMsgIdParams,
QzonePublicFeedParams,
QzonePublicCommentParams,
QzonePublicReplyParams,
QzonePublicInteractionParams,
SetQzonePublicCommentLikeParams,
ReplyQzonePublicFeedParams,
ForwardQzonePublicFeedParams,
RenameFlashFileParams,
RequestDecryptKeyParams,
SendFlashMsgParams,
@@ -187,6 +198,7 @@ import type {
QzoneMsgListResult,
QzonePublishResult,
QzoneProfileResult,
QzonePublicFeedsPage,
QzoneUpdateRightResult,
RkeyServerResult,
SendFlashMsgResult,
@@ -361,11 +373,14 @@ export interface SnowLumaActionMap {
};
clean_stream_temp_file: { params: JsonObject; data: CleanStreamTempFileResult };
comment_qzone: { params: CommentQzoneParams; data: QzoneCommentResult };
comment_qzone_public_feed: { params: CommentQzonePublicFeedParams; data: JsonObject };
create_flash_task: { params: CreateFlashTaskParams; data: CreateFlashTaskResult };
del_group_album_media: { params: GroupAlbumMediaParams; data: DeleteGroupAlbumMediaResult };
delete_custom_face: { params: CustomFaceIdParams; data: EmptyData };
delete_flash_file: { params: FilesetIdParams; data: EmptyData };
delete_qzone_msg: { params: QzoneMsgIdParams; data: EmptyData };
delete_qzone_public_comment: { params: QzonePublicCommentParams; data: JsonObject };
delete_qzone_public_reply: { params: QzonePublicReplyParams; data: JsonObject };
do_group_album_comment: { params: GroupAlbumCommentParams; data: GroupAlbumCommentResult };
download_file_image_stream: {
params: DownloadFileStreamParams;
@@ -400,6 +415,11 @@ export interface SnowLumaActionMap {
get_qzone_feeds: { params: GetQzoneFeedsParams; data: QzoneFeedsResult };
get_qzone_msg_list: { params: GetQzoneMsgListParams; data: QzoneMsgListResult };
get_qzone_profile: { params: GetQzoneProfileParams; data: QzoneProfileResult };
get_qzone_public_capabilities: { params: JsonObject; data: JsonObject };
get_qzone_public_feeds: { params: GetQzonePublicFeedsParams; data: QzonePublicFeedsPage };
get_qzone_public_feed_detail: { params: QzonePublicFeedParams; data: JsonObject };
get_qzone_public_comments: { params: GetQzonePublicCommentsParams; data: JsonObject };
get_qzone_public_replies: { params: GetQzonePublicRepliesParams; data: JsonObject };
get_rkey_server: { params: JsonObject; data: RkeyServerResult };
get_share_link: { params: FilesetIdParams; data: string };
like_qzone: { params: LikeQzoneParams; data: EmptyData };
@@ -407,6 +427,7 @@ export interface SnowLumaActionMap {
modify_custom_face: { params: ModifyCustomFaceParams; data: EmptyData };
move_custom_face_to_front: { params: CustomFaceIdParams; data: EmptyData };
rename_flash_file: { params: RenameFlashFileParams; data: EmptyData };
reply_qzone_public_feed: { params: ReplyQzonePublicFeedParams; data: JsonObject };
request_decrypt_key: { params: RequestDecryptKeyParams; data: DecryptKeyResult };
send_ark_share: { params: SharePeerParams; data: ArkShareResult };
send_flash_msg: { params: SendFlashMsgParams; data: SendFlashMsgResult };
@@ -428,6 +449,11 @@ export interface SnowLumaActionMap {
set_qzone_ban: { params: SetQzoneBanParams; data: EmptyData };
set_qzone_msg_right: { params: SetQzoneMsgRightParams; data: QzoneUpdateRightResult };
set_qzone_profile: { params: SetQzoneProfileParams; data: EmptyData };
set_qzone_public_upvote: { params: QzonePublicInteractionParams; data: JsonObject };
set_qzone_public_comment_like: { params: SetQzonePublicCommentLikeParams; data: JsonObject };
set_qzone_public_like: { params: QzonePublicInteractionParams; data: JsonObject };
set_qzone_public_follow: { params: QzonePublicInteractionParams; data: JsonObject };
forward_qzone_public_feed: { params: ForwardQzonePublicFeedParams; data: JsonObject };
share_group_ex: { params: ActionGroupIdParams; data: string };
share_peer: { params: SharePeerParams; data: ArkShareResult };
test_download_stream: { params: TestDownloadStreamParams; data: TestDownloadStreamResult };
+60
View File
@@ -589,6 +589,66 @@ export type SetQzoneProfileParams = JsonObject &
| { name?: ActionStringInput; description: ActionStringInput }
);
/** Non-empty text or a non-empty array of upstream rich-text items. */
export type QzonePublicContent = string | JsonObject[];
export interface GetQzonePublicFeedsParams extends JsonObject {
/** Opaque account-bound next_cursor from the previous page. */
cursor?: string;
}
export interface QzonePublicFeedParams extends JsonObject {
/** The original feed cells returned in get_qzone_public_feeds.feeds. */
feed: JsonObject;
}
export interface GetQzonePublicCommentsParams extends QzonePublicFeedParams {
/** Upstream attach_info from the detail or previous comment page. */
cursor: string;
}
export interface QzonePublicCommentParams extends QzonePublicFeedParams {
/** Preserve the complete upstream parent comment. */
comment: JsonObject;
}
export interface GetQzonePublicRepliesParams extends QzonePublicCommentParams {
/** Omit to use comment.reply_attach_info; then pass the reply page's cursor unchanged. */
cursor?: string;
/** Defaults to 20; must be at least 1. */
page_size?: ActionNumberInput;
}
export interface QzonePublicInteractionParams extends QzonePublicFeedParams {
/** Defaults to true; false cancels the interaction. */
enable?: ActionBooleanInput;
}
export interface SetQzonePublicCommentLikeParams extends QzonePublicCommentParams {
/** Omit for the parent comment; provide the complete upstream reply to like that reply. */
reply?: JsonObject;
/** Defaults to true; false cancels the like. */
enable?: ActionBooleanInput;
}
export interface CommentQzonePublicFeedParams extends QzonePublicFeedParams {
content: QzonePublicContent;
}
export interface ReplyQzonePublicFeedParams extends CommentQzonePublicFeedParams {
comment: JsonObject;
/** Preserve a specific upstream reply when addressing its author. */
reply?: JsonObject;
}
export interface QzonePublicReplyParams extends QzonePublicCommentParams {
reply: JsonObject;
}
export interface ForwardQzonePublicFeedParams extends QzonePublicFeedParams {
reason?: string;
}
export interface QzoneMsgIdParams extends JsonObject {
tid: ActionStringInput;
}
+9
View File
@@ -401,6 +401,15 @@ export interface QzoneProfileResult extends JsonObject {
description: string;
}
export interface QzonePublicFeedsPage extends JsonObject {
/** Original feed cells, with the upstream item.feed wrapper removed. */
feeds: JsonObject[];
/** Controls pagination even when a page contains fewer than ten items. */
has_more: boolean;
/** Account-bound continuation; null when the list ends. */
next_cursor: string | null;
}
export interface QzoneFeed extends JsonObject {
uin: number;
nickname: string;
+99
View File
@@ -8,6 +8,24 @@ const fileset = { fileset_id: 'fileset' };
const flashFile = { ...fileset, file_name: 'file.txt', file_index: '0' };
const peer = { group_id: '10001', user_id: '10002', phone_number: '' };
const qzoneLike = { tid: 'post', target_uin: '10002', abstime: '1700000000' };
const qzonePublicFeed = {
cell_common: {
domain_type: 3,
union_id: { uf_key: '9007199254740993', unknown_identity: 'preserved' },
},
cell_feed_transfer: { opaque: 'fixture' },
unknown_cell: { decimal: '18446744073709551615' },
};
const qzonePublicComment = {
id: '9007199254740993',
user: { uid: 'public-reader' },
like: { id: 'comment-like-key' },
};
const qzonePublicReply = {
id: '18446744073709551615',
user: { uid: 'public-author' },
like: { id: 'reply-like-key' },
};
// The same examples are compiled against the published declarations and parsed
// by the real server action definitions. They never invoke QQ or perform I/O.
@@ -26,6 +44,10 @@ export const actionParams = {
reply_uin: '10004',
reply_name: 'Reader',
},
comment_qzone_public_feed: {
feed: qzonePublicFeed,
content: [{ type: 0, content: 'Comment', upstream_option: true }],
},
create_flash_task: {
files: ['file:///one', { file: 'file:///two', name: 'two.txt' }],
name: 'Files',
@@ -35,6 +57,12 @@ export const actionParams = {
delete_custom_face: { emoji_id: 'face' },
delete_flash_file: fileset,
delete_qzone_msg: { tid: 'post' },
delete_qzone_public_comment: { feed: qzonePublicFeed, comment: qzonePublicComment },
delete_qzone_public_reply: {
feed: qzonePublicFeed,
comment: qzonePublicComment,
reply: qzonePublicReply,
},
do_group_album_comment: { ...album, lloc: 'photo', content: 'Comment' },
download_file_image_stream: download,
download_file_record_stream: download,
@@ -42,6 +70,7 @@ export const actionParams = {
download_fileset: flashFile,
fetch_custom_face_detail: { count: '48' },
fetch_ptt_text: { message_id: -42 },
forward_qzone_public_feed: { feed: qzonePublicFeed, reason: '' },
get_ptt_text: { message_id: '-42' },
get_record_text: { message_id: -42 },
get_doubt_friends_add_request: { count: '50' },
@@ -57,6 +86,16 @@ export const actionParams = {
get_qzone_feeds: { page_num: '1', count: '10', cursor: 'cursor-from-previous-response' },
get_qzone_msg_list: { target_uin: '10002', pos: '0', num: '20' },
get_qzone_profile: { target_uin: '10002' },
get_qzone_public_capabilities: {},
get_qzone_public_comments: { feed: qzonePublicFeed, cursor: 'comments-from-detail' },
get_qzone_public_feed_detail: { feed: qzonePublicFeed },
get_qzone_public_feeds: { cursor: 'public-feed-cursor' },
get_qzone_public_replies: {
feed: qzonePublicFeed,
comment: qzonePublicComment,
cursor: '',
page_size: '20',
},
get_rkey_server: {},
get_share_link: fileset,
like_qzone: qzoneLike,
@@ -64,6 +103,12 @@ export const actionParams = {
modify_custom_face: { emoji_id: 'face', desc: 'Description' },
move_custom_face_to_front: { emoji_id: 'face' },
rename_flash_file: { ...fileset, new_name: 'new.txt' },
reply_qzone_public_feed: {
feed: qzonePublicFeed,
comment: qzonePublicComment,
content: 'Reply',
reply: qzonePublicReply,
},
request_decrypt_key: { db_path: '/fixture.db' },
send_ark_share: peer,
send_flash_msg: { ...fileset, group_id: '10001', user_id: '10002' },
@@ -101,6 +146,15 @@ export const actionParams = {
set_qzone_ban: { user_id: '10002', enable: false },
set_qzone_msg_right: { tid: 'post', ugc_right: '128', target_uins: ['10002'] },
set_qzone_profile: { name: 'Space', description: '' },
set_qzone_public_follow: { feed: qzonePublicFeed, enable: 'off' },
set_qzone_public_comment_like: {
feed: qzonePublicFeed,
comment: qzonePublicComment,
reply: qzonePublicReply,
enable: 'on',
},
set_qzone_public_like: { feed: qzonePublicFeed, enable: 0 },
set_qzone_public_upvote: { feed: qzonePublicFeed, enable: true },
share_group_ex: { group_id: '10001' },
share_peer: peer,
test_download_stream: { error: false },
@@ -131,11 +185,14 @@ export type CoveredAction =
| 'cancel_group_album_media_like'
| 'clean_stream_temp_file'
| 'comment_qzone'
| 'comment_qzone_public_feed'
| 'create_flash_task'
| 'del_group_album_media'
| 'delete_custom_face'
| 'delete_flash_file'
| 'delete_qzone_msg'
| 'delete_qzone_public_comment'
| 'delete_qzone_public_reply'
| 'do_group_album_comment'
| 'download_file_image_stream'
| 'download_file_record_stream'
@@ -143,6 +200,7 @@ export type CoveredAction =
| 'download_fileset'
| 'fetch_custom_face_detail'
| 'fetch_ptt_text'
| 'forward_qzone_public_feed'
| 'get_ptt_text'
| 'get_record_text'
| 'get_doubt_friends_add_request'
@@ -158,6 +216,11 @@ export type CoveredAction =
| 'get_qzone_feeds'
| 'get_qzone_msg_list'
| 'get_qzone_profile'
| 'get_qzone_public_capabilities'
| 'get_qzone_public_comments'
| 'get_qzone_public_feed_detail'
| 'get_qzone_public_feeds'
| 'get_qzone_public_replies'
| 'get_rkey_server'
| 'get_share_link'
| 'like_qzone'
@@ -165,6 +228,7 @@ export type CoveredAction =
| 'modify_custom_face'
| 'move_custom_face_to_front'
| 'rename_flash_file'
| 'reply_qzone_public_feed'
| 'request_decrypt_key'
| 'send_ark_share'
| 'send_flash_msg'
@@ -180,6 +244,10 @@ export type CoveredAction =
| 'set_qzone_ban'
| 'set_qzone_msg_right'
| 'set_qzone_profile'
| 'set_qzone_public_follow'
| 'set_qzone_public_comment_like'
| 'set_qzone_public_like'
| 'set_qzone_public_upvote'
| 'share_group_ex'
| 'share_peer'
| 'test_download_stream'
@@ -220,11 +288,14 @@ export const actionResults = {
cancel_group_album_media_like: {},
clean_stream_temp_file: { message: 'success', removed: 1, freed_bytes: 42, skipped_active: 1 },
comment_qzone: { comment_id: 'comment' },
comment_qzone_public_feed: { comment: qzonePublicComment },
create_flash_task: { fileset_id: 'fileset', task_id: 'fileset' },
del_group_album_media: { success: true },
delete_custom_face: null,
delete_flash_file: null,
delete_qzone_msg: null,
delete_qzone_public_comment: {},
delete_qzone_public_reply: {},
do_group_album_comment: {
id: 'comment',
user: { uin: '10002' },
@@ -259,6 +330,7 @@ export const actionResults = {
download_fileset: { url: '', file_name: 'file.txt', file_size: 42 },
fetch_custom_face_detail: [{ emoji_id: 'face', resId: 'face', url: '', md5: '', desc: '' }],
fetch_ptt_text: { text: 'Speech' },
forward_qzone_public_feed: {},
get_ptt_text: { text: 'Speech' },
get_record_text: { text: 'Speech' },
get_doubt_friends_add_request: [
@@ -369,6 +441,28 @@ export const actionResults = {
],
},
get_qzone_profile: { name: 'Space', description: 'Description' },
get_qzone_public_capabilities: { public_qzone_entrance_switch: true, can_upvote: true },
get_qzone_public_comments: {
cell_comment: { comments: [qzonePublicComment] },
attach_info: 'next-comments',
has_more: true,
},
get_qzone_public_feed_detail: {
feed: { feed: qzonePublicFeed },
attach_info: 'comments-from-detail',
has_more: true,
},
get_qzone_public_feeds: {
feeds: [qzonePublicFeed],
has_more: true,
next_cursor: 'public-feed-cursor',
unknown_page: { preserved: true },
},
get_qzone_public_replies: {
replys: [qzonePublicReply],
reply_attach_info: '',
has_more: false,
},
get_rkey_server: { expired_time: 1, name: 'SnowLuma', private_rkey: 'fixture' },
get_share_link: 'https://example.com/share',
like_qzone: null,
@@ -376,6 +470,7 @@ export const actionResults = {
modify_custom_face: null,
move_custom_face_to_front: null,
rename_flash_file: null,
reply_qzone_public_feed: { reply: qzonePublicReply },
request_decrypt_key: { db_key: 'fixture' },
send_ark_share: { arkMsg: '{}' },
send_flash_msg: { message_id: 0 },
@@ -391,6 +486,10 @@ export const actionResults = {
set_qzone_ban: null,
set_qzone_msg_right: { ugc_right: 128 },
set_qzone_profile: null,
set_qzone_public_follow: { ret_code: 0 },
set_qzone_public_comment_like: { like: { status: 1 } },
set_qzone_public_like: { like: { liked: true } },
set_qzone_public_upvote: { upvote: { upvoted: true } },
share_group_ex: '{}',
share_peer: { arkMsg: '{}' },
test_download_stream: {
+52
View File
@@ -115,6 +115,58 @@ export const invalidQzoneProfilePatch: ActionParams<'set_qzone_profile'> = {
// @ts-expect-error profile fields accept string, number or boolean primitives
description: [],
};
const publicPage = await http.raw('get_qzone_public_feeds', {});
export const publicCells: JsonObject[] = publicPage.feeds;
export const publicHasMore: boolean = publicPage.has_more;
export const publicCursor: string | null = publicPage.next_cursor;
if (publicPage.has_more && publicPage.next_cursor) {
await http.raw('get_qzone_public_feeds', { cursor: publicPage.next_cursor });
}
declare const publicFeed: JsonObject;
declare const publicComment: JsonObject;
export const publicReplyDefaults: ActionParams<'get_qzone_public_replies'> = {
feed: publicFeed,
comment: publicComment,
};
export const publicUpvoteDefault: ActionParams<'set_qzone_public_upvote'> = { feed: publicFeed };
export const publicLikeDefault: ActionParams<'set_qzone_public_like'> = { feed: publicFeed };
export const publicFollowDefault: ActionParams<'set_qzone_public_follow'> = { feed: publicFeed };
export const publicCommentLikeDefault: ActionParams<'set_qzone_public_comment_like'> = {
feed: publicFeed,
comment: publicComment,
};
export const publicReplyLike: ActionParams<'set_qzone_public_comment_like'> = {
feed: publicFeed,
comment: publicComment,
reply: { id: '18446744073709551615', like: { id: 'reply-like-key' } },
enable: false,
};
export const publicReplyToComment: ActionParams<'reply_qzone_public_feed'> = {
feed: publicFeed,
comment: publicComment,
content: 'Reply',
};
export const publicForwardDefault: ActionParams<'forward_qzone_public_feed'> = { feed: publicFeed };
export const publicReplyResult: JsonObject = await ws.raw(
'reply_qzone_public_feed',
actionParams.reply_qzone_public_feed,
);
// @ts-expect-error follow-up comments require attach_info as the cursor
export const publicCommentsWithoutCursor: ActionParams<'get_qzone_public_comments'> = {
feed: publicFeed,
};
export const invalidPublicContent: ActionParams<'comment_qzone_public_feed'> = {
feed: publicFeed,
// @ts-expect-error public content does not coerce numeric primitives
content: 123,
};
export const invalidPublicRichItems: ActionParams<'comment_qzone_public_feed'> = {
feed: publicFeed,
// @ts-expect-error rich-text arrays contain JSON objects, not strings
content: ['text'],
};
const speech = await ws.raw('get_record_text', { message_id: -42 });
const transcription: string = speech.text;
const flash = await http.raw('get_fileset_info', { fileset_id: 'files' });
+71
View File
@@ -0,0 +1,71 @@
import { describe, expect, expectTypeOf, it, vi } from 'vitest';
import { SnowLumaHttpClient, type JsonObject, type QzonePublicFeedsPage } from '../src';
const feed: JsonObject = {
cell_common: {
domain_type: 3,
union_id: { uf_key: '9007199254740993', unknown_identity: 'preserved' },
},
cell_feed_transfer: { opaque: 'fixture' },
unknown_cell: { decimal: '18446744073709551615' },
};
describe('public Qzone raw actions', () => {
it('preserves original feed cells and follows an explicit cursor after a short page', async () => {
const first: QzonePublicFeedsPage = {
feeds: [feed],
has_more: true,
next_cursor: 'account-bound-cursor',
upstream_page: { untouched: '18446744073709551615' },
};
const last: QzonePublicFeedsPage = { feeds: [], has_more: false, next_cursor: null };
const fetchImpl = vi
.fn()
.mockImplementationOnce(
async () => new Response(JSON.stringify({ status: 'ok', retcode: 0, data: first })),
)
.mockImplementationOnce(
async () => new Response(JSON.stringify({ status: 'ok', retcode: 0, data: last })),
);
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
const page = await client.raw('get_qzone_public_feeds', {});
expectTypeOf(page).toEqualTypeOf<QzonePublicFeedsPage>();
expect(page).toEqual(first);
expect(fetchImpl).toHaveBeenCalledTimes(1);
expect(page.has_more).toBe(true);
expect(await client.raw('get_qzone_public_feeds', { cursor: page.next_cursor! })).toEqual(
last,
);
expect(
fetchImpl.mock.calls.map((call) => JSON.parse((call[1] as RequestInit).body as string)),
).toEqual([
{ action: 'get_qzone_public_feeds', params: {} },
{ action: 'get_qzone_public_feeds', params: { cursor: 'account-bound-cursor' } },
]);
});
it('preserves complete comment and reply objects and unknown writer results', async () => {
const comment: JsonObject = { id: '9007199254740993', unknown_parent: { keep: true } };
const reply: JsonObject = { id: '18446744073709551615', user: { uid: 'reader' } };
const content = [{ type: 0, content: 'Reply', upstream_option: true }];
const data = { reply, upstream_result: { untouched: true } };
const fetchImpl = vi
.fn()
.mockImplementation(
async () => new Response(JSON.stringify({ status: 'ok', retcode: 0, data })),
);
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
const params = { feed, comment, reply, content };
const result = await client.raw('reply_qzone_public_feed', params);
expectTypeOf(result).toEqualTypeOf<JsonObject>();
expect(result).toEqual(data);
expect(fetchImpl).toHaveBeenCalledWith(
'http://127.0.0.1:3000/',
expect.objectContaining({
body: JSON.stringify({ action: 'reply_qzone_public_feed', params }),
}),
);
});
});