feat(qzone): add homepage feeds and share cards

Read accessible Qzone homepage posts and generate their original share cards. Return sharing notices so callers can confirm visibility before sending through the existing message actions.

Include SDK contracts, action discovery, documentation, and regression coverage.

Fixes #609
This commit is contained in:
DrSmoothl committed 2026-10-31 18:28:05 +08:00
1 parent 304f3e772f
commit eb119ecb92
15 files changed
+944 -4

No files matched your search

+215 -1
View File
@@ -9,6 +9,20 @@ export interface QzonePublicFeedsPage extends JsonObject {
next_cursor: string | null;
}
export interface QzoneShareArk extends JsonObject {
ark: string;
requires_confirmation: boolean;
notice: string | null;
}
interface HomeFeedCursor {
version: 1;
kind: 'home';
uin: string;
host_uin: string;
attach_info: string;
}
interface PublicFeedCursor {
version: 1;
uin: string;
@@ -75,7 +89,7 @@ function feedParams(feed: JsonObject): JsonObject {
};
}
function encodeCursor(state: PublicFeedCursor): string {
function encodeCursor(state: PublicFeedCursor | HomeFeedCursor): string {
const cursor = Buffer.from(JSON.stringify(state)).toString('base64url');
if (cursor.length > 65_536) {
@@ -150,6 +164,206 @@ export async function getQzonePublicCapabilities(
return result.entrances;
}
export async function getQzoneHomeFeeds(
cookies: Record<string, string>,
selfUin: string,
targetUin = selfUin,
cursor?: string,
): Promise<QzonePublicFeedsPage> {
let attachInfo = '';
if (cursor !== undefined) {
if (!cursor || cursor.length > 65_536 || !/^[A-Za-z0-9_-]+$/.test(cursor)) {
throw new Error('无效的空间主页 cursor');
}
const bytes = Buffer.from(cursor, 'base64url');
const value: unknown = JSON.parse(bytes.toString('utf8'));
if (
bytes.toString('base64url') !== cursor ||
!isObject(value) ||
value.version !== 1 ||
value.kind !== 'home' ||
value.uin !== selfUin ||
value.host_uin !== targetUin ||
typeof value.attach_info !== 'string' ||
!value.attach_info
) {
throw new Error('空间主页 cursor 无效或不属于当前账号及主页');
}
attachInfo = value.attach_info;
}
const data = await request(cookies, reader, 'GetMainPageFeeds', '0x9794_2', {
host_uid: '',
host_uin: targetUin,
attach_info: attachInfo,
refresh_attach_info: '',
feed_action_domain_type: 1,
});
if (!Array.isArray(data.feeds) || typeof data.has_more !== 'boolean') {
throw new Error('空间主页动态分页响应异常');
}
const feeds = data.feeds.map((entry) => {
if (!isObject(entry) || !isObject(entry.feed)) {
throw new Error('空间主页动态响应异常');
}
return entry.feed;
});
let nextCursor: string | null = null;
if (data.has_more) {
if (
typeof data.attach_info !== 'string' ||
!data.attach_info ||
data.attach_info === attachInfo
) {
throw new Error('空间主页动态分页未推进');
}
nextCursor = encodeCursor({
version: 1,
kind: 'home',
uin: selfUin,
host_uin: targetUin,
attach_info: data.attach_info,
});
}
return { ...data, feeds, has_more: data.has_more, next_cursor: nextCursor };
}
export async function getQzoneShareArk(
cookies: Record<string, string>,
feed: JsonObject,
): Promise<QzoneShareArk> {
const operation = feed.cell_operation;
const share = isObject(operation) ? operation.share_outside : undefined;
const resource = isObject(share) ? share.share_access_resource : undefined;
const common = feed.cell_common;
const mask = isObject(common) ? common.operate_mask : undefined;
if (
mask !== undefined &&
(typeof mask !== 'number' || !Number.isSafeInteger(mask) || mask < 0)
) {
throw new Error('空间动态分享权限数据异常');
}
if (typeof mask === 'number' && (mask & (1 << 17)) !== 0) {
const reason =
isObject(share) && typeof share.share_out_button_toast === 'string'
? share.share_out_button_toast
: '该空间动态暂不支持分享';
throw new Error(reason);
}
if (
!isObject(resource) ||
typeof resource.busi_id !== 'string' ||
!resource.busi_id ||
typeof resource.resource_id !== 'string' ||
!resource.resource_id ||
typeof feed.cell_feed_transfer !== 'string' ||
!feed.cell_feed_transfer
) {
throw new Error('空间动态缺少分享信息,请传入主页或推荐列表返回的完整动态');
}
const data = await request(cookies, 'trpc.qq.share.Service', 'CreateShare', '0x9409_1', {
info: {
busi_id: resource.busi_id,
resource_id: resource.resource_id,
template: 'ark_busi_select',
busi_data: feed.cell_feed_transfer,
plat: 1,
target: 3,
},
});
if (data.err !== undefined) {
if (
!isObject(data.err) ||
(data.err.code !== undefined && typeof data.err.code !== 'number')
) {
throw new Error('空间分享业务响应异常');
}
if (data.err.code !== undefined && data.err.code !== 0) {
const message = typeof data.err.msg === 'string' ? data.err.msg : '';
throw new Error(`空间分享失败: ${data.err.code} ${message}`.trim());
}
}
if (typeof data.template_data !== 'string' || !data.template_data.trim()) {
throw new Error('空间分享未返回卡片');
}
const ark: unknown = JSON.parse(data.template_data);
if (!isObject(ark)) {
throw new Error('空间分享返回的卡片格式异常');
}
let requiresConfirmation = false;
let notice: string | null = null;
if (data.info !== undefined) {
if (!isObject(data.info)) {
throw new Error('空间分享提示格式异常');
}
const encoded = data.info.busi_data;
if (encoded !== undefined && encoded !== '') {
if (typeof encoded !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)) {
throw new Error('空间分享提示编码异常');
}
const decoded = Buffer.from(encoded, 'base64');
if (decoded.toString('base64').replace(/=+$/, '') !== encoded.replace(/=+$/, '')) {
throw new Error('空间分享提示编码异常');
}
const permission: unknown = JSON.parse(
new TextDecoder('utf-8', { fatal: true }).decode(decoded),
);
if (permission !== null) {
if (
!isObject(permission) ||
(permission.need_break !== undefined &&
typeof permission.need_break !== 'boolean')
) {
throw new Error('空间分享提示格式异常');
}
requiresConfirmation = permission.need_break === true;
if (
isObject(permission.tips) &&
typeof permission.tips.content === 'string' &&
permission.tips.content
) {
notice = permission.tips.content;
}
if (requiresConfirmation && !notice) {
notice = '你的空间有权限,分享出去的页面所有人都可以看。';
}
}
}
}
return { ark: data.template_data, requires_confirmation: requiresConfirmation, notice };
}
export async function getQzonePublicFeeds(
cookies: Record<string, string>,
selfUin: string,
@@ -0,0 +1,152 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getQzoneHomeFeeds, getQzoneShareArk } from '../../src/web/qzone-public';
import { RequestUtil } from '../../src/web/request-util';
const cookies = { p_skey: 'test', uin: 'o10001' };
const feed = {
cell_common: { union_id: { feed_id: 'feed-id' }, operate_mask: 0 },
cell_operation: {
share_outside: { share_access_resource: { busi_id: 'qzone_feed', resource_id: 'opaque' } },
},
cell_feed_transfer: 'original-transfer',
unknown: { keep: true },
};
const ark = '{ "app": "com.tencent.tuwen.lua", "config": {"token":"fixture"} }';
const request = (data: unknown) =>
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ retcode: 0, data });
afterEach(() => vi.restoreAllMocks());
describe('Qzone share card', () => {
it('generates the original card and returns the upstream confirmation notice', async () => {
const req = request({
template_data: ark,
err: { code: 0 },
info: {
busi_data: Buffer.from(
JSON.stringify({ need_break: true, tips: { content: '分享后所有人可见' } }),
).toString('base64'),
},
});
await expect(getQzoneShareArk(cookies, feed)).resolves.toEqual({
ark,
requires_confirmation: true,
notice: '分享后所有人可见',
});
expect(req).toHaveBeenCalledExactlyOnceWith(
expect.stringContaining('/trpc.qq.share.Service/CreateShare?g_tk='),
'POST',
{
info: {
busi_id: 'qzone_feed',
resource_id: 'opaque',
template: 'ark_busi_select',
busi_data: 'original-transfer',
plat: 1,
target: 3,
},
},
expect.objectContaining({
'x-oidb': JSON.stringify({ uint32_command: '0x9409', uint32_service_type: '1' }),
Cookie: 'p_skey=test; uin=o10001',
}),
);
});
it('preserves a valid card without a confirmation notice', async () => {
request({ template_data: ark, err: {} });
await expect(getQzoneShareArk(cookies, feed)).resolves.toEqual({
ark,
requires_confirmation: false,
notice: null,
});
});
it('rejects unavailable sharing and incomplete feeds before requesting a card', async () => {
const req = request({ template_data: ark });
await expect(
getQzoneShareArk(cookies, { ...feed, cell_common: { operate_mask: 1 << 17 } }),
).rejects.toThrow('不支持分享');
await expect(
getQzoneShareArk(cookies, { ...feed, cell_feed_transfer: '' }),
).rejects.toThrow('缺少分享信息');
await expect(getQzoneShareArk(cookies, {})).rejects.toThrow('缺少分享信息');
expect(req).not.toHaveBeenCalled();
});
it.each([
[{ err: { code: 3, msg: '参数错误' }, template_data: ark }, '3 参数错误'],
[{ err: { code: '0' }, template_data: ark }, '业务响应异常'],
[{}, '未返回卡片'],
[{ template_data: '[]' }, '卡片格式异常'],
[{ template_data: ark, info: { busi_data: '!' } }, '提示编码异常'],
[{ template_data: ark, info: { busi_data: Buffer.from('{').toString('base64') } }, 'JSON'],
])('surfaces rejected or malformed share responses', async (data, error) => {
request(data);
await expect(getQzoneShareArk(cookies, feed)).rejects.toThrow(error);
});
it('propagates access errors without a retry', async () => {
const req = request(null).mockResolvedValue({ retcode: 10023, message: '无权限访问' });
await expect(getQzoneShareArk(cookies, feed)).rejects.toThrow('10023 无权限访问');
expect(req).toHaveBeenCalledOnce();
});
});
describe('Qzone homepage feeds', () => {
it('reads own homepage and preserves full cells across explicit pagination', async () => {
const req = request({ feeds: [{ feed }], has_more: true, attach_info: 'next', extra: 1 });
const first = await getQzoneHomeFeeds(cookies, '10001');
expect(first).toMatchObject({ feeds: [feed], has_more: true, extra: 1 });
expect(req.mock.calls[0]![2]).toEqual({
host_uid: '',
host_uin: '10001',
attach_info: '',
refresh_attach_info: '',
feed_action_domain_type: 1,
});
req.mockResolvedValueOnce({ retcode: 0, data: { feeds: [], has_more: false } });
await expect(
getQzoneHomeFeeds(cookies, '10001', undefined, first.next_cursor!),
).resolves.toEqual({ feeds: [], has_more: false, next_cursor: null });
expect(req.mock.calls[1]![2]).toMatchObject({ attach_info: 'next' });
});
it('rejects a cursor reused for another account, homepage or stream', async () => {
const req = request({ feeds: [{ feed }], has_more: true, attach_info: 'next' });
const first = await getQzoneHomeFeeds(cookies, '10001');
req.mockClear();
for (const [self, host, cursor] of [
['20002', '10001', first.next_cursor!],
['10001', '20002', first.next_cursor!],
[
'10001',
'10001',
Buffer.from(
JSON.stringify({
version: 1,
uin: '10001',
attach_info: 'next',
refresh_id: 'x',
}),
).toString('base64url'),
],
]) {
await expect(getQzoneHomeFeeds(cookies, self!, host!, cursor!)).rejects.toThrow(
'cursor',
);
}
expect(req).not.toHaveBeenCalled();
});
it('surfaces missing or stalled pagination and permission failures', async () => {
const req = request({ feeds: [], has_more: true });
await expect(getQzoneHomeFeeds(cookies, '10001')).rejects.toThrow('分页未推进');
req.mockResolvedValue({ retcode: 10023, message: '无权限访问' });
await expect(getQzoneHomeFeeds(cookies, '10001', '20002')).rejects.toThrow(
'10023 无权限访问',
);
});
});