feat(qzone): get_qzone_feeds — read friend feeds (好友动态) via web API

Second read-only Qzone slice. getQzoneFeeds over ic2.qzone.qq.com's
feeds3_html_more CGI, same cookie/g_tk plumbing + JSONP-tolerant parse +
throw-on-auth-failure contract as get_qzone_msg_list. Surfaces the stable
structured fields (uin/nickname/time/appid/key) and passes the
pre-rendered html blob through verbatim — deep HTML→segment parsing is
left to callers. Paginated via page_num (1-based) + count.

- protocol/web/qzone.ts: getQzoneFeeds + mapFeeds.
- core: QzoneApi.getFeeds (always the bot's own identity).
- onebot: get_qzone_feeds action; regenerated MCP catalog.
- tests: feeds mapping, HTTP url/params, empty-feed→[], auth-throw,
  and bridge pageNum/count threading.

Exact CGI field names / pagination cursor to be re-confirmed against a
live capture (same posture as the msglist helper).
This commit is contained in:
DrSmoothl committed 2026-06-20 01:31:36 +08:00
1 parent 0083a8fb07
commit 094dc12f0c
6 files changed
+293 -3

No files matched your search

+15 -1
View File
@@ -1,4 +1,9 @@
import { getQzoneMsgList, type QzoneMsgListResult } from '@snowluma/protocol/web/qzone';
import {
getQzoneFeeds,
getQzoneMsgList,
type QzoneFeedsResult,
type QzoneMsgListResult,
} from '@snowluma/protocol/web/qzone';
import type { BridgeContext } from '../bridge-context';
/**
@@ -19,4 +24,13 @@ export class QzoneApi {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneMsgList(cookieObject, uin, pos, num);
}
/**
* 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。
* 始终以机器人自己的身份拉取好友动态。
*/
async getFeeds(pageNum = 1, count = 10): Promise<QzoneFeedsResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
}
}
@@ -39,4 +39,13 @@ describe('apis/qzone', () => {
await new QzoneApi(bridge as never).getMsgList(20002, 5, 50);
expect(fetchSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '20002', 5, 50);
});
it('getFeeds always uses the bot\'s own uin and threads pageNum/count', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const feedsSpy = vi.spyOn(qzoneWeb, 'getQzoneFeeds').mockResolvedValue({ feeds: [], has_more: false });
await new QzoneApi(bridge as never).getFeeds(3, 20);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20);
});
});
+53 -1
View File
@@ -3000,6 +3000,58 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "群相册"
},
{
"name": "get_qzone_feeds",
"aliases": [],
"summary": "获取 QQ 空间好友动态(feed)",
"readOnly": true,
"params": [
{
"name": "page_num",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "页码(1 起)",
"default": 1
},
{
"name": "count",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 50
},
"desc": "本页数量",
"default": 10
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"page_num": {
"type": "integer",
"minimum": 1,
"description": "页码(1 起)",
"default": 1
},
"count": {
"type": "integer",
"minimum": 1,
"maximum": 50,
"description": "本页数量",
"default": 10
}
},
"additionalProperties": true
},
"category": "空间"
},
{
"name": "get_qzone_msg_list",
"aliases": [],
@@ -6641,6 +6693,6 @@ export const CATEGORIES: CatalogCategory[] = [
},
{
"category": "空间",
"count": 1
"count": 2
}
];
+21
View File
@@ -26,6 +26,27 @@ export const actions = [
}
},
}),
// get_qzone_feeds — 获取好友动态(feed)。只读,始终以机器人自己身份拉取。
// 每条 feed 含结构化字段 + 预渲染 html 原样透传(深度解析交由调用方)。
defineAction({
name: 'get_qzone_feeds',
readOnly: true,
summary: '获取 QQ 空间好友动态(feed)',
params: {
page_num: f.int({ min: 1 }).describe('页码(1 起)').default(1),
count: f.int({ min: 1, max: 50 }).describe('本页数量').default(10),
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.qzone.getFeeds(p.page_num, p.count);
return okResponse(res as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get qzone feeds';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
+125
View File
@@ -158,3 +158,128 @@ export async function getQzoneMsgList(
return mapMsgList(data);
}
// ─────────────── 好友动态 (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;
abstime?: number | string;
appid?: number | string;
typeid?: number | string;
key?: string;
feedskey?: string;
html?: string;
}
interface RawFeedsResponse {
code?: number;
subcode?: number;
message?: string;
data?: {
data?: RawFeedItem[] | null;
hasmore?: number | string;
};
}
/** One friend-feed entry in a normalised, OneBot-friendly form. */
export interface QzoneFeed {
[key: string]: JsonValue;
/** Author uin. */
uin: number;
nickname: string;
/** Unix seconds the feed was posted. */
time: number;
/** Qzone app id (311 = 说说, 4 = 相册, …). */
appid: number;
/** Feed key — the handle Qzone uses to address this feed. */
key: string;
/** Pre-rendered HTML blob for the feed (passed through verbatim). */
html: string;
}
export interface QzoneFeedsResult {
[key: string]: JsonValue;
feeds: QzoneFeed[];
/** Whether the server reports more pages after this one. */
has_more: boolean;
}
/** Pure transform from the raw feeds response into the OneBot list. */
export function mapFeeds(data: RawFeedsResponse): QzoneFeedsResult {
const list = data.data?.data ?? [];
return {
feeds: list.map((f) => ({
uin: Number(f.uin ?? 0),
nickname: f.nickname ?? '',
time: Number(f.abstime ?? 0),
appid: Number(f.appid ?? 0),
key: String(f.key ?? f.feedskey ?? ''),
html: f.html ?? '',
})),
has_more: Number(data.data?.hasmore ?? 0) !== 0,
};
}
/**
* Fetch the 好友动态 (friend-feed) list via ic2.qzone.qq.com's
* feeds3_html_more CGI. `pageNum` is 1-based; `count` is the page size.
* Same cookie/g_tk plumbing and 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.
*/
export async function getQzoneFeeds(
cookieObject: Record<string, string>,
selfUin: string,
pageNum = 1,
count = 10,
): Promise<QzoneFeedsResult> {
if (!cookieObject || typeof cookieObject !== 'object') {
throw new Error('cookieObject is required');
}
const bkn = getBknFromCookie(cookieObject);
const url = `https://ic2.qzone.qq.com/cgi-bin/feeds/feeds3_html_more?${new URLSearchParams(
{
uin: selfUin,
scope: '0',
view: '1',
filter: 'all',
flag: '1',
applist: 'all',
pagenum: String(pageNum),
count: String(count),
aisortEndTime: '0',
aisortOffset: '0',
aisortBeginTime: '0',
begintime: '0',
format: 'json',
g_tk: bkn,
useutf8: '1',
outputhtmlfeed: '1',
},
).toString()}`;
const text = await RequestUtil.HttpGetText(url, 'GET', '', {
Cookie: cookieToString(cookieObject),
});
const data = parseQzoneJson<RawFeedsResponse>(text);
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 (!Array.isArray(data.data?.data)) {
log.warn('getQzoneFeeds: no data array in response (uin=%s) — likely auth/cookie failure', selfUin);
throw new Error('无法获取空间好友动态');
}
return mapFeeds(data);
}
+70 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { getQzoneMsgList, mapMsgList, parseQzoneJson } from '@snowluma/protocol/web/qzone';
import { getQzoneFeeds, getQzoneMsgList, mapFeeds, mapMsgList, parseQzoneJson } from '@snowluma/protocol/web/qzone';
import { RequestUtil } from '@snowluma/protocol/web/request-util';
// The 说说 list comes from taotao.qzone.qq.com's emotion_cgi_msglist_v6 CGI,
@@ -115,3 +115,72 @@ describe('qzone / getQzoneMsgList (HTTP layer)', () => {
await expect(getQzoneMsgList(cookies, '10000')).rejects.toThrow('无法获取空间说说列表');
});
});
describe('qzone / mapFeeds', () => {
it('maps structured fields, prefers key over feedskey, and reads has_more', () => {
const out = mapFeeds({
code: 0,
data: {
hasmore: 1,
data: [
{ uin: 12345, nickname: 'Alice', abstime: 1700000000, appid: 311, key: 'K1', html: '<div>a</div>' },
{ uin: '67890', nickname: 'Bob', abstime: '1700000050', appid: '4', feedskey: 'FK2', html: '<div>b</div>' },
],
},
});
expect(out).toEqual({
has_more: true,
feeds: [
{ uin: 12345, nickname: 'Alice', time: 1700000000, appid: 311, key: 'K1', html: '<div>a</div>' },
{ uin: 67890, nickname: 'Bob', time: 1700000050, appid: 4, key: 'FK2', html: '<div>b</div>' },
],
});
});
it('tolerates missing fields and empty data', () => {
expect(mapFeeds({ code: 0, data: { data: [] } })).toEqual({ feeds: [], has_more: false });
});
});
describe('qzone / getQzoneFeeds (HTTP layer)', () => {
afterEach(() => vi.restoreAllMocks());
it('GETs the exact feeds url + params and maps the JSONP body', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(
'_Callback({"code":0,"data":{"hasmore":1,"data":[{"uin":12345,"nickname":"Alice","abstime":1700000000,"appid":311,"key":"K1","html":"<div>a</div>"}]}});',
);
const out = await getQzoneFeeds(cookies, '10000', 2, 10);
expect(out).toEqual({
has_more: true,
feeds: [{ uin: 12345, nickname: 'Alice', time: 1700000000, appid: 311, key: 'K1', html: '<div>a</div>' }],
});
const [url, method, body, headers] = spy.mock.calls[0]!;
expect(method).toBe('GET');
expect(body).toBe('');
expect((headers as Record<string, string>).Cookie).toContain('p_skey=PSK');
expect(url).toContain('https://ic2.qzone.qq.com/cgi-bin/feeds/feeds3_html_more?');
const q = new URLSearchParams((url as string).split('?')[1]);
expect(q.get('uin')).toBe('10000');
expect(q.get('pagenum')).toBe('2');
expect(q.get('count')).toBe('10');
expect(q.get('g_tk')).toBe(expectedGtk);
});
it('returns an empty list (not a throw) for a genuinely empty feed', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"data":{"data":[],"hasmore":0}}');
await expect(getQzoneFeeds(cookies, '10000')).resolves.toEqual({ feeds: [], has_more: false });
});
it('throws on a non-zero qzone code', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-3000,"message":"need login"}');
await expect(getQzoneFeeds(cookies, '10000')).rejects.toThrow('code=-3000');
});
it('throws when the data array is absent (cookie failure), not an empty list', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"data":{}}');
await expect(getQzoneFeeds(cookies, '10000')).rejects.toThrow('无法获取空间好友动态');
});
});