diff --git a/packages/core/src/bridge/apis/qzone.ts b/packages/core/src/bridge/apis/qzone.ts index 6decc7c3..dc0103a4 100644 --- a/packages/core/src/bridge/apis/qzone.ts +++ b/packages/core/src/bridge/apis/qzone.ts @@ -11,7 +11,7 @@ import { updateQzoneMsgRight, uploadQzoneImageFromSource, type QzoneCommentResult, - type QzoneFeedsResult, + type QzoneFeedsPage, type QzoneMsgDetailResult, type QzoneMsgListResult, type QzonePublishResult, @@ -53,12 +53,12 @@ export class QzoneApi { } /** - * 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。 + * 获取好友动态。页码调用从首页顺序定位;续页优先传上一页的 cursor。 * 始终以机器人自己的身份拉取好友动态。 */ - async getFeeds(pageNum = 1, count = 10): Promise { + async getFeeds(pageNum = 1, count = 10, cursor?: string): Promise { const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count); + return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count, cursor); } /** diff --git a/packages/core/tests/actions/qzone.test.ts b/packages/core/tests/actions/qzone.test.ts index 1fe91407..84835854 100644 --- a/packages/core/tests/actions/qzone.test.ts +++ b/packages/core/tests/actions/qzone.test.ts @@ -77,10 +77,18 @@ describe('apis/qzone', () => { const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never }); const feedsSpy = vi .spyOn(qzoneWeb, 'getQzoneFeeds') - .mockResolvedValue({ feeds: [], has_more: false }); + .mockResolvedValue({ feeds: [], has_more: false, next_cursor: null }); await new QzoneApi(bridge as never).getFeeds(3, 20); expect(getCookies).toHaveBeenCalledWith('qzone.qq.com'); - expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20); + expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20, undefined); + await new QzoneApi(bridge as never).getFeeds(1, 20, 'opaque-cursor'); + expect(feedsSpy).toHaveBeenLastCalledWith( + { p_skey: 'PSK' }, + '10001', + 1, + 20, + 'opaque-cursor', + ); }); it('uploadImageFromSource uploads from file:// http:// base64:// and returns richval + url', async () => { diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index 02327ad4..0fdf9eba 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -10717,8 +10717,8 @@ { "name": "get_qzone_feeds", "aliases": [], - "summary": "获取 QQ 空间好友动态(feed);page_num 仅首页可靠,深翻页需时间游标(暂未实现)", - "returns": "好友动态对象,含本页 feed 数组与是否有更多页。", + "summary": "获取 QQ 空间好友动态,支持结构化正文与游标分页", + "returns": "好友动态、可提取的正文与图片、统计值及下一页游标;未知内容或统计为 null,HTML 保留。", "returnsSchema": { "type": "object", "properties": { @@ -10751,6 +10751,51 @@ "html": { "type": "string", "description": "预渲染 HTML 原样透传" + }, + "tid": { + "type": [ + "string", + "null" + ], + "description": "可确认的说说编号;其他类型或无法确认时为 null" + }, + "content": { + "type": [ + "string", + "null" + ], + "description": "当前动态正文,不含评论;无法识别时为 null" + }, + "content_complete": { + "type": [ + "boolean", + "null" + ], + "description": "正文是否完整;false 表示折叠摘要,null 表示未知" + }, + "images": { + "type": [ + "array", + "null" + ], + "items": { + "type": "string" + }, + "description": "当前正文中可提取的图片地址,不含头像、评论图片或视频封面;不保证完整相册" + }, + "like_count": { + "type": [ + "integer", + "null" + ], + "description": "服务端提供的点赞数;未知时为 null" + }, + "comment_count": { + "type": [ + "integer", + "null" + ], + "description": "服务端提供的评论数;未知时为 null,不以展示的评论条数估算" } }, "required": [ @@ -10759,28 +10804,50 @@ "time", "appid", "key", - "html" + "html", + "tid", + "content", + "content_complete", + "images", + "like_count", + "comment_count" ] } }, "has_more": { "type": "boolean", "description": "服务端是否报告本页之后还有更多页" + }, + "next_cursor": { + "type": [ + "string", + "null" + ], + "description": "下一页游标,原样作为 cursor 传回;没有更多页时为 null" } }, "required": [ "feeds", - "has_more" + "has_more", + "next_cursor" ] }, "examples": [ { - "summary": "获取 QQ 空间好友动态(feed);page_num 仅首页可靠,深翻页需时间游标(暂未实现)", + "summary": "获取 QQ 空间好友动态首页及结构化内容", "params": { "page_num": 1, "count": 10 }, - "notes": "目前仅首页可靠,不应假设任意页码均能完整翻页。" + "notes": "保留 html;content/images 为可提取的正文和图片,未知值为 null。续页使用 next_cursor。" + }, + { + "summary": "继续读取上一页之后的好友动态", + "params": { + "cursor": "", + "count": 10 + }, + "notes": "cursor 原样使用上次返回的 next_cursor,仅适用于同一账号;has_more=false 时停止。" } ], "readOnly": true, @@ -10793,7 +10860,7 @@ "type": "integer", "minimum": 1 }, - "desc": "页码(1 起;仅首页可靠)", + "desc": "页码(1 起);不传 cursor 时从首页顺序定位,较深页可能耗时较长", "default": 1 }, { @@ -10807,6 +10874,17 @@ }, "desc": "本页数量", "default": 10 + }, + { + "name": "cursor", + "type": "string", + "required": false, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 65536 + }, + "desc": "上一次返回的 next_cursor;原样传递,省略 page_num 或传入对应页码" } ], "invariants": [], @@ -10816,7 +10894,7 @@ "page_num": { "type": "integer", "minimum": 1, - "description": "页码(1 起;仅首页可靠)", + "description": "页码(1 起);不传 cursor 时从首页顺序定位,较深页可能耗时较长", "default": 1 }, "count": { @@ -10825,6 +10903,12 @@ "maximum": 50, "description": "本页数量", "default": 10 + }, + "cursor": { + "type": "string", + "minLength": 1, + "maxLength": 65536, + "description": "上一次返回的 next_cursor;原样传递,省略 page_num 或传入对应页码" } }, "additionalProperties": true diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 8ae0a2a8..8b54a73b 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -10720,8 +10720,8 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_qzone_feeds", "aliases": [], - "summary": "获取 QQ 空间好友动态(feed);page_num 仅首页可靠,深翻页需时间游标(暂未实现)", - "returns": "好友动态对象,含本页 feed 数组与是否有更多页。", + "summary": "获取 QQ 空间好友动态,支持结构化正文与游标分页", + "returns": "好友动态、可提取的正文与图片、统计值及下一页游标;未知内容或统计为 null,HTML 保留。", "returnsSchema": { "type": "object", "properties": { @@ -10754,6 +10754,51 @@ export const ACTIONS: CatalogAction[] = [ "html": { "type": "string", "description": "预渲染 HTML 原样透传" + }, + "tid": { + "type": [ + "string", + "null" + ], + "description": "可确认的说说编号;其他类型或无法确认时为 null" + }, + "content": { + "type": [ + "string", + "null" + ], + "description": "当前动态正文,不含评论;无法识别时为 null" + }, + "content_complete": { + "type": [ + "boolean", + "null" + ], + "description": "正文是否完整;false 表示折叠摘要,null 表示未知" + }, + "images": { + "type": [ + "array", + "null" + ], + "items": { + "type": "string" + }, + "description": "当前正文中可提取的图片地址,不含头像、评论图片或视频封面;不保证完整相册" + }, + "like_count": { + "type": [ + "integer", + "null" + ], + "description": "服务端提供的点赞数;未知时为 null" + }, + "comment_count": { + "type": [ + "integer", + "null" + ], + "description": "服务端提供的评论数;未知时为 null,不以展示的评论条数估算" } }, "required": [ @@ -10762,28 +10807,50 @@ export const ACTIONS: CatalogAction[] = [ "time", "appid", "key", - "html" + "html", + "tid", + "content", + "content_complete", + "images", + "like_count", + "comment_count" ] } }, "has_more": { "type": "boolean", "description": "服务端是否报告本页之后还有更多页" + }, + "next_cursor": { + "type": [ + "string", + "null" + ], + "description": "下一页游标,原样作为 cursor 传回;没有更多页时为 null" } }, "required": [ "feeds", - "has_more" + "has_more", + "next_cursor" ] }, "examples": [ { - "summary": "获取 QQ 空间好友动态(feed);page_num 仅首页可靠,深翻页需时间游标(暂未实现)", + "summary": "获取 QQ 空间好友动态首页及结构化内容", "params": { "page_num": 1, "count": 10 }, - "notes": "目前仅首页可靠,不应假设任意页码均能完整翻页。" + "notes": "保留 html;content/images 为可提取的正文和图片,未知值为 null。续页使用 next_cursor。" + }, + { + "summary": "继续读取上一页之后的好友动态", + "params": { + "cursor": "", + "count": 10 + }, + "notes": "cursor 原样使用上次返回的 next_cursor,仅适用于同一账号;has_more=false 时停止。" } ], "readOnly": true, @@ -10796,7 +10863,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "minimum": 1 }, - "desc": "页码(1 起;仅首页可靠)", + "desc": "页码(1 起);不传 cursor 时从首页顺序定位,较深页可能耗时较长", "default": 1 }, { @@ -10810,6 +10877,17 @@ export const ACTIONS: CatalogAction[] = [ }, "desc": "本页数量", "default": 10 + }, + { + "name": "cursor", + "type": "string", + "required": false, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 65536 + }, + "desc": "上一次返回的 next_cursor;原样传递,省略 page_num 或传入对应页码" } ], "invariants": [], @@ -10819,7 +10897,7 @@ export const ACTIONS: CatalogAction[] = [ "page_num": { "type": "integer", "minimum": 1, - "description": "页码(1 起;仅首页可靠)", + "description": "页码(1 起);不传 cursor 时从首页顺序定位,较深页可能耗时较长", "default": 1 }, "count": { @@ -10828,6 +10906,12 @@ export const ACTIONS: CatalogAction[] = [ "maximum": 50, "description": "本页数量", "default": 10 + }, + "cursor": { + "type": "string", + "minLength": 1, + "maxLength": 65536, + "description": "上一次返回的 next_cursor;原样传递,省略 page_num 或传入对应页码" } }, "additionalProperties": true diff --git a/packages/onebot/src/actions/qzone.ts b/packages/onebot/src/actions/qzone.ts index d70aeca7..95543571 100644 --- a/packages/onebot/src/actions/qzone.ts +++ b/packages/onebot/src/actions/qzone.ts @@ -171,22 +171,30 @@ export const actions = [ }), // get_qzone_feeds — 获取好友动态(feed)。只读,始终以机器人自己身份拉取。 - // 每条 feed 含结构化字段 + 预渲染 html 原样透传(深度解析交由调用方)。 + // 保留旧 HTML,同时提供正文摘要与服务端分页接续。 defineAction({ name: 'get_qzone_feeds', examples: [ { - summary: - '获取 QQ 空间好友动态(feed);page_num 仅首页可靠,深翻页需时间游标(暂未实现)', + summary: '获取 QQ 空间好友动态首页及结构化内容', params: { page_num: 1, count: 10, }, - notes: '目前仅首页可靠,不应假设任意页码均能完整翻页。', + notes: '保留 html;content/images 为可提取的正文和图片,未知值为 null。续页使用 next_cursor。', + }, + { + summary: '继续读取上一页之后的好友动态', + params: { + cursor: '', + count: 10, + }, + notes: 'cursor 原样使用上次返回的 next_cursor,仅适用于同一账号;has_more=false 时停止。', }, ], readOnly: true, - returns: '好友动态对象,含本页 feed 数组与是否有更多页。', + returns: + '好友动态、可提取的正文与图片、统计值及下一页游标;未知内容或统计为 null,HTML 保留。', returnsSchema: { type: 'object', properties: { @@ -208,21 +216,72 @@ export const actions = [ description: 'feed 句柄(Qzone 用于定位该条动态)', }, html: { type: 'string', description: '预渲染 HTML 原样透传' }, + tid: { + type: ['string', 'null'], + description: '可确认的说说编号;其他类型或无法确认时为 null', + }, + content: { + type: ['string', 'null'], + description: '当前动态正文,不含评论;无法识别时为 null', + }, + content_complete: { + type: ['boolean', 'null'], + description: '正文是否完整;false 表示折叠摘要,null 表示未知', + }, + images: { + type: ['array', 'null'], + items: { type: 'string' }, + description: + '当前正文中可提取的图片地址,不含头像、评论图片或视频封面;不保证完整相册', + }, + like_count: { + type: ['integer', 'null'], + description: '服务端提供的点赞数;未知时为 null', + }, + comment_count: { + type: ['integer', 'null'], + description: + '服务端提供的评论数;未知时为 null,不以展示的评论条数估算', + }, }, - required: ['uin', 'nickname', 'time', 'appid', 'key', 'html'], + required: [ + 'uin', + 'nickname', + 'time', + 'appid', + 'key', + 'html', + 'tid', + 'content', + 'content_complete', + 'images', + 'like_count', + 'comment_count', + ], }, }, has_more: { type: 'boolean', description: '服务端是否报告本页之后还有更多页' }, + next_cursor: { + type: ['string', 'null'], + description: '下一页游标,原样作为 cursor 传回;没有更多页时为 null', + }, }, - required: ['feeds', 'has_more'], + required: ['feeds', 'has_more', 'next_cursor'], }, - summary: '获取 QQ 空间好友动态(feed);page_num 仅首页可靠,深翻页需时间游标(暂未实现)', + summary: '获取 QQ 空间好友动态,支持结构化正文与游标分页', params: { - page_num: f.int({ min: 1 }).describe('页码(1 起;仅首页可靠)').default(1), + page_num: f + .int({ min: 1 }) + .describe('页码(1 起);不传 cursor 时从首页顺序定位,较深页可能耗时较长') + .default(1), count: f.int({ min: 1, max: 50 }).describe('本页数量').default(10), + cursor: f + .string({ allowEmpty: false, maxLen: 65536 }) + .describe('上一次返回的 next_cursor;原样传递,省略 page_num 或传入对应页码') + .optional(), }, run: async (p, ctx) => { - const res = await ctx.bridge.apis.qzone.getFeeds(p.page_num, p.count); + const res = await ctx.bridge.apis.qzone.getFeeds(p.page_num, p.count, p.cursor); return okResponse(res as unknown as JsonValue); }, }), diff --git a/packages/onebot/tests/qzone-actions.test.ts b/packages/onebot/tests/qzone-actions.test.ts index a641896a..587305be 100644 --- a/packages/onebot/tests/qzone-actions.test.ts +++ b/packages/onebot/tests/qzone-actions.test.ts @@ -10,6 +10,40 @@ function makeHandler(qzone: Record): ApiHandler { } describe('qzone actions', () => { + it('get_qzone_feeds retains defaults and forwards optional continuation without stripping result fields', async () => { + const result = { feeds: [], has_more: true, next_cursor: 'next' }; + const getFeeds = vi.fn().mockResolvedValue(result); + const handler = makeHandler({ getFeeds }); + expect(await handler.handle('get_qzone_feeds', {})).toMatchObject({ + status: 'ok', + data: result, + }); + expect(getFeeds).toHaveBeenLastCalledWith(1, 10, undefined); + await handler.handle('get_qzone_feeds', { cursor: 'opaque-cursor', count: '20' }); + expect(getFeeds).toHaveBeenLastCalledWith(1, 20, 'opaque-cursor'); + expect( + actions.find((action) => action.names.includes('get_qzone_feeds'))?.describe().readOnly, + ).toBe(true); + }); + + it.each([{ cursor: '' }, { cursor: 'a'.repeat(65537) }, { count: 51 }, { page_num: 0 }])( + 'get_qzone_feeds rejects invalid pagination before calling the bridge', + async (params) => { + const getFeeds = vi.fn(); + expect(await makeHandler({ getFeeds }).handle('get_qzone_feeds', params)).toMatchObject( + { status: 'failed', retcode: 1400 }, + ); + expect(getFeeds).not.toHaveBeenCalled(); + }, + ); + + it('get_qzone_feeds exposes continuation failures to callers', async () => { + const getFeeds = vi.fn().mockRejectedValue(new Error('pagination did not advance')); + expect( + await makeHandler({ getFeeds }).handle('get_qzone_feeds', { cursor: 'opaque' }), + ).toMatchObject({ status: 'failed', wording: 'pagination did not advance' }); + }); + it('get_qzone_msg_detail returns the comment page with default parameters', async () => { const detail = { tid: 'T1', diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 5f09fd90..a2d4832d 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -115,7 +115,8 @@ "@snowluma/common": "workspace:*", "@snowluma/proto-defs": "workspace:*", "@snowluma/proton": "workspace:*", - "@snowluma/sqlite": "workspace:*" + "@snowluma/sqlite": "workspace:*", + "htmlparser2": "10.0.0" }, "devDependencies": { "@types/node": "catalog:", diff --git a/packages/protocol/src/web/qzone-feed-content.ts b/packages/protocol/src/web/qzone-feed-content.ts new file mode 100644 index 00000000..a296f47f --- /dev/null +++ b/packages/protocol/src/web/qzone-feed-content.ts @@ -0,0 +1,189 @@ +import { DomUtils, parseDocument } from 'htmlparser2'; + +type Element = ReturnType[number]; +type Node = ReturnType['children'][number]; + +export interface QzoneFeedContent { + tid: string | null; + content: string | null; + content_complete: boolean | null; + images: string[] | null; + like_count: number | null; + comment_count: number | null; +} + +function hasClass(node: Element, name: string): boolean { + return (node.attribs.class ?? '').split(/\s+/).includes(name); +} + +function isContentNode(node: Element, root: Element): boolean { + for (let parent = node.parent; parent && parent !== root; parent = parent.parent) { + if ( + 'attribs' in parent && + (hasClass(parent, 'mod-comments') || + hasClass(parent, 'comments-list') || + hasClass(parent, 'f-item-passive') || + hasClass(parent, 'f-ct-video')) + ) { + return false; + } + } + + return true; +} + +function text(node: Element): string { + const chunks: string[] = []; + const stack: (Node | string)[] = [...node.children].reverse(); + + while (stack.length) { + const next = stack.pop()!; + + if (typeof next === 'string') { + chunks.push(next); + } else if (next.type === 'text') { + chunks.push(next.data.replace(/\s+/g, ' ')); + } else if (next.type === 'tag') { + if (next.attribs['data-cmd'] === 'qz_toggle' || hasClass(next, 'load_img')) { + continue; + } + + if (next.name === 'br') { + chunks.push('\n'); + } else if (next.name === 'img') { + chunks.push(next.attribs.alt ?? ''); + } else { + if (['div', 'p', 'li'].includes(next.name)) { + chunks.push('\n'); + stack.push('\n'); + } + + for (let i = next.children.length - 1; i >= 0; i--) { + stack.push(next.children[i]); + } + } + } + } + + return chunks + .join('') + .replace(/ *\n */g, '\n') + .replace(/\n{3,}/g, '\n\n') + .trim(); +} + +function count(value: unknown): number | null { + if (typeof value !== 'number' && (typeof value !== 'string' || !/^\d+$/.test(value))) { + return null; + } + + const number = Number(value); + return Number.isSafeInteger(number) && number >= 0 ? number : null; +} + +function imageUrl(value: string | undefined): string | null { + if (!value) { + return null; + } + + try { + const url = new URL(value.startsWith('//') ? `https:${value}` : value); + return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : null; + } catch { + return null; + } +} + +/** Extract only the post's own content; comments, avatars and video covers are separate. */ +export function parseQzoneFeedContent( + html: string, + key: string, + uin: number, + appid: number, + likeCount?: unknown, + commentCount?: unknown, +): QzoneFeedContent { + const doc = parseDocument(html); + const elements = DomUtils.findAll(() => true, doc.children); + const body = elements.find( + (node) => hasClass(node, 'f-item') && node.attribs['data-key'] === key, + ); + const result: QzoneFeedContent = { + tid: null, + content: null, + content_complete: null, + images: null, + like_count: count(likeCount), + comment_count: count(commentCount), + }; + + if (!body) { + return result; + } + + let root = body; + + for (let parent = body.parent; parent && 'attribs' in parent; parent = parent.parent) { + if (hasClass(parent, 'f-single')) { + root = parent; + break; + } + } + + const bodyElements = DomUtils.findAll((node) => isContentNode(node, body), body.children); + const metadata = bodyElements.find( + (node) => + node.attribs.name === 'feed_data' && + node.attribs['data-uin'] === String(uin) && + node.attribs['data-fkey'] === key, + ); + + if (appid === 311 && metadata?.attribs['data-tid']) { + result.tid = metadata.attribs['data-tid']; + } + + const contentNodes = bodyElements.filter((node) => hasClass(node, 'f-info')); + const complete = contentNodes.find( + (node) => hasClass(node, 'qz_info_complete') && text(node) !== '', + ); + const content = complete ?? contentNodes.find((node) => !hasClass(node, 'qz_info_complete')); + + if (content) { + result.content = text(content); + result.content_complete = + !!complete || + !DomUtils.findAll((node) => node.attribs['data-cmd'] === 'qz_toggle', content.children) + .length; + } + + const images = new Set(); + + for (const item of bodyElements.filter((node) => hasClass(node, 'img-item'))) { + if (item.attribs['data-v_itemid'] || item.attribs['data-videotype']) { + continue; + } + + const full = imageUrl(item.attribs['data-originurl'] ?? item.attribs['data-url3']); + + if (full) { + images.add(full); + continue; + } + + for (const image of DomUtils.findAll((node) => node.name === 'img', item.children)) { + const url = imageUrl(image.attribs.truesrc ?? image.attribs.src); + + if (url) { + images.add(url); + } + } + } + + result.images = [...images]; + const like = DomUtils.findAll( + (node) => hasClass(node, 'qz_like_btn_v3') && isContentNode(node, root), + root.children, + )[0]; + result.like_count ??= count(like?.attribs['data-likecnt']); + return result; +} diff --git a/packages/protocol/src/web/qzone-feed-cursor.ts b/packages/protocol/src/web/qzone-feed-cursor.ts new file mode 100644 index 00000000..e9cf6243 --- /dev/null +++ b/packages/protocol/src/web/qzone-feed-cursor.ts @@ -0,0 +1,154 @@ +const numericFields = [ + 'begintime', + 'dayspac', + 'pagenum', + 'aisortEndTime', + 'aisortOffset', + 'aisortBeginTime', + 'aisortNextTime', + 'icServerTime', +] as const; +const stringFields = ['externparam', 'daylist', 'uinlist'] as const; +const fields = [...numericFields, ...stringFields]; +type StateField = (typeof fields)[number]; +export type QzoneFeedState = Record; + +export function initialQzoneFeedState(): QzoneFeedState { + return { + begintime: '0', + dayspac: '0', + pagenum: '1', + aisortEndTime: '0', + aisortOffset: '0', + aisortBeginTime: '0', + aisortNextTime: '0', + icServerTime: '0', + externparam: '', + daylist: '', + uinlist: '', + }; +} + +function record(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** Carry forward the fields used by the web client, including opaque server state. */ +export function nextQzoneFeedState( + main: Record, + previous: QzoneFeedState, +): QzoneFeedState { + const next = { ...previous }; + + for (const field of numericFields) { + const value = main[field]; + + if (value === undefined || value === '') { + continue; + } + + if ( + (typeof value !== 'number' && typeof value !== 'string') || + !/^\d+$/.test(String(value)) || + !Number.isSafeInteger(Number(value)) || + (field === 'pagenum' && Number(value) < 1) + ) { + throw new Error(`空间好友动态分页字段异常: ${field}`); + } + + next[field] = String(Number(value)); + } + + for (const field of stringFields) { + const value = main[field]; + + if (value === undefined || (value === '' && field !== 'uinlist')) { + continue; + } + + if (typeof value !== 'string' || value.length > 32_768) { + throw new Error(`空间好友动态分页字段异常: ${field}`); + } + + next[field] = value; + } + + return next; +} + +/** The server clock alone does not constitute pagination progress. */ +export function qzoneFeedPosition(state: QzoneFeedState): string { + return JSON.stringify( + fields.filter((field) => field !== 'icServerTime').map((field) => state[field]), + ); +} + +export function encodeQzoneFeedCursor(uin: string, page: number, state: QzoneFeedState): string { + if (!Number.isSafeInteger(page) || page < 2) { + throw new Error('空间好友动态分页页码超出范围'); + } + const cursor = Buffer.from(JSON.stringify({ version: 1, uin, page, state })).toString( + 'base64url', + ); + + if (cursor.length > 65_536) { + throw new Error('空间好友动态分页游标过大'); + } + + return cursor; +} + +export function decodeQzoneFeedCursor( + cursor: string, + uin: string, +): { + page: number; + state: QzoneFeedState; +} { + 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 ( + !record(value) || + value.version !== 1 || + value.uin !== uin || + typeof value.page !== 'number' || + !Number.isSafeInteger(value.page) || + value.page < 2 || + !record(value.state) + ) { + throw new Error('空间好友动态 cursor 无效或不属于当前账号'); + } + + const rawState = value.state; + + if ( + Object.keys(rawState).length !== fields.length || + !fields.every((field) => typeof rawState[field] === 'string') + ) { + throw new Error('无效的空间好友动态 cursor 状态'); + } + + const state = nextQzoneFeedState(rawState, initialQzoneFeedState()); + + if (fields.some((field) => state[field] !== rawState[field])) { + throw new Error('无效的空间好友动态 cursor 状态'); + } + + return { page: value.page, state }; +} diff --git a/packages/protocol/src/web/qzone.ts b/packages/protocol/src/web/qzone.ts index b87dab35..e2bd8246 100644 --- a/packages/protocol/src/web/qzone.ts +++ b/packages/protocol/src/web/qzone.ts @@ -1,6 +1,14 @@ import type { JsonValue } from '@snowluma/common/json'; import { createLogger } from '@snowluma/common/logger'; import { RequestUtil, cookieToString, getBknFromCookie } from './request-util'; +import { parseQzoneFeedContent, type QzoneFeedContent } from './qzone-feed-content'; +import { + decodeQzoneFeedCursor, + encodeQzoneFeedCursor, + initialQzoneFeedState, + nextQzoneFeedState, + qzoneFeedPosition, +} from './qzone-feed-cursor'; const log = createLogger('Bridge.Web'); @@ -638,13 +646,6 @@ export async function getQzoneMsgList( } // ─────────────── 好友动态 (friend feeds) — feeds3_html_more ─────────────── -// The friend-feed CGI returns each feed as a pre-rendered HTML blob plus a -// few structured fields. We surface the stable structured fields and pass -// the `html` through verbatim (deep HTML→segment parsing is out of scope — -// callers that want it parse the blob themselves). Exact field names / -// pagination cursor to be re-confirmed against a live capture, same posture -// as the msglist helper. - interface RawFeedItem { uin?: number | string; nickname?: string; @@ -654,6 +655,8 @@ interface RawFeedItem { key?: string; feedskey?: string; html?: string; + likecnt?: number | string; + commentcnt?: number | string; } interface RawFeedsResponse { @@ -662,6 +665,7 @@ interface RawFeedsResponse { message?: string; data?: { data?: RawFeedItem[] | null; + main?: Record; hasmore?: number | string; }; } @@ -689,107 +693,233 @@ export interface QzoneFeedsResult { has_more: boolean; } -/** Pure transform from the raw feeds response into the OneBot list. */ -export function mapFeeds(data: RawFeedsResponse): QzoneFeedsResult { - // The CGI pads the array with trailing `undefined`/null holes — drop them. - const list = (data.data?.data ?? []).filter((f): f is RawFeedItem => !!f); +export interface QzoneStructuredFeed extends QzoneFeed, QzoneFeedContent {} + +export interface QzoneFeedsPage extends QzoneFeedsResult { + feeds: QzoneStructuredFeed[]; + /** Opaque, account-bound continuation. Null at the end of the list. */ + next_cursor: string | null; +} + +function feedHasMore(data: RawFeedsResponse): boolean { + const value = data.data?.main === undefined ? data.data?.hasmore : data.data.main.hasMoreFeeds; + + if (value === true || value === 1 || value === '1') { + return true; + } + + if (value === false || value === 0 || value === '0') { + return false; + } + + throw new Error('空间好友动态缺少有效的分页结束标志'); +} + +/** Pure mapping; request continuation is attached by getQzoneFeeds. */ +export function mapFeeds(data: RawFeedsResponse): QzoneFeedsPage { + if (!Array.isArray(data.data?.data)) { + throw new Error('无法获取空间好友动态(响应结构异常)'); + } + + // The web payload pads lists with null/undefined; these are not feed entries. + const list = data.data.data.filter((item) => item != null); return { - feeds: list.map((f) => ({ - uin: Number(f.uin ?? 0), - nickname: f.nickname ?? '', - time: Number(f.abstime ?? 0), - appid: Number(f.appid ?? 0), - // `key` is the per-feed handle; `feedskey` is its older alias on some - // feed types. They name the same per-feed identifier here (NOT the - // list-level next-page cursor, which lives on data.* not the item). - key: String(f.key ?? f.feedskey ?? ''), - html: f.html ?? '', - })), - has_more: Number(data.data?.hasmore ?? 0) !== 0, + feeds: list.map((item) => { + if (typeof item !== 'object' || Array.isArray(item)) { + throw new Error('空间好友动态条目结构异常'); + } + + const feed: QzoneFeed = { + uin: Number(item.uin ?? 0), + nickname: item.nickname ?? '', + time: Number(item.abstime ?? 0), + appid: Number(item.appid ?? 0), + key: String(item.key ?? item.feedskey ?? ''), + html: item.html ?? '', + }; + + if ( + ![feed.uin, feed.time, feed.appid].every( + (n) => Number.isSafeInteger(n) && n >= 0, + ) || + typeof feed.nickname !== 'string' || + typeof feed.html !== 'string' + ) { + throw new Error('空间好友动态条目字段异常'); + } + + return { + ...feed, + ...parseQzoneFeedContent( + feed.html, + feed.key, + feed.uin, + feed.appid, + item.likecnt, + item.commentcnt, + ), + }; + }), + has_more: feedHasMore(data), + next_cursor: null, }; } -/** - * Fetch the 好友动态 (friend-feed) list via the feeds3_html_more CGI on - * ic2.qzone.qq.com, routed through the h5.qzone.qq.com proxy gateway — the - * same gateway {@link getQzoneMsgList} and group-album use, because the - * qzone.qq.com cookie jar only authenticates against the proxy origin - * (hitting ic2 directly fails the referer/same-origin check). Body is - * requested as JSONP (`format=jsonp` + a callback) and parsed with the - * shared tolerant parser, matching slice-1's contract exactly. - * - * `pageNum` is 1-based; `count` is the page size. PAGINATION CAVEAT: this - * CGI's reliable deep-pagination is driven by a time cursor - * (begintime/externparam/usertime carried forward from the previous page), - * which we do not yet thread — so `pageNum` is dependable for the first - * page and `has_more` only signals whether more exist, not a stable - * page-2 fetch. Cursor pagination is deferred until a live capture. - * - * Same throw-on-auth-failure contract as {@link getQzoneMsgList}: a missing - * `data.data` array means the cookie/auth failed and throws, whereas a - * genuinely empty feed (`data.data: []`) maps to an empty list. - */ +/** Read one page. Legacy page numbers walk continuations from the beginning. */ export async function getQzoneFeeds( cookieObject: Record, selfUin: string, pageNum = 1, count = 10, -): Promise { + cursor?: string, +): Promise { if (!cookieObject || typeof cookieObject !== 'object') { throw new Error('cookieObject is required'); } + if ( + !Number.isSafeInteger(pageNum) || + pageNum < 1 || + !Number.isSafeInteger(count) || + count < 1 || + count > 50 + ) { + throw new Error('空间好友动态页码或数量无效'); + } + + const start = + cursor === undefined + ? { page: 1, state: initialQzoneFeedState() } + : decodeQzoneFeedCursor(cursor, selfUin); + + if (cursor !== undefined && pageNum !== 1 && pageNum !== start.page) { + throw new Error('page_num 与空间好友动态 cursor 不匹配'); + } + + const target = cursor === undefined ? pageNum : start.page; const bkn = getBknFromCookie(cookieObject); - const url = `https://h5.qzone.qq.com/proxy/domain/ic2.qzone.qq.com/cgi-bin/feeds/feeds3_html_more?${new URLSearchParams( - { + let state = start.state; + const seen = new Set([qzoneFeedPosition(state)]); + log.debug( + 'getQzoneFeeds start (uin=%s page=%d count=%d cursor=%s)', + selfUin, + target, + count, + cursor !== undefined, + ); + + for (let page = start.page; page <= target; page++) { + const query = new URLSearchParams({ uin: selfUin, scope: '0', view: '1', - filter: 'all', + gid: '', flag: '1', + filter: 'all', applist: 'all', - pagenum: String(pageNum), + refresh: '0', + firstGetGroup: '0', + mixnocache: '0', + scene: '0', + sidomain: 'qzonestyle.gtimg.cn', count: String(count), - aisortEndTime: '0', - aisortOffset: '0', - aisortBeginTime: '0', - begintime: '0', + ...state, + getAisort: state.aisortNextTime, g_tk: bkn, callback: '_preloadCallback', format: 'jsonp', useutf8: '1', outputhtmlfeed: '1', - }, - ).toString()}`; + usertime: String(Date.now()), + rd: String(Math.random()), + windowId: String(Math.random()), + }); + query.delete('aisortNextTime'); + const url = `https://h5.qzone.qq.com/proxy/domain/ic2.qzone.qq.com/cgi-bin/feeds/feeds3_html_more?${query}`; - const text = await RequestUtil.HttpGetText(url, 'GET', '', { - Cookie: cookieToString(cookieObject), - }); - log.trace('getQzoneFeeds raw body (uin=%s): %s', selfUin, text); - // feeds3_html_more's payload is a JS object literal, not JSON — parse it as - // inert data (see parseQzoneCallback; never executed) rather than JSON.parse. - const data = parseQzoneCallback(text); + try { + const body = await RequestUtil.HttpGetText(url, 'GET', '', { + Cookie: cookieToString(cookieObject), + }); + const data = parseQzoneCallback(body); - if (typeof data.code === 'number' && data.code !== 0) { - log.warn( - 'getQzoneFeeds: non-zero code (uin=%s) code=%d msg=%s', - selfUin, - data.code, - data.message, - ); - throw new Error(`qzone feeds failed: code=${data.code} ${data.message ?? ''}`.trim()); + if (data.code !== 0 || (data.subcode !== undefined && data.subcode !== 0)) { + throw new Error( + `qzone feeds failed: code=${data.code} subcode=${data.subcode ?? 0} ${typeof data.message === 'string' ? data.message : ''}`.trim(), + ); + } + + const main = data.data?.main; + + if ( + main !== undefined && + (main === null || typeof main !== 'object' || Array.isArray(main)) + ) { + throw new Error('空间好友动态分页信息结构异常'); + } + + if (main?.error !== undefined && main.error !== '') { + throw new Error('空间好友动态服务端报告拉取失败'); + } + + const result = mapFeeds(data); + + if (result.has_more) { + if (!main) { + throw new Error('空间好友动态缺少下一页游标'); + } + + state = nextQzoneFeedState(main, state); + const position = qzoneFeedPosition(state); + + if (seen.has(position)) { + throw new Error('空间好友动态分页游标未推进'); + } + + seen.add(position); + result.next_cursor = encodeQzoneFeedCursor(selfUin, page + 1, state); + } + + const unavailable = result.feeds.filter( + (feed) => feed.appid === 311 && feed.content === null, + ).length; + + if (unavailable) { + log.warn( + 'getQzoneFeeds content unavailable (uin=%s page=%d entries=%d)', + selfUin, + page, + unavailable, + ); + } + + log.debug( + 'getQzoneFeeds page (uin=%s page=%d entries=%d more=%s)', + selfUin, + page, + result.feeds.length, + result.has_more, + ); + + if (page === target) { + return result; + } + + if (!result.has_more) { + return { feeds: [], has_more: false, next_cursor: null }; + } + } catch (error) { + log.warn( + 'getQzoneFeeds failed (uin=%s page=%d): %s', + selfUin, + page, + error instanceof Error ? error.message : String(error), + ); + throw error; + } } - if (!Array.isArray(data.data?.data)) { - log.warn( - 'getQzoneFeeds: no data array in response (uin=%s) — likely auth/cookie failure or unverified response shape; body head=%s', - selfUin, - text.slice(0, 300), - ); - throw new Error(`无法获取空间好友动态(响应结构异常): ${text.slice(0, 200)}`); - } - - return mapFeeds(data); + throw new Error('空间好友动态分页未完成'); } // ─────────────── 发说说 (publish emotion) — emotion_cgi_publish_v6 ─────────────── diff --git a/packages/protocol/tests/web/qzone-feeds-parse.test.ts b/packages/protocol/tests/web/qzone-feeds-parse.test.ts index e8d23afc..6767b600 100644 --- a/packages/protocol/tests/web/qzone-feeds-parse.test.ts +++ b/packages/protocol/tests/web/qzone-feeds-parse.test.ts @@ -44,6 +44,14 @@ describe('qzone feeds JS-literal parsing (issue #182)', () => { // \xNN escapes decoded by the JS eval, html passed through verbatim. expect(f.html).toContain('
  • { diff --git a/packages/protocol/tests/web/qzone-feeds.test.ts b/packages/protocol/tests/web/qzone-feeds.test.ts new file mode 100644 index 00000000..cdec129a --- /dev/null +++ b/packages/protocol/tests/web/qzone-feeds.test.ts @@ -0,0 +1,286 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { getQzoneFeeds } from '../../src/web/qzone'; +import { RequestUtil } from '../../src/web/request-util'; +import { parseQzoneFeedContent } from '../../src/web/qzone-feed-content'; + +const cookies = { p_skey: 'fixture' }; + +function page(key: string, more: boolean, state: Record = {}) { + return `_preloadCallback(${JSON.stringify({ + code: 0, + data: { + main: { + hasMoreFeeds: more, + error: '', + begintime: '1700000000', + dayspac: '5', + pagenum: '2', + externparam: 'basetime=1700000000&pagenum=2&opaque=a%26b', + ...state, + }, + data: [ + { + uin: '10002', + nickname: 'Reader', + abstime: '1700000001', + appid: '311', + key, + html: `
  • +
    Hello & friend
    Second line[笑]
    + +
    +
    赞 +
    Another person's comment
    +
  • `, + commentcnt: '3', + }, + null, + ], + }, + })});`; +} + +describe('Qzone friend feed continuation', () => { + afterEach(() => vi.restoreAllMocks()); + + it('uses server continuation state and preserves structured content alongside legacy fields', async () => { + const request = vi + .spyOn(RequestUtil, 'HttpGetText') + .mockResolvedValueOnce( + page('first', true, { + aisortEndTime: '17', + aisortOffset: '4', + aisortBeginTime: '11', + aisortNextTime: '2', + icServerTime: '1700000010', + daylist: 'd', + uinlist: '10002', + }), + ) + .mockResolvedValueOnce(page('second', false)); + const first = await getQzoneFeeds(cookies, '10001'); + expect(first.has_more).toBe(true); + expect(first.next_cursor).toEqual(expect.any(String)); + expect(first.feeds[0]).toMatchObject({ + uin: 10002, + appid: 311, + key: 'first', + tid: 'first', + content: 'Hello & friend\nSecond line[笑]', + content_complete: true, + images: ['https://example.com/full.jpg?a=1&b=2'], + like_count: 12, + comment_count: 3, + html: expect.stringContaining('Another person'), + }); + const second = await getQzoneFeeds(cookies, '10001', 1, 10, first.next_cursor!); + expect(second).toMatchObject({ has_more: false, next_cursor: null }); + expect(second.feeds[0].key).toBe('second'); + const query = new URL(request.mock.calls[1][0]).searchParams; + expect(Object.fromEntries(query)).toMatchObject({ + uin: '10001', + pagenum: '2', + begintime: '1700000000', + dayspac: '5', + externparam: 'basetime=1700000000&pagenum=2&opaque=a%26b', + aisortEndTime: '17', + aisortOffset: '4', + aisortBeginTime: '11', + getAisort: '2', + icServerTime: '1700000010', + daylist: 'd', + uinlist: '10002', + refresh: '0', + }); + expect(request).toHaveBeenCalledTimes(2); + }); + + it('resolves a legacy page number by traversing continuations, not restarting at that number', async () => { + const request = vi + .spyOn(RequestUtil, 'HttpGetText') + .mockResolvedValueOnce(page('first', true)) + .mockResolvedValueOnce(page('second', false)); + const result = await getQzoneFeeds(cookies, '10001', 2, 20); + expect(result.feeds[0].key).toBe('second'); + expect(request.mock.calls.map(([url]) => new URL(url).searchParams.get('pagenum'))).toEqual( + ['1', '2'], + ); + }); + + it('rejects stalled continuation instead of looping or silently ending the list', async () => { + const request = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(page('same', true)); + await expect(getQzoneFeeds(cookies, '10001', 3)).rejects.toThrow(/未推进|advance/); + expect(request).toHaveBeenCalledTimes(2); + }); + + it('keeps empty intermediate pages traversable and stops at the real end', async () => { + const empty = JSON.parse(page('unused', true).slice(17, -2)); + empty.data.data = [null]; + const request = vi + .spyOn(RequestUtil, 'HttpGetText') + .mockResolvedValueOnce(JSON.stringify(empty)) + .mockResolvedValueOnce(page('last', false)); + const first = await getQzoneFeeds(cookies, '10001'); + expect(first.feeds).toEqual([]); + expect(first.has_more).toBe(true); + expect( + (await getQzoneFeeds(cookies, '10001', 1, 10, first.next_cursor!)).feeds[0].key, + ).toBe('last'); + request.mockReset().mockResolvedValue(page('last', false)); + expect(await getQzoneFeeds(cookies, '10001', 8)).toEqual({ + feeds: [], + has_more: false, + next_cursor: null, + }); + expect(request).toHaveBeenCalledTimes(1); + }); + + it('rejects foreign-account, corrupt and mismatched-page cursors before HTTP', async () => { + const request = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(page('first', true)); + const first = await getQzoneFeeds(cookies, '10001'); + request.mockClear(); + await expect(getQzoneFeeds(cookies, '10002', 1, 10, first.next_cursor!)).rejects.toThrow( + '账号', + ); + await expect(getQzoneFeeds(cookies, '10001', 3, 10, first.next_cursor!)).rejects.toThrow( + '不匹配', + ); + + for (const cursor of ['', 'bad!', 'e30', 'a'.repeat(65537)]) { + await expect(getQzoneFeeds(cookies, '10001', 1, 10, cursor)).rejects.toThrow('cursor'); + } + + const raw = JSON.parse(Buffer.from(first.next_cursor!, 'base64url').toString()); + raw.state.url = 'https://example.com/foreign'; + await expect( + getQzoneFeeds( + cookies, + '10001', + 1, + 10, + Buffer.from(JSON.stringify(raw)).toString('base64url'), + ), + ).rejects.toThrow('cursor'); + expect(request).not.toHaveBeenCalled(); + }); + + it('preserves opaque parameters and sort state when a later page omits optional fields', async () => { + const request = vi + .spyOn(RequestUtil, 'HttpGetText') + .mockResolvedValueOnce(page('first', true, { aisortOffset: '9', aisortNextTime: '2' })) + .mockResolvedValueOnce( + page('second', true, { + pagenum: '3', + begintime: '1699999000', + externparam: '', + }), + ) + .mockResolvedValueOnce(page('third', false)); + const first = await getQzoneFeeds(cookies, '10001'); + const second = await getQzoneFeeds(cookies, '10001', 1, 10, first.next_cursor!); + await getQzoneFeeds(cookies, '10001', 1, 10, second.next_cursor!); + const query = new URL(request.mock.calls[2][0]).searchParams; + expect(query.get('aisortOffset')).toBe('9'); + expect(query.get('getAisort')).toBe('2'); + expect(query.get('externparam')).toBe('basetime=1700000000&pagenum=2&opaque=a%26b'); + }); + + it('does not regard the changing server clock as pagination progress', async () => { + vi.spyOn(RequestUtil, 'HttpGetText') + .mockResolvedValueOnce(page('first', true, { icServerTime: '20' })) + .mockResolvedValueOnce(page('first', true, { icServerTime: '21' })); + await expect(getQzoneFeeds(cookies, '10001', 3)).rejects.toThrow('未推进'); + }); + + it.each([ + { code: 0, subcode: -1, data: { data: [] } }, + { code: 0, data: { main: { error: 'more', hasMoreFeeds: false }, data: [] } }, + { code: 0, data: { main: { hasMoreFeeds: 'false' }, data: [] } }, + { code: 0, data: { main: { hasMoreFeeds: true }, data: [] } }, + { code: 0, data: { main: { hasMoreFeeds: true, pagenum: {} }, data: [] } }, + { code: 0, data: { hasmore: 1, data: [] } }, + { code: 0, data: { main: [], data: [] } }, + { code: 0, data: { main: { hasMoreFeeds: false }, data: [false] } }, + { code: 0, data: { main: { hasMoreFeeds: false }, data: [{ uin: 'broken' }] } }, + ])( + 'exposes malformed or failed responses instead of returning an empty success (%j)', + async (response) => { + vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(JSON.stringify(response)); + await expect(getQzoneFeeds(cookies, '10001')).rejects.toThrow(); + }, + ); + + it('propagates transport failures without retrying or resetting pagination', async () => { + const request = vi + .spyOn(RequestUtil, 'HttpGetText') + .mockRejectedValue(new Error('network unavailable')); + await expect(getQzoneFeeds(cookies, '10001')).rejects.toThrow('network unavailable'); + expect(request).toHaveBeenCalledTimes(1); + }); +}); + +describe('Qzone friend feed content', () => { + function parse(body: string, like?: unknown, comments?: unknown) { + return parseQzoneFeedContent( + `
    ${body}
    `, + 'post', + 10002, + 311, + like, + comments, + ); + } + + it('marks excerpts as incomplete, removes expansion controls and prefers the full body when present', () => { + const excerpt = + ''; + expect(parse(excerpt + '
    ')).toMatchObject({ + content: 'Start', + content_complete: false, + }); + expect( + parse(excerpt + '
    Start and finish
    '), + ).toMatchObject({ content: 'Start and finish', content_complete: true }); + }); + + it('preserves explicit zero, distinguishes unknown values and never estimates counts from visible comments', () => { + expect(parse('
    ', '0', 0)).toMatchObject({ + content: '', + content_complete: true, + images: [], + like_count: 0, + comment_count: 0, + }); + expect(parse('
    one
    ', '', 'many')).toMatchObject({ + content: null, + content_complete: null, + like_count: null, + comment_count: null, + }); + expect( + parseQzoneFeedContent('
    unrecognised template
    ', 'post', 10002, 311), + ).toMatchObject({ tid: null, content: null, images: null }); + }); + + it('excludes video covers, nested reposts, avatars and comment pictures', () => { + expect( + parse(` + +
    + +
    +
    repost
    + + + `), + ).toMatchObject({ content: null, images: ['https://example.com/photo.jpg?a=1&b=2'] }); + }); + + it('parses markup as inert data and decodes entities without including script or style text', () => { + expect( + parse( + '
    <b>😀

    Next

    ', + ), + ).toMatchObject({ content: '😀\nNext' }); + }); +}); diff --git a/packages/protocol/tests/web/qzone.test.ts b/packages/protocol/tests/web/qzone.test.ts index 806fb72a..e161289f 100644 --- a/packages/protocol/tests/web/qzone.test.ts +++ b/packages/protocol/tests/web/qzone.test.ts @@ -237,7 +237,7 @@ describe('qzone / mapFeeds', () => { ], }, }); - expect(out).toEqual({ + expect(out).toMatchObject({ has_more: true, feeds: [ { @@ -261,7 +261,11 @@ describe('qzone / mapFeeds', () => { }); it('tolerates missing fields and empty data', () => { - expect(mapFeeds({ code: 0, data: { data: [] } })).toEqual({ feeds: [], has_more: false }); + expect(mapFeeds({ code: 0, data: { hasmore: 0, data: [] } })).toEqual({ + feeds: [], + has_more: false, + next_cursor: null, + }); }); }); @@ -272,12 +276,12 @@ describe('qzone / getQzoneFeeds (HTTP layer)', () => { const spy = vi .spyOn(RequestUtil, 'HttpGetText') .mockResolvedValue( - '_preloadCallback({"code":0,"data":{"hasmore":1,"data":[{"uin":12345,"nickname":"Alice","abstime":1700000000,"appid":311,"key":"K1","html":"
    a
    "}]}});', + '_preloadCallback({"code":0,"data":{"main":{"hasMoreFeeds":true,"pagenum":"2","externparam":"page=2","begintime":"1699999999"},"data":[{"uin":12345,"nickname":"Alice","abstime":1700000000,"appid":311,"key":"K1","html":"
    a
    "}]}});', ); - const out = await getQzoneFeeds(cookies, '10000', 2, 10); + const out = await getQzoneFeeds(cookies, '10000', 1, 10); - expect(out).toEqual({ + expect(out).toMatchObject({ has_more: true, feeds: [ { @@ -302,7 +306,7 @@ describe('qzone / getQzoneFeeds (HTTP layer)', () => { ); const q = new URLSearchParams((url as string).split('?')[1]); expect(q.get('uin')).toBe('10000'); - expect(q.get('pagenum')).toBe('2'); + expect(q.get('pagenum')).toBe('1'); expect(q.get('count')).toBe('10'); expect(q.get('g_tk')).toBe(expectedGtk); // The request asks for JSONP — pin it so the JSONP-bodied response above @@ -317,6 +321,7 @@ describe('qzone / getQzoneFeeds (HTTP layer)', () => { await expect(getQzoneFeeds(cookies, '10000')).resolves.toEqual({ feeds: [], has_more: false, + next_cursor: null, }); }); diff --git a/packages/sdk/MESSAGING.md b/packages/sdk/MESSAGING.md index 091054d4..60420de6 100644 --- a/packages/sdk/MESSAGING.md +++ b/packages/sdk/MESSAGING.md @@ -122,3 +122,45 @@ console.log(result.comment_id, result.parent_comment_id); `post`, `postOwnerUin`, `parentComment` and `selectedReply` above are the post and comments chosen by the caller. For an ordinary reply to the parent, omit `reply_uin` and `reply_name`. For a nested reply, keep the **top-level parent** in `comment_id`/`comment_uin`; do not substitute the nested reply's own ID. New servers also include `parent_comment_id` and `parent_comment_uin` on each inline reply to preserve this association. Inline replies may be incomplete; absence from a page does not mean a comment was deleted. On success, `comment_id` is the **new reply's** ID and the result includes its parent ID and author. Those parent fields are optional in SDK types for compatibility with older servers. Non-empty `images` with a parent comment are rejected before upload: threaded replies currently support text only. Incomplete recipient/parent parameters are errors, and a failed reply never falls back to an ordinary comment or retries automatically. If an acknowledgement is malformed after sending, check the thread before retrying; the reply may already exist. + +## Read structured Qzone friend feeds + +`get_qzone_feeds` retains `page_num`, `count`, `feeds`, `has_more`, and each feed's +original `html`. Newer servers also return `tid`, `content`, `content_complete`, +`images`, `like_count`, and `comment_count`. A `null` value means the source did +not establish that field; it does not mean zero or an empty post. A collapsed +excerpt has `content_complete: false`. Images cover only pictures available in +the post body, excluding avatars, comment pictures and video covers; they are +not a complete album listing. Non-post feed types may have no `tid`. + +Use the returned `next_cursor` unchanged to continue on the same account: + +```ts +let cursor: string | undefined; +while (true) { + const page = await bot.raw('get_qzone_feeds', { count: 10, cursor }); + for (const feed of page.feeds) { + console.log(feed.content, feed.images); + } + if (!page.has_more) { + break; + } + if (!page.next_cursor) { + throw new Error('This server did not provide a continuation cursor'); + } + cursor = page.next_cursor; +} +``` + +Omit `page_num` when using a cursor, or supply its corresponding page number. +Without a cursor, requesting a later `page_num` walks earlier pages from the +beginning and can take longer; requesting beyond the end returns an empty page. +The service may return fewer entries than `count`, including empty intermediate +pages with a continuation. Follow `has_more` and `next_cursor`, not array length. +Invalid, foreign-account or stalled cursors fail visibly. Results reflect a live +feed, not a frozen snapshot; posts may change between requests. + +The added result fields are optional in SDK types so older servers and existing +consumer-created result objects remain supported. MCP discovers the same fields +and cursor examples through `get_action` and calls this read-only action through +`query_action`; its existing mode restrictions are unchanged. diff --git a/packages/sdk/src/types/params.ts b/packages/sdk/src/types/params.ts index cd7d5ef9..83ffc1ed 100644 --- a/packages/sdk/src/types/params.ts +++ b/packages/sdk/src/types/params.ts @@ -570,9 +570,11 @@ export interface GetQzoneMsgListParams extends JsonObject { } export interface GetQzoneFeedsParams extends JsonObject { - /** Page number starts at 1; only the first page is reliable upstream. */ + /** Starts at 1. Without a cursor, earlier pages are traversed to reach this page. */ page_num?: ActionNumberInput; count?: ActionNumberInput; + /** Pass next_cursor unchanged for the same account; omit page_num when continuing. */ + cursor?: string; } export interface QzoneMsgIdParams extends JsonObject { diff --git a/packages/sdk/src/types/results.ts b/packages/sdk/src/types/results.ts index 03d241c4..96c2f847 100644 --- a/packages/sdk/src/types/results.ts +++ b/packages/sdk/src/types/results.ts @@ -403,11 +403,22 @@ export interface QzoneFeed extends JsonObject { appid: number; key: string; html: string; + /** Newer servers return these fields; null means the source could not establish the value. */ + tid?: string | null; + content?: string | null; + /** False for a collapsed excerpt; null when content is unavailable. */ + content_complete?: boolean | null; + /** Images visible in the post body, excluding avatars, comment images and video covers. */ + images?: string[] | null; + like_count?: number | null; + comment_count?: number | null; } export interface QzoneFeedsResult extends JsonObject { feeds: QzoneFeed[]; has_more: boolean; + /** Opaque account-bound continuation; null at the end, absent on older servers. */ + next_cursor?: string | null; } export interface QzonePublishResult extends JsonObject { diff --git a/packages/sdk/tests/fixtures/action-contracts.ts b/packages/sdk/tests/fixtures/action-contracts.ts index 4fd8ba1d..b8765a30 100644 --- a/packages/sdk/tests/fixtures/action-contracts.ts +++ b/packages/sdk/tests/fixtures/action-contracts.ts @@ -54,7 +54,7 @@ export const actionParams = { get_group_signed_list: { group_id: '10001' }, get_msg_emoji_likes: { message_id: '-42' }, get_qun_album_list: { group_id: '10001', attach_info: '' }, - get_qzone_feeds: { page_num: '1', count: '10' }, + 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_rkey_server: {}, get_share_link: fileset, diff --git a/packages/sdk/tests/fixtures/action-types.mts b/packages/sdk/tests/fixtures/action-types.mts index 5aabf96c..d0688a95 100644 --- a/packages/sdk/tests/fixtures/action-types.mts +++ b/packages/sdk/tests/fixtures/action-types.mts @@ -69,6 +69,20 @@ ws.downloadFileStream({}); const feeds = await http.raw('get_qzone_feeds', { page_num: '2', count: 10 }); const more: boolean = feeds.has_more; const author: number = feeds.feeds[0].uin; +export const legacyFeedHtml: string = feeds.feeds[0].html; +export const feedContent: string | null | undefined = feeds.feeds[0].content; +export const feedPhotos: string[] | null | undefined = feeds.feeds[0].images; +export const feedLikeCount: number | null | undefined = feeds.feeds[0].like_count; +export const feedCursor: string | null | undefined = feeds.next_cursor; +if (feedCursor) { + await http.raw('get_qzone_feeds', { cursor: feedCursor, count: 10 }); +} +export const legacyFeedsResult: ActionResult<'get_qzone_feeds'> = { + feeds: [{ uin: 10002, nickname: 'User', time: 1, appid: 311, key: 'post', html: '' }], + has_more: false, +}; +// @ts-expect-error continuation tokens must be strings +http.raw('get_qzone_feeds', { cursor: 123 }); const qzoneReply = await http.raw('comment_qzone', actionParams.comment_qzone); export const qzoneReplyId: string = qzoneReply.comment_id; export const qzoneParentId: string | undefined = qzoneReply.parent_comment_id; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 726c0c65..e76c0784 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -305,6 +305,9 @@ importers: '@snowluma/sqlite': specifier: workspace:* version: link:../sqlite + htmlparser2: + specifier: 10.0.0 + version: 10.0.0 devDependencies: '@types/node': specifier: 'catalog:' @@ -2406,6 +2409,19 @@ packages: detect-node-es@1.1.0: resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==} + dom-serializer@2.0.0: + resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==} + + domelementtype@2.3.0: + resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==} + + domhandler@5.0.3: + resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==} + engines: {node: '>= 4'} + + domutils@3.2.2: + resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==} + dunder-proto@1.0.1: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} @@ -2424,6 +2440,14 @@ packages: resolution: {integrity: sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==} engines: {node: '>=10.13.0'} + entities@4.5.0: + resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} + engines: {node: '>=0.12'} + + entities@6.0.1: + resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} + engines: {node: '>=0.12'} + env-paths@2.2.1: resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} engines: {node: '>=6'} @@ -2711,6 +2735,9 @@ packages: html-escaper@2.0.2: resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==} + htmlparser2@10.0.0: + resolution: {integrity: sha512-TwAZM+zE5Tq3lrEHvOlvwgj1XLWQCtaaibSN11Q+gGBAS7Y1uZSWwXXRe4iF6OXnaq1riyQAPFOBtYc77Mxq0g==} + http-errors@2.0.1: resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==} engines: {node: '>= 0.8'} @@ -5310,6 +5337,24 @@ snapshots: detect-node-es@1.1.0: {} + dom-serializer@2.0.0: + dependencies: + domelementtype: 2.3.0 + domhandler: 5.0.3 + entities: 4.5.0 + + domelementtype@2.3.0: {} + + domhandler@5.0.3: + dependencies: + domelementtype: 2.3.0 + + domutils@3.2.2: + dependencies: + dom-serializer: 2.0.0 + domelementtype: 2.3.0 + domhandler: 5.0.3 + dunder-proto@1.0.1: dependencies: call-bind-apply-helpers: 1.0.2 @@ -5327,6 +5372,10 @@ snapshots: graceful-fs: 4.2.11 tapable: 2.3.2 + entities@4.5.0: {} + + entities@6.0.1: {} + env-paths@2.2.1: optional: true @@ -5658,6 +5707,13 @@ snapshots: html-escaper@2.0.2: {} + htmlparser2@10.0.0: + dependencies: + domelementtype: 2.3.0 + domhandler: 5.0.3 + domutils: 3.2.2 + entities: 6.0.1 + http-errors@2.0.1: dependencies: depd: 2.0.0