diff --git a/packages/core/src/bridge/apis/index.ts b/packages/core/src/bridge/apis/index.ts index 831b223b..03dc5349 100644 --- a/packages/core/src/bridge/apis/index.ts +++ b/packages/core/src/bridge/apis/index.ts @@ -10,6 +10,7 @@ import { InteractionApi } from './interaction'; import { MessageApi } from './message'; import { MiscApi } from './misc'; import { ProfileApi } from './profile'; +import { QzoneApi } from './qzone'; import { WebApi } from './web'; export interface ApiHub { @@ -23,6 +24,8 @@ export interface ApiHub { readonly groupFile: GroupFileApi; /** Group photo album: list/upload/comment/like/delete + media listing. */ readonly groupAlbum: GroupAlbumApi; + /** Personal QQ-Zone (个人空间): 说说 list + (future) publish/like/comment. */ + readonly qzone: QzoneApi; /** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */ readonly interaction: InteractionApi; /** Friend roster mutations: handleRequest / delete / setRemark. */ @@ -54,6 +57,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub { groupAdmin: new GroupAdminApi(ctx), groupFile: new GroupFileApi(ctx), groupAlbum: new GroupAlbumApi(ctx), + qzone: new QzoneApi(ctx), interaction: new InteractionApi(ctx), friend: new FriendApi(ctx), profile: new ProfileApi(ctx), @@ -78,5 +82,6 @@ export { InteractionApi } from './interaction'; export { MessageApi } from './message'; export { MiscApi } from './misc'; export { ProfileApi } from './profile'; +export { QzoneApi } from './qzone'; export { WebApi } from './web'; diff --git a/packages/core/src/bridge/apis/qzone.ts b/packages/core/src/bridge/apis/qzone.ts new file mode 100644 index 00000000..48162e91 --- /dev/null +++ b/packages/core/src/bridge/apis/qzone.ts @@ -0,0 +1,22 @@ +import { getQzoneMsgList, type QzoneMsgListResult } from '@snowluma/protocol/web/qzone'; +import type { BridgeContext } from '../bridge-context'; + +/** + * Personal QQ-Zone (个人空间) web API: 说说 (feed) read/write, likes, + * comments — all over the cookie-backed qzone.qq.com CGIs, reusing the same + * `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi. Distinct from the + * group-album surface, which lives on GroupAlbumApi. + */ +export class QzoneApi { + constructor(private readonly ctx: BridgeContext) { } + + /** + * 获取说说列表。`targetUin` 省略时取机器人自己的空间。 + * `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。 + */ + async getMsgList(targetUin?: number, pos = 0, num = 20): Promise { + const uin = targetUin && targetUin > 0 ? targetUin.toString() : this.ctx.identity.uin; + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + return getQzoneMsgList(cookieObject, uin, pos, num); + } +} diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 3a71334e..8a3bc6af 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -3000,6 +3000,73 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "群相册" }, + { + "name": "get_qzone_msg_list", + "aliases": [], + "summary": "获取 QQ 空间说说列表(默认机器人自己的空间)", + "readOnly": true, + "params": [ + { + "name": "target_uin", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "目标 QQ 号,省略则取机器人自己" + }, + { + "name": "pos", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "desc": "起始偏移", + "default": 0 + }, + { + "name": "num", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + }, + "desc": "本页数量", + "default": 20 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "target_uin": { + "type": "integer", + "minimum": 1, + "description": "目标 QQ 号,省略则取机器人自己" + }, + "pos": { + "type": "integer", + "minimum": 0, + "description": "起始偏移", + "default": 0 + }, + "num": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "description": "本页数量", + "default": 20 + } + }, + "additionalProperties": true + }, + "category": "空间" + }, { "name": "get_recent_contact", "aliases": [], @@ -6571,5 +6638,9 @@ export const CATEGORIES: CatalogCategory[] = [ { "category": "群相册", "count": 8 + }, + { + "category": "空间", + "count": 1 } ]; diff --git a/packages/onebot/src/action-docs.ts b/packages/onebot/src/action-docs.ts index 43982da9..640da92a 100644 --- a/packages/onebot/src/action-docs.ts +++ b/packages/onebot/src/action-docs.ts @@ -22,6 +22,7 @@ import { actions as groupFileActions } from './actions/group-file'; import { actions as requestActions } from './actions/request'; import { actions as extendedActions } from './actions/extended'; import { actions as groupAlbumActions } from './actions/group-album'; +import { actions as qzoneActions } from './actions/qzone'; type AnySpec = ActionSpec>>; @@ -36,6 +37,7 @@ const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [ { category: '请求', specs: requestActions }, { category: '扩展', specs: extendedActions }, { category: '群相册', specs: groupAlbumActions }, + { category: '空间', specs: qzoneActions }, ]; /** Every declarative action's doc (with category), sorted by name. */ diff --git a/packages/onebot/src/actions/qzone.ts b/packages/onebot/src/actions/qzone.ts new file mode 100644 index 00000000..ebee6ddb --- /dev/null +++ b/packages/onebot/src/actions/qzone.ts @@ -0,0 +1,33 @@ +import { defineAction, registerActions, f } from '../action-kit'; +import type { ApiActionContext, ApiHandler } from '../api-handler'; +import type { JsonValue } from '../types'; +import { RETCODE, failedResponse, okResponse } from '../types'; + +export const actions = [ + // get_qzone_msg_list — 获取 QQ 空间说说列表。无 go-cqhttp 标准,自定义命名。 + // 默认取机器人自己的空间;传 target_uin 可查看指定账号(需有权限)。 + // 复用 qzone.qq.com 的 cookie/g_tk 基建(与群相册同源),纯 web,无 trpc。 + defineAction({ + name: 'get_qzone_msg_list', + readOnly: true, + summary: '获取 QQ 空间说说列表(默认机器人自己的空间)', + params: { + target_uin: f.uint().describe('目标 QQ 号,省略则取机器人自己').optional(), + pos: f.int({ min: 0 }).describe('起始偏移').default(0), + num: f.int({ min: 1, max: 100 }).describe('本页数量').default(20), + }, + run: async (p, ctx) => { + try { + const res = await ctx.bridge.apis.qzone.getMsgList(p.target_uin, p.pos, p.num); + return okResponse(res as unknown as JsonValue); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to get qzone msg list'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }, + }), +]; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + registerActions(h, ctx, actions); +} diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index e757530a..1e958e16 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -9,6 +9,7 @@ import { register as registerGroupFile } from './actions/group-file'; import { register as registerGroupInfo } from './actions/group-info'; import { register as registerInfo } from './actions/info'; import { register as registerMessage } from './actions/message'; +import { register as registerQzone } from './actions/qzone'; import { register as registerRequest } from './actions/request'; import type { ForwardPreviewMeta } from './modules/message-actions'; import type { JsonObject, JsonValue, MessageMeta } from './types'; @@ -114,6 +115,7 @@ export class ApiHandler { registerRequest(this, context); registerExtended(this, context); registerGroupAlbum(this, context); + registerQzone(this, context); } registerAction(action: string, handler: ActionHandler): void { diff --git a/packages/protocol/package.json b/packages/protocol/package.json index ac2fbcc2..186bf01e 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -420,6 +420,10 @@ "types": "./src/web/group-signin.ts", "default": "./src/web/group-signin.ts" }, + "./web/qzone": { + "types": "./src/web/qzone.ts", + "default": "./src/web/qzone.ts" + }, "./web/request-util": { "types": "./src/web/request-util.ts", "default": "./src/web/request-util.ts" diff --git a/packages/protocol/src/web/qzone.ts b/packages/protocol/src/web/qzone.ts new file mode 100644 index 00000000..407557cc --- /dev/null +++ b/packages/protocol/src/web/qzone.ts @@ -0,0 +1,160 @@ +import type { JsonValue } from '@snowluma/common/json'; +import { createLogger } from '@snowluma/common/logger'; +import { RequestUtil, cookieToString, getBknFromCookie } from './request-util'; + +const log = createLogger('Bridge.Web'); + +// ─────────────── raw shapes from taotao.qzone.qq.com ─────────────── +// These mirror the `emotion_cgi_msglist_v6` response. The endpoint is a +// legacy Qzone CGI: field names are stable across years (the community +// libs SmartHypercube/Qzone-API and cw1997/QzoneUtil rely on the same +// set), but the server occasionally adds fields and may wrap the body in +// a JSONP callback — both handled below. Precise field coverage should be +// re-confirmed against a live capture when extending this (same +// maintenance posture as the group-album / group-signin web helpers). + +interface RawPic { + url1?: string; + url2?: string; + url3?: string; + smallurl?: string; +} + +interface RawEmotion { + tid?: string; + content?: string; + created_time?: number; + cmtnum?: number; + secret?: number; + pic?: RawPic[]; +} + +interface RawMsgListResponse { + code?: number; + subcode?: number; + message?: string; + total?: number; + msglist?: RawEmotion[] | null; +} + +// ─────────────── OneBot-facing shapes ─────────────── + +/** One 说说 (Qzone emotion/feed) in a normalised, OneBot-friendly form. */ +export interface QzoneEmotion { + [key: string]: JsonValue; + /** Feed id — the handle for delete/comment/like on this 说说. */ + tid: string; + content: string; + /** Unix seconds the 说说 was posted. */ + time: number; + /** Number of comments on the 说说. */ + comment_num: number; + /** Private (仅自己可见) flag. */ + is_private: boolean; + /** Picture URLs (largest available variant per picture). */ + images: string[]; +} + +export interface QzoneMsgListResult { + [key: string]: JsonValue; + /** Total number of 说说 the account has (not the page size). */ + total: number; + msglist: QzoneEmotion[]; +} + +/** + * Parse a Qzone CGI body that may be raw JSON or a JSONP callback wrapper + * (`_Callback({...});` / `callback({...})`). We slice from the first `{` + * to the last `}` and JSON.parse that — robust to either form without + * pinning the callback name, which Qzone varies. Throws if no object body + * is present (e.g. an HTML error page), which the caller turns into a + * failed response rather than a silent empty list. + */ +export function parseQzoneJson(text: string): T { + const s = text.trim(); + const start = s.indexOf('{'); + const end = s.lastIndexOf('}'); + if (start === -1 || end === -1 || end < start) { + throw new Error('invalid response from qzone api'); + } + return JSON.parse(s.slice(start, end + 1)) as T; +} + +/** Pick the largest picture URL variant a feed picture offers. */ +function pickPicUrl(pic: RawPic): string | undefined { + return pic.url3 || pic.url2 || pic.url1 || pic.smallurl || undefined; +} + +/** Pure transform from the raw CGI response into the OneBot list. */ +export function mapMsgList(data: RawMsgListResponse): QzoneMsgListResult { + const list = data.msglist ?? []; + return { + total: Number(data.total ?? list.length), + msglist: list.map((e) => ({ + tid: String(e.tid ?? ''), + content: e.content ?? '', + time: Number(e.created_time ?? 0), + comment_num: Number(e.cmtnum ?? 0), + is_private: Number(e.secret ?? 0) !== 0, + images: (e.pic ?? []).map(pickPicUrl).filter((u): u is string => !!u), + })), + }; +} + +/** + * Fetch a 说说 (Qzone emotion/feed) list via the taotao.qzone.qq.com web + * API, proxied through h5.qzone.qq.com — the same cookie/g_tk plumbing the + * group-album helper uses. Defaults to the bot's own space; `targetUin` + * can name any space the bot may view. + * + * Errors PROPAGATE: a transport failure, a non-zero `code` (Qzone's own + * error envelope, e.g. auth/permission), or a missing `msglist` (the body + * an expired cookie produces) all throw — we do NOT swallow them to an + * empty list, because that would make a broken cookie indistinguishable + * from a genuinely empty space. A real empty space returns `msglist: []`, + * which maps to an empty list with the correct `total`. Mirrors the + * group-signin helper's throw-on-auth-failure contract. + */ +export async function getQzoneMsgList( + cookieObject: Record, + targetUin: string, + pos = 0, + num = 20, +): Promise { + if (!cookieObject || typeof cookieObject !== 'object') { + throw new Error('cookieObject is required'); + } + + const bkn = getBknFromCookie(cookieObject); + const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_msglist_v6?${new URLSearchParams( + { + uin: targetUin, + ftype: '0', + sort: '0', + pos: String(pos), + num: String(num), + replynum: '100', + g_tk: bkn, + callback: '_preloadCallback', + code_version: '1', + format: 'jsonp', + need_private_comment: '1', + }, + ).toString()}`; + + const text = await RequestUtil.HttpGetText(url, 'GET', '', { + Cookie: cookieToString(cookieObject), + }); + const data = parseQzoneJson(text); + + if (typeof data.code === 'number' && data.code !== 0) { + log.warn('getQzoneMsgList: non-zero code (uin=%s) code=%d msg=%s', targetUin, data.code, data.message); + throw new Error(`qzone msglist failed: code=${data.code} ${data.message ?? ''}`.trim()); + } + if (!Array.isArray(data.msglist)) { + log.warn('getQzoneMsgList: no msglist in response (uin=%s) — likely auth/cookie failure', targetUin); + throw new Error('无法获取空间说说列表'); + } + + return mapMsgList(data); +} diff --git a/packages/protocol/tests/web/qzone.test.ts b/packages/protocol/tests/web/qzone.test.ts new file mode 100644 index 00000000..0997e846 --- /dev/null +++ b/packages/protocol/tests/web/qzone.test.ts @@ -0,0 +1,110 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { getQzoneMsgList, 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, +// proxied through h5.qzone.qq.com. The body is JSONP (`_preloadCallback({…})`) +// so we pin both the JSONP-stripping and the field renames (created_time→time, +// cmtnum→comment_num, secret→is_private, pic→largest-url images), plus the +// auth-failure throw contract — these are the only real logic in an otherwise +// thin HTTP port and would be invisible end-to-end if they regressed. + +const cookies = { p_skey: 'PSK', skey: 'SK', uin: 'o10000', p_uin: 'o10000' }; +const expectedGtk = (() => { + let h = 5381; + for (const c of 'PSK') h += (h << 5) + c.charCodeAt(0); + return (h & 0x7fffffff).toString(); +})(); + +describe('qzone / parseQzoneJson', () => { + it('parses a raw JSON body', () => { + expect(parseQzoneJson<{ a: number }>('{"a":1}')).toEqual({ a: 1 }); + }); + + it('strips a JSONP callback wrapper', () => { + expect(parseQzoneJson<{ a: number }>('_preloadCallback({"a":1});')).toEqual({ a: 1 }); + }); + + it('throws on a non-object body (HTML error page)', () => { + expect(() => parseQzoneJson('nope')).toThrow('invalid response from qzone api'); + }); +}); + +describe('qzone / mapMsgList', () => { + it('renames fields, flags private, and picks the largest pic url', () => { + const out = mapMsgList({ + code: 0, + total: 42, + msglist: [ + { + tid: 'T1', + content: 'hello', + created_time: 1700000000, + cmtnum: 3, + secret: 0, + pic: [{ url1: 'a', url2: 'b', url3: 'c' }], + }, + { tid: 'T2', content: 'secret one', created_time: 1700000050, cmtnum: 0, secret: 1 }, + ], + }); + expect(out).toEqual({ + total: 42, + msglist: [ + { tid: 'T1', content: 'hello', time: 1700000000, comment_num: 3, is_private: false, images: ['c'] }, + { tid: 'T2', content: 'secret one', time: 1700000050, comment_num: 0, is_private: true, images: [] }, + ], + }); + }); + + it('falls back to list length when total is absent and tolerates missing fields', () => { + const out = mapMsgList({ msglist: [{ tid: 'T1' }] }); + expect(out).toEqual({ + total: 1, + msglist: [{ tid: 'T1', content: '', time: 0, comment_num: 0, is_private: false, images: [] }], + }); + }); +}); + +describe('qzone / getQzoneMsgList (HTTP layer)', () => { + afterEach(() => vi.restoreAllMocks()); + + it('GETs the exact proxied url + params and maps the JSONP body', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue( + '_preloadCallback({"code":0,"total":1,"msglist":[{"tid":"T1","content":"hi","created_time":1700000000,"cmtnum":2,"secret":0,"pic":[{"url1":"a","url3":"c"}]}]});', + ); + + const out = await getQzoneMsgList(cookies, '10000', 0, 20); + + expect(out).toEqual({ + total: 1, + msglist: [{ tid: 'T1', content: 'hi', time: 1700000000, comment_num: 2, is_private: false, images: ['c'] }], + }); + + const [url, method, body, headers] = spy.mock.calls[0]!; + expect(method).toBe('GET'); + expect(body).toBe(''); + expect((headers as Record).Cookie).toContain('p_skey=PSK'); + expect(url).toContain('https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_msglist_v6?'); + const q = new URLSearchParams((url as string).split('?')[1]); + expect(q.get('uin')).toBe('10000'); + expect(q.get('pos')).toBe('0'); + expect(q.get('num')).toBe('20'); + expect(q.get('g_tk')).toBe(expectedGtk); + expect(q.get('format')).toBe('jsonp'); + }); + + it('propagates a transport error instead of swallowing it', async () => { + vi.spyOn(RequestUtil, 'HttpGetText').mockRejectedValue(new Error('Unexpected status code: 403')); + await expect(getQzoneMsgList(cookies, '10000')).rejects.toThrow('403'); + }); + + it('throws on a non-zero qzone code (auth/permission), not an empty list', async () => { + vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-3000,"message":"need login","subcode":0}'); + await expect(getQzoneMsgList(cookies, '10000')).rejects.toThrow('code=-3000'); + }); + + it('throws when msglist is absent (cookie failure), not an empty list', async () => { + vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"total":0}'); + await expect(getQzoneMsgList(cookies, '10000')).rejects.toThrow('无法获取空间说说列表'); + }); +});