feat: Qzone支持上传图片(发说说、评论附图) (#152)
* feat(core,onebot,protocol): support publish shuoshuo and comment with image * Fix: Accidentally changed notes
This commit is contained in:
1 parent
547640bbfd
commit
62eb8fd763
9 files changed
+658
-28
No files matched your search
@@ -5,18 +5,20 @@ import {
|
||||
getQzoneMsgList,
|
||||
publishQzoneMsg,
|
||||
setQzoneLike,
|
||||
uploadQzoneImageFromSource,
|
||||
type QzoneCommentResult,
|
||||
type QzoneFeedsResult,
|
||||
type QzoneMsgListResult,
|
||||
type QzonePublishResult,
|
||||
type QzoneUploadImageResult,
|
||||
} 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.
|
||||
* comments, image upload — 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) { }
|
||||
@@ -40,10 +42,23 @@ export class QzoneApi {
|
||||
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
|
||||
}
|
||||
|
||||
/** 发表一条纯文字说说,返回新说说的 tid。始终发到机器人自己的空间。 */
|
||||
async publish(content: string): Promise<QzonePublishResult> {
|
||||
/**
|
||||
* 从来源上传图片到 QQ 空间。
|
||||
* `source` 支持: file:// 本地路径 | http(s):// URL | base64:// base64数据
|
||||
*/
|
||||
async uploadImageFromSource(source: string): Promise<QzoneUploadImageResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content);
|
||||
return uploadQzoneImageFromSource(cookieObject, this.ctx.identity.uin, source);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发表说说,返回新说说的 tid。始终发到机器人自己的空间。
|
||||
* `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串
|
||||
* (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。
|
||||
*/
|
||||
async publish(content: string, richType?: number, richval?: string): Promise<QzonePublishResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval);
|
||||
}
|
||||
|
||||
/** 删除机器人自己空间的一条说说(按 tid)。 */
|
||||
@@ -66,11 +81,19 @@ export class QzoneApi {
|
||||
/**
|
||||
* 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间);
|
||||
* 始终以机器人身份发表评论。返回新评论 id(尽力而为)。
|
||||
* `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL
|
||||
* (从 uploadImageFromSource 的 url 字段获取)。
|
||||
*/
|
||||
async comment(tid: string, content: string, targetUin: number | undefined): Promise<QzoneCommentResult> {
|
||||
async comment(
|
||||
tid: string,
|
||||
content: string,
|
||||
targetUin: number | undefined,
|
||||
richType?: number,
|
||||
richval?: string,
|
||||
): Promise<QzoneCommentResult> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content);
|
||||
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval);
|
||||
}
|
||||
}
|
||||
@@ -49,16 +49,57 @@ describe('apis/qzone', () => {
|
||||
expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20);
|
||||
});
|
||||
|
||||
it('publish posts to the bot\'s own space with the given content', async () => {
|
||||
it('uploadImageFromSource uploads from file:// http:// base64:// and returns richval + url', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK', skey: 'SK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const uploadSpy = vi.spyOn(qzoneWeb, 'uploadQzoneImageFromSource').mockResolvedValue({
|
||||
richval: ',12345,abc,abc,22,800,600,,800,600',
|
||||
url: 'https://example.com/img.jpg',
|
||||
albumid: '12345',
|
||||
lloc: 'abc',
|
||||
type: 22,
|
||||
width: 600,
|
||||
height: 800,
|
||||
});
|
||||
const out = await new QzoneApi(bridge as never).uploadImageFromSource('file:///path/to/image.jpg');
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(uploadSpy).toHaveBeenCalledWith({ p_skey: 'PSK', skey: 'SK' }, '10001', 'file:///path/to/image.jpg');
|
||||
expect(out.richval).toBe(',12345,abc,abc,22,800,600,,800,600');
|
||||
expect(out.url).toBe('https://example.com/img.jpg');
|
||||
});
|
||||
|
||||
it('publish posts to the bot\'s own space with the given content (text-only)', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 });
|
||||
const out = await new QzoneApi(bridge as never).publish('hello');
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello');
|
||||
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined);
|
||||
expect(out).toEqual({ tid: 'T', time: 1 });
|
||||
});
|
||||
|
||||
it('publish posts with richtype and richval for image post', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T2', time: 2 });
|
||||
const richval = ',12345,abc,abc,22,800,600,,800,600';
|
||||
const out = await new QzoneApi(bridge as never).publish('look at this', 1, richval);
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'look at this', 1, richval);
|
||||
expect(out).toEqual({ tid: 'T2', time: 2 });
|
||||
});
|
||||
|
||||
it('publish posts with multiple images (richval joined with tab)', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T3', time: 3 });
|
||||
const richval = ',12345,a,a,22,800,600,,800,600\t,12346,b,b,22,1024,768,,1024,768';
|
||||
const out = await new QzoneApi(bridge as never).publish('two images', 1, richval);
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'two images', 1, richval);
|
||||
expect(out).toEqual({ tid: 'T3', time: 3 });
|
||||
});
|
||||
|
||||
it('delete removes a feed by tid from the bot\'s own space', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
@@ -92,7 +133,7 @@ describe('apis/qzone', () => {
|
||||
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '1' });
|
||||
const out = await new QzoneApi(bridge as never).comment('TIDX', 'nice', undefined);
|
||||
// selfUin='10001' commenter; owner defaults to self
|
||||
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice');
|
||||
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice', undefined, undefined);
|
||||
expect(out).toEqual({ comment_id: '1' });
|
||||
});
|
||||
|
||||
@@ -101,6 +142,15 @@ describe('apis/qzone', () => {
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '2' });
|
||||
await new QzoneApi(bridge as never).comment('TIDX', 'nice', 20002);
|
||||
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '20002', 'TIDX', 'nice');
|
||||
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '20002', 'TIDX', 'nice', undefined, undefined);
|
||||
});
|
||||
|
||||
it('comment with images (richType=1, richval=direct URLs joined with tab)', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '3' });
|
||||
const richval = 'https://example.com/a.jpg\thttps://example.com/b.jpg';
|
||||
await new QzoneApi(bridge as never).comment('TIDX', 'nice pic', undefined, 1, richval);
|
||||
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice pic', 1, richval);
|
||||
});
|
||||
});
|
||||
@@ -600,7 +600,7 @@
|
||||
{
|
||||
"name": "comment_qzone",
|
||||
"aliases": [],
|
||||
"summary": "评论一条说说(QQ 空间)",
|
||||
"summary": "评论一条说说(QQ 空间,支持纯文字或带图;传 images 自动上传)",
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
@@ -632,6 +632,19 @@
|
||||
"minimum": 1
|
||||
},
|
||||
"desc": "说说所属 QQ 号,省略则为机器人自己"
|
||||
},
|
||||
{
|
||||
"name": "images",
|
||||
"type": "string[]",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"desc": "图片数组(可选),支持 file:// http:// base64://;自动上传"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
@@ -652,6 +665,14 @@
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"description": "说说所属 QQ 号,省略则为机器人自己"
|
||||
},
|
||||
"images": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"description": "图片数组(可选),支持 file:// http:// base64://;自动上传"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -6721,7 +6742,7 @@
|
||||
{
|
||||
"name": "send_qzone_msg",
|
||||
"aliases": [],
|
||||
"summary": "发表一条纯文字说说(QQ 空间)",
|
||||
"summary": "发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)",
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
@@ -6733,6 +6754,19 @@
|
||||
"minLength": 1
|
||||
},
|
||||
"desc": "说说正文"
|
||||
},
|
||||
{
|
||||
"name": "images",
|
||||
"type": "string[]",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"desc": "图片数组(可选),支持 file:// http:// base64://;自动上传"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
@@ -6743,6 +6777,14 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "说说正文"
|
||||
},
|
||||
"images": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"description": "图片数组(可选),支持 file:// http:// base64://;自动上传"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -603,7 +603,7 @@ export const ACTIONS: CatalogAction[] = [
|
||||
{
|
||||
"name": "comment_qzone",
|
||||
"aliases": [],
|
||||
"summary": "评论一条说说(QQ 空间)",
|
||||
"summary": "评论一条说说(QQ 空间,支持纯文字或带图;传 images 自动上传)",
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
@@ -635,6 +635,19 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"minimum": 1
|
||||
},
|
||||
"desc": "说说所属 QQ 号,省略则为机器人自己"
|
||||
},
|
||||
{
|
||||
"name": "images",
|
||||
"type": "string[]",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"desc": "图片数组(可选),支持 file:// http:// base64://;自动上传"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
@@ -655,6 +668,14 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"description": "说说所属 QQ 号,省略则为机器人自己"
|
||||
},
|
||||
"images": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"description": "图片数组(可选),支持 file:// http:// base64://;自动上传"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -6724,7 +6745,7 @@ export const ACTIONS: CatalogAction[] = [
|
||||
{
|
||||
"name": "send_qzone_msg",
|
||||
"aliases": [],
|
||||
"summary": "发表一条纯文字说说(QQ 空间)",
|
||||
"summary": "发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)",
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
@@ -6736,6 +6757,19 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"minLength": 1
|
||||
},
|
||||
"desc": "说说正文"
|
||||
},
|
||||
{
|
||||
"name": "images",
|
||||
"type": "string[]",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"desc": "图片数组(可选),支持 file:// http:// base64://;自动上传"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
@@ -6746,6 +6780,14 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "说说正文"
|
||||
},
|
||||
"images": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"description": "图片数组(可选),支持 file:// http:// base64://;自动上传"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -3,6 +3,24 @@ import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import type { JsonValue } from '../types';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
async function uploadQzoneImages(
|
||||
ctx: ApiActionContext,
|
||||
images: string[],
|
||||
select: (upload: { richval: string; url: string }) => string,
|
||||
): Promise<string> {
|
||||
const parts: string[] = [];
|
||||
for (let i = 0; i < images.length; i++) {
|
||||
try {
|
||||
const upload = await ctx.bridge.apis.qzone.uploadImageFromSource(images[i]);
|
||||
parts.push(select(upload));
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'unknown error';
|
||||
throw new Error(`第 ${i + 1} 张图片上传失败: ${message}`);
|
||||
}
|
||||
}
|
||||
return parts.join('\t');
|
||||
}
|
||||
|
||||
export const actions = [
|
||||
// get_qzone_msg_list — 获取 QQ 空间说说列表。无 go-cqhttp 标准,自定义命名。
|
||||
// 默认取机器人自己的空间;传 target_uin 可查看指定账号(需有权限)。
|
||||
@@ -96,17 +114,24 @@ export const actions = [
|
||||
},
|
||||
}),
|
||||
|
||||
// send_qzone_msg — 发表一条纯文字说说。写操作,发到机器人自己的空间。
|
||||
// send_qzone_msg — 发表说说(纯文字或带图)。写操作,发到机器人自己的空间。
|
||||
// 传入 images 数组,自动上传并发布。
|
||||
// 返回新说说的 tid(供后续 delete/comment/like 使用)。
|
||||
// 注意:发说说为主动行为,高频会被 Qzone 风控,调用方需自行限流。
|
||||
defineAction({
|
||||
name: 'send_qzone_msg',
|
||||
summary: '发表一条纯文字说说(QQ 空间)',
|
||||
summary: '发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)',
|
||||
params: {
|
||||
content: f.string({ allowEmpty: false }).describe('说说正文'),
|
||||
images: f.array(f.string({ allowEmpty: false })).describe('图片数组(可选),支持 file:// http:// base64://;自动上传').optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
if (p.images && p.images.length > 0) {
|
||||
const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.richval);
|
||||
const res = await ctx.bridge.apis.qzone.publish(p.content, 1, richval);
|
||||
return okResponse(res as unknown as JsonValue);
|
||||
}
|
||||
const res = await ctx.bridge.apis.qzone.publish(p.content);
|
||||
return okResponse(res as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
@@ -178,17 +203,24 @@ export const actions = [
|
||||
}),
|
||||
|
||||
// comment_qzone — 评论一条说说。target_uin=说说所属 QQ 号(省略=机器人自己空间)。
|
||||
// 传入 images 数组,自动上传获取直链(多图用 tab 拼接)。
|
||||
// 写操作;高频评论会被 Qzone 风控,调用方需限流。
|
||||
defineAction({
|
||||
name: 'comment_qzone',
|
||||
summary: '评论一条说说(QQ 空间)',
|
||||
summary: '评论一条说说(QQ 空间,支持纯文字或带图;传 images 自动上传)',
|
||||
params: {
|
||||
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
|
||||
content: f.string({ allowEmpty: false }).describe('评论内容'),
|
||||
target_uin: f.uint().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
|
||||
images: f.array(f.string({ allowEmpty: false })).describe('图片数组(可选),支持 file:// http:// base64://;自动上传').optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
if (p.images && p.images.length > 0) {
|
||||
const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.url);
|
||||
const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin, 1, richval);
|
||||
return okResponse(res as unknown as JsonValue);
|
||||
}
|
||||
const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin);
|
||||
return okResponse(res as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
|
||||
function makeHandler(qzone: Record<string, unknown>): ApiHandler {
|
||||
const bridge = { apis: { qzone } } as unknown as BridgeInterface;
|
||||
const ctx = { bridge } as ApiActionContext;
|
||||
return new ApiHandler(ctx);
|
||||
}
|
||||
|
||||
describe('qzone actions', () => {
|
||||
it('send_qzone_msg uploads images and publishes richvals joined with tab', async () => {
|
||||
const uploadImageFromSource = vi.fn()
|
||||
.mockResolvedValueOnce({ richval: 'RV1', url: 'URL1' })
|
||||
.mockResolvedValueOnce({ richval: 'RV2', url: 'URL2' });
|
||||
const publish = vi.fn().mockResolvedValue({ tid: 'T1', time: 1 });
|
||||
const handler = makeHandler({ uploadImageFromSource, publish });
|
||||
|
||||
const res = await handler.handle('send_qzone_msg', {
|
||||
content: 'hello',
|
||||
images: ['file:///a.jpg', 'file:///b.jpg'],
|
||||
});
|
||||
|
||||
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { tid: 'T1', time: 1 } });
|
||||
expect(uploadImageFromSource).toHaveBeenNthCalledWith(1, 'file:///a.jpg');
|
||||
expect(uploadImageFromSource).toHaveBeenNthCalledWith(2, 'file:///b.jpg');
|
||||
expect(publish).toHaveBeenCalledWith('hello', 1, 'RV1\tRV2');
|
||||
});
|
||||
|
||||
it('comment_qzone uploads images and comments direct urls joined with tab', async () => {
|
||||
const uploadImageFromSource = vi.fn()
|
||||
.mockResolvedValueOnce({ richval: 'RV1', url: 'URL1' })
|
||||
.mockResolvedValueOnce({ richval: 'RV2', url: 'URL2' });
|
||||
const comment = vi.fn().mockResolvedValue({ comment_id: 'C1' });
|
||||
const handler = makeHandler({ uploadImageFromSource, comment });
|
||||
|
||||
const res = await handler.handle('comment_qzone', {
|
||||
tid: 'T1',
|
||||
content: 'nice',
|
||||
target_uin: 20002,
|
||||
images: ['file:///a.jpg', 'file:///b.jpg'],
|
||||
});
|
||||
|
||||
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { comment_id: 'C1' } });
|
||||
expect(comment).toHaveBeenCalledWith('T1', 'nice', 20002, 1, 'URL1\tURL2');
|
||||
});
|
||||
|
||||
it('returns a clear error and skips publish when one image upload fails', async () => {
|
||||
const uploadImageFromSource = vi.fn()
|
||||
.mockResolvedValueOnce({ richval: 'RV1', url: 'URL1' })
|
||||
.mockRejectedValueOnce(new Error('network down'));
|
||||
const publish = vi.fn();
|
||||
const handler = makeHandler({ uploadImageFromSource, publish });
|
||||
|
||||
const res = await handler.handle('send_qzone_msg', {
|
||||
content: 'hello',
|
||||
images: ['file:///a.jpg', 'file:///b.jpg'],
|
||||
});
|
||||
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1200 });
|
||||
expect(res.wording).toContain('第 2 张图片上传失败: network down');
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
});
|
||||
@@ -80,6 +80,55 @@ export function parseQzoneJson<T>(text: string): T {
|
||||
return JSON.parse(s.slice(start, end + 1)) as T;
|
||||
}
|
||||
|
||||
function assertRichParams(richType?: number, richval?: string): void {
|
||||
const hasRichType = richType !== undefined;
|
||||
const hasRichval = richval !== undefined && richval.trim() !== '';
|
||||
if (hasRichType !== hasRichval) {
|
||||
throw new Error('richType and richval must be provided together');
|
||||
}
|
||||
if (richType !== undefined && (!Number.isInteger(richType) || richType < 1)) {
|
||||
throw new Error('richType must be a positive integer');
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeQzoneImageBase64(input: string): string {
|
||||
let text = input.trim();
|
||||
if (/^base64:\/\//i.test(text)) {
|
||||
text = text.slice(9).trim();
|
||||
}
|
||||
if (/^data:/i.test(text)) {
|
||||
const comma = text.indexOf(',');
|
||||
if (comma === -1) {
|
||||
throw new Error('imageBase64 data URI is missing base64 payload');
|
||||
}
|
||||
text = text.slice(comma + 1);
|
||||
}
|
||||
|
||||
const compact = text.replace(/ /g, '+').replace(/[\r\n\t]/g, '');
|
||||
if (!compact) {
|
||||
throw new Error('imageBase64 is required');
|
||||
}
|
||||
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(compact)) {
|
||||
throw new Error('imageBase64 is not valid base64');
|
||||
}
|
||||
const firstPadding = compact.indexOf('=');
|
||||
if (firstPadding !== -1 && /[^=]/.test(compact.slice(firstPadding))) {
|
||||
throw new Error('imageBase64 is not valid base64');
|
||||
}
|
||||
|
||||
const unpadded = compact.replace(/=+$/, '');
|
||||
const remainder = unpadded.length % 4;
|
||||
if (remainder === 1) {
|
||||
throw new Error('imageBase64 is not valid base64');
|
||||
}
|
||||
const base64 = unpadded + '='.repeat((4 - remainder) % 4);
|
||||
const bytes = Buffer.from(base64, 'base64');
|
||||
if (bytes.length === 0) {
|
||||
throw new Error('imageBase64 is empty');
|
||||
}
|
||||
return base64;
|
||||
}
|
||||
|
||||
/** 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;
|
||||
@@ -331,10 +380,14 @@ export interface QzonePublishResult {
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish a text-only 说说 via taotao.qzone.qq.com's emotion_cgi_publish_v6
|
||||
* CGI (proxied through h5.qzone.qq.com). POSTs a form-urlencoded body with
|
||||
* Publish a 说说 via taotao.qzone.qq.com's emotion_cgi_publish_v6 CGI
|
||||
* (proxied through h5.qzone.qq.com). POSTs a form-urlencoded body with
|
||||
* `g_tk` in the query, on the bot's own space (`hostUin`).
|
||||
*
|
||||
* `richType` / `richval`: for image posts, set `richType=1` and pass the
|
||||
* richval string(s) from {@link uploadQzoneImage} (multi-image: join with
|
||||
* `\t`). Omit both for text-only posts.
|
||||
*
|
||||
* Errors PROPAGATE: a transport failure, a non-zero Qzone `code` (its error
|
||||
* envelope, e.g. content rejected / rate-limited), or a success body that
|
||||
* carries no `tid` all throw — we never report a publish as succeeded
|
||||
@@ -344,6 +397,8 @@ export async function publishQzoneMsg(
|
||||
cookieObject: Record<string, string>,
|
||||
hostUin: string,
|
||||
content: string,
|
||||
richType?: number,
|
||||
richval?: string,
|
||||
): Promise<QzonePublishResult> {
|
||||
if (!cookieObject || typeof cookieObject !== 'object') {
|
||||
throw new Error('cookieObject is required');
|
||||
@@ -351,6 +406,7 @@ export async function publishQzoneMsg(
|
||||
if (!content) {
|
||||
throw new Error('content is required');
|
||||
}
|
||||
assertRichParams(richType, richval);
|
||||
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=${bkn}`;
|
||||
@@ -358,8 +414,8 @@ export async function publishQzoneMsg(
|
||||
syn_tweet_verson: '1',
|
||||
paramstr: '1',
|
||||
pic_template: '',
|
||||
richtype: '',
|
||||
richval: '',
|
||||
richtype: richType !== undefined ? String(richType) : '',
|
||||
richval: richval ?? '',
|
||||
special_url: '',
|
||||
subrichtype: '',
|
||||
con: content,
|
||||
@@ -546,6 +602,172 @@ export async function setQzoneLike(
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── 上传图片 (upload image) — cgi_upload_image ───────────────
|
||||
// Uploads an image to Qzone's hosting and returns metadata for use in
|
||||
// publish/comment. The image is POSTed as base64 to up.qzone.qq.com
|
||||
// (bypassing the h5 proxy — the upload CGI is NOT behind
|
||||
// h5.qzone.qq.com/proxy). Body is form-urlencoded with `base64=1` and the
|
||||
// base64 payload in `picfile`. Response is a JSONP wrapper (parsed with the
|
||||
// shared tolerant parser) carrying `albumid`, `lloc`, `height`, `width`,
|
||||
// `type`, and `url`. The `richval` (for publish's richval param) is
|
||||
// constructed as `,albumid,lloc,sloc,type,height,width,,height,width` — the
|
||||
// double height/width mirrors the PHP impl. WRITE OP — rate-limit (though
|
||||
// upload itself is not风控'd like publish, batching huge uploads is impolite).
|
||||
// Confirmed against php-qzone/qzone.class.php:97-172.
|
||||
|
||||
interface RawUploadImageResponse {
|
||||
code?: number;
|
||||
subcode?: number;
|
||||
message?: string;
|
||||
data?: {
|
||||
albumid?: string;
|
||||
lloc?: string;
|
||||
url?: string;
|
||||
type?: number;
|
||||
height?: number;
|
||||
width?: number;
|
||||
};
|
||||
}
|
||||
|
||||
/** Result of uploading an image to Qzone. */
|
||||
export interface QzoneUploadImageResult {
|
||||
[key: string]: JsonValue;
|
||||
/** Richval string for publish's `richval` param (multi-image: join with `\t`). */
|
||||
richval: string;
|
||||
/** Direct URL to the uploaded image. */
|
||||
url: string;
|
||||
albumid: string;
|
||||
lloc: string;
|
||||
type: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload an image from a source (file:// / http:// / base64://) to Qzone
|
||||
* hosting. Loads the image via {@link loadBinarySource}, converts to base64,
|
||||
* and uploads via {@link uploadQzoneImage}.
|
||||
*
|
||||
* `source` supports:
|
||||
* - `file://` local file path
|
||||
* - `http://` or `https://` remote URL
|
||||
* - `base64://` base64-encoded data (with or without data-URI prefix)
|
||||
*
|
||||
* Errors PROPAGATE from both the load step and the upload step.
|
||||
*/
|
||||
export async function uploadQzoneImageFromSource(
|
||||
cookieObject: Record<string, string>,
|
||||
hostUin: string,
|
||||
source: string,
|
||||
): Promise<QzoneUploadImageResult> {
|
||||
if (/^base64:\/\//i.test(source)) {
|
||||
return uploadQzoneImage(cookieObject, hostUin, source);
|
||||
}
|
||||
// Import loadBinarySource at function level to avoid circular deps
|
||||
const { loadBinarySource } = await import('../highway/utils');
|
||||
const loaded = await loadBinarySource(source, 'qzone-image');
|
||||
const base64 = Buffer.from(loaded.bytes).toString('base64');
|
||||
return uploadQzoneImage(cookieObject, hostUin, base64);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload an image (as base64) to Qzone hosting via up.qzone.qq.com's
|
||||
* cgi_upload_image CGI. Returns metadata including the `richval` string
|
||||
* (for use in {@link publishQzoneMsg}'s richval param) and the direct URL.
|
||||
* Multi-image publish: call this once per image and join the richval strings
|
||||
* with `\t`.
|
||||
*
|
||||
* `imageBase64` is the raw base64-encoded image bytes; a data-URI prefix is
|
||||
* tolerated and stripped. Errors PROPAGATE: invalid base64, a transport
|
||||
* failure, a non-zero Qzone `code`/`subcode`, or a success body missing
|
||||
* required fields all throw.
|
||||
*/
|
||||
export async function uploadQzoneImage(
|
||||
cookieObject: Record<string, string>,
|
||||
hostUin: string,
|
||||
imageBase64: string,
|
||||
): Promise<QzoneUploadImageResult> {
|
||||
if (!cookieObject || typeof cookieObject !== 'object') {
|
||||
throw new Error('cookieObject is required');
|
||||
}
|
||||
if (!imageBase64) {
|
||||
throw new Error('imageBase64 is required');
|
||||
}
|
||||
const base64 = normalizeQzoneImageBase64(imageBase64);
|
||||
|
||||
const skey = cookieObject['skey'] || '';
|
||||
const pskey = cookieObject['p_skey'] || '';
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
|
||||
const url = `https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${bkn}`;
|
||||
const body = new URLSearchParams({
|
||||
filename: 'filename',
|
||||
uin: hostUin,
|
||||
skey,
|
||||
zzpaneluin: hostUin,
|
||||
p_uin: hostUin,
|
||||
p_skey: pskey,
|
||||
uploadtype: '1',
|
||||
albumtype: '7',
|
||||
exttype: '0',
|
||||
refer: 'shuoshuo',
|
||||
output_type: 'jsonhtml',
|
||||
charset: 'utf-8',
|
||||
output_charset: 'utf-8',
|
||||
upload_hd: '1',
|
||||
hd_width: '2048',
|
||||
hd_height: '10000',
|
||||
hd_quality: '96',
|
||||
backUrls: `http://upbak.photo.qzone.qq.com/cgi-bin/upload/cgi_upload_image,http://119.147.64.75/cgi-bin/upload/cgi_upload_image&url=https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${bkn}`,
|
||||
base64: '1',
|
||||
jsonhtml_callback: 'callback',
|
||||
picfile: base64,
|
||||
qzreferrer: `https://user.qzone.qq.com/${hostUin}/main`,
|
||||
}).toString();
|
||||
|
||||
const text = await RequestUtil.HttpGetText(url, 'POST', body, {
|
||||
Cookie: cookieToString(cookieObject),
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
});
|
||||
|
||||
// Response is `<script>frameElement.callback(...JSON...);</script>` — slice
|
||||
// from the first `{` to the last `}` (same as parseQzoneJson, but the
|
||||
// wrapper shape differs slightly).
|
||||
let jsonText = text.trim();
|
||||
const callbackStart = jsonText.indexOf('callback');
|
||||
if (callbackStart !== -1) {
|
||||
jsonText = jsonText.slice(callbackStart);
|
||||
}
|
||||
const data = parseQzoneJson<RawUploadImageResponse>(jsonText);
|
||||
|
||||
if (typeof data.code === 'number' && data.code !== 0) {
|
||||
log.warn('uploadQzoneImage: non-zero code (uin=%s) code=%d msg=%s', hostUin, data.code, data.message);
|
||||
throw new Error(`qzone upload image failed: code=${data.code} ${data.message ?? ''}`.trim());
|
||||
}
|
||||
if (typeof data.subcode === 'number' && data.subcode !== 0) {
|
||||
log.warn('uploadQzoneImage: non-zero subcode (uin=%s) subcode=%d msg=%s', hostUin, data.subcode, data.message);
|
||||
throw new Error(`qzone upload image failed: subcode=${data.subcode} ${data.message ?? ''}`.trim());
|
||||
}
|
||||
if (!data.data || !data.data.albumid || !data.data.lloc || !data.data.url) {
|
||||
log.warn('uploadQzoneImage: missing required fields in response (uin=%s)', hostUin);
|
||||
throw new Error('上传图片失败:响应缺少必要字段');
|
||||
}
|
||||
|
||||
const { albumid, lloc, url: imageUrl, type, height, width } = data.data;
|
||||
const sloc = lloc; // lloc and sloc are identical in the wire format
|
||||
const richval = `,${albumid},${lloc},${sloc},${type ?? 0},${height ?? 0},${width ?? 0},,${height ?? 0},${width ?? 0}`;
|
||||
|
||||
return {
|
||||
richval,
|
||||
url: imageUrl,
|
||||
albumid,
|
||||
lloc,
|
||||
type: type ?? 0,
|
||||
width: width ?? 0,
|
||||
height: height ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ─────────────── 评论说说 (comment) — emotion_cgi_re_feeds ───────────────
|
||||
// Posts a comment on a 说说 owned by `hostUin`, as the bot (`selfUin`). Same
|
||||
// form-POST mechanics + param family (paramstr/richtype/richval) as
|
||||
@@ -576,7 +798,15 @@ export interface QzoneCommentResult {
|
||||
|
||||
/**
|
||||
* Comment on a 说说 (`tid`, owned by `hostUin`) as the bot (`selfUin`) via
|
||||
* taotao.qzone.qq.com's emotion_cgi_re_feeds CGI (proxied through h5.qzone).
|
||||
* taotao.qzone.qq.com's emotion_cgi_re_feeds CGI (proxied through
|
||||
* h5.qzone.qq.com, matching php-qzone's working request).
|
||||
*
|
||||
* `richType` / `richval`: for image comments, set `richType=1` and pass the
|
||||
* direct image URL from {@link uploadQzoneImage}'s `url` field (NOT the
|
||||
* richval string — comment uses the direct URL, unlike publish which uses
|
||||
* richval). Multi-image comments use direct URLs joined with `\t`. Omit both
|
||||
* for text-only comments.
|
||||
*
|
||||
* Resolves with the new comment id (best-effort) on success; THROWS on a
|
||||
* transport failure or a non-zero Qzone `code`/`subcode` (e.g. comments
|
||||
* disabled, no permission, or auth failure).
|
||||
@@ -587,6 +817,8 @@ export async function commentQzoneMsg(
|
||||
hostUin: string,
|
||||
tid: string,
|
||||
content: string,
|
||||
richType?: number,
|
||||
richval?: string,
|
||||
): Promise<QzoneCommentResult> {
|
||||
if (!cookieObject || typeof cookieObject !== 'object') {
|
||||
throw new Error('cookieObject is required');
|
||||
@@ -597,6 +829,7 @@ export async function commentQzoneMsg(
|
||||
if (!content) {
|
||||
throw new Error('content is required');
|
||||
}
|
||||
assertRichParams(richType, richval);
|
||||
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_re_feeds?g_tk=${bkn}`;
|
||||
@@ -606,14 +839,14 @@ export async function commentQzoneMsg(
|
||||
inCharset: 'utf-8',
|
||||
outCharset: 'utf-8',
|
||||
hostUin,
|
||||
format: 'fs',
|
||||
format: 'json',
|
||||
ref: 'feeds',
|
||||
topicId: `${hostUin}_${tid}__1`,
|
||||
feedsType: '100',
|
||||
private: '0',
|
||||
paramstr: '1',
|
||||
richtype: '',
|
||||
richval: '',
|
||||
richtype: richType !== undefined ? String(richType) : '',
|
||||
richval: richval ?? '',
|
||||
isSignIn: '',
|
||||
uin: selfUin,
|
||||
content,
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { uploadQzoneImage, uploadQzoneImageFromSource } from '../../src/web/qzone';
|
||||
import { RequestUtil } from '../../src/web/request-util';
|
||||
|
||||
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();
|
||||
})();
|
||||
|
||||
const successBody = `<script>frameElement.callback({
|
||||
"code": 0,
|
||||
"subcode": 0,
|
||||
"data": {
|
||||
"albumid": "12345",
|
||||
"lloc": "abc123",
|
||||
"url": "https://example.qzone.qq.com/image.jpg",
|
||||
"type": 22,
|
||||
"height": 800,
|
||||
"width": 600
|
||||
}
|
||||
});</script>`;
|
||||
|
||||
describe('qzone / uploadQzoneImage', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('POSTs the upload form and returns richval + direct url', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(successBody);
|
||||
|
||||
const out = await uploadQzoneImage(cookies, '10000', 'AQID');
|
||||
|
||||
expect(out).toEqual({
|
||||
richval: ',12345,abc123,abc123,22,800,600,,800,600',
|
||||
url: 'https://example.qzone.qq.com/image.jpg',
|
||||
albumid: '12345',
|
||||
lloc: 'abc123',
|
||||
type: 22,
|
||||
width: 600,
|
||||
height: 800,
|
||||
});
|
||||
|
||||
const [url, method, body, headers] = spy.mock.calls[0]!;
|
||||
expect(url).toBe(`https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${expectedGtk}`);
|
||||
expect(method).toBe('POST');
|
||||
const h = headers as Record<string, string>;
|
||||
expect(h['Content-Type']).toBe('application/x-www-form-urlencoded');
|
||||
expect(h.Cookie).toContain('p_skey=PSK');
|
||||
expect(h.Cookie).toContain('skey=SK');
|
||||
|
||||
const form = new URLSearchParams(body as string);
|
||||
expect(form.get('uin')).toBe('10000');
|
||||
expect(form.get('p_uin')).toBe('10000');
|
||||
expect(form.get('p_skey')).toBe('PSK');
|
||||
expect(form.get('base64')).toBe('1');
|
||||
expect(form.get('jsonhtml_callback')).toBe('callback');
|
||||
expect(form.get('picfile')).toBe('AQID');
|
||||
expect(form.get('qzreferrer')).toBe('https://user.qzone.qq.com/10000/main');
|
||||
});
|
||||
|
||||
it('accepts base64:// data-URI sources and strips the prefix before upload', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(successBody);
|
||||
|
||||
await uploadQzoneImageFromSource(cookies, '10000', 'base64://data:image/png;base64,AQID');
|
||||
|
||||
const form = new URLSearchParams(spy.mock.calls[0]![2] as string);
|
||||
expect(form.get('picfile')).toBe('AQID');
|
||||
});
|
||||
|
||||
it('defaults optional image metadata to 0 when the upload succeeds without it', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(
|
||||
'callback({"code":0,"data":{"albumid":"12345","lloc":"abc123","url":"https://example.qzone.qq.com/image.jpg"}});',
|
||||
);
|
||||
|
||||
await expect(uploadQzoneImage(cookies, '10000', 'AQID')).resolves.toMatchObject({
|
||||
richval: ',12345,abc123,abc123,0,0,0,,0,0',
|
||||
type: 0,
|
||||
width: 0,
|
||||
height: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects invalid base64 before any request', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
|
||||
|
||||
await expect(uploadQzoneImage(cookies, '10000', 'not base64?')).rejects.toThrow('valid base64');
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws on non-zero code or subcode from Qzone', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
|
||||
|
||||
spy.mockResolvedValueOnce('callback({"code":-1,"message":"upload failed"});');
|
||||
await expect(uploadQzoneImage(cookies, '10000', 'AQID')).rejects.toThrow('code=-1');
|
||||
|
||||
spy.mockResolvedValueOnce('callback({"code":0,"subcode":-2,"message":"sub failed"});');
|
||||
await expect(uploadQzoneImage(cookies, '10000', 'AQID')).rejects.toThrow('subcode=-2');
|
||||
});
|
||||
|
||||
it('throws when the success response lacks required upload fields', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('callback({"code":0,"data":{"albumid":"12345"}});');
|
||||
|
||||
await expect(uploadQzoneImage(cookies, '10000', 'AQID')).rejects.toThrow('响应缺少必要字段');
|
||||
});
|
||||
});
|
||||
@@ -222,6 +222,19 @@ describe('qzone / publishQzoneMsg (HTTP layer)', () => {
|
||||
expect(form.get('qzreferrer')).toBe('https://user.qzone.qq.com/10000');
|
||||
});
|
||||
|
||||
it('threads image richType/richval into the publish form', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(
|
||||
'{"code":0,"t1_tid":"NEWTID","t1_time":"1700000000"}',
|
||||
);
|
||||
const richval = ',12345,abc,abc,22,800,600,,800,600\t,12346,def,def,22,640,480,,640,480';
|
||||
|
||||
await publishQzoneMsg(cookies, '10000', 'with images', 1, richval);
|
||||
|
||||
const form = new URLSearchParams(spy.mock.calls[0]![2] as string);
|
||||
expect(form.get('richtype')).toBe('1');
|
||||
expect(form.get('richval')).toBe(richval);
|
||||
});
|
||||
|
||||
it('falls back to tid/now for alternate client builds', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"tid":"ALT","now":1700000001}');
|
||||
await expect(publishQzoneMsg(cookies, '10000', 'hi')).resolves.toEqual({ tid: 'ALT', time: 1700000001 });
|
||||
@@ -233,6 +246,13 @@ describe('qzone / publishQzoneMsg (HTTP layer)', () => {
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects incomplete publish rich params before any request', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
|
||||
await expect(publishQzoneMsg(cookies, '10000', 'hi', 1)).rejects.toThrow('richType and richval');
|
||||
await expect(publishQzoneMsg(cookies, '10000', 'hi', undefined, ',123')).rejects.toThrow('richType and richval');
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws on a non-zero qzone code (rejected/rate-limited)', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-10000,"message":"too frequent"}');
|
||||
await expect(publishQzoneMsg(cookies, '10000', 'hi')).rejects.toThrow('code=-10000');
|
||||
@@ -378,7 +398,7 @@ describe('qzone / commentQzoneMsg (HTTP layer)', () => {
|
||||
expect(form.get('uin')).toBe('10000');
|
||||
expect(form.get('hostUin')).toBe('20002');
|
||||
expect(form.get('content')).toBe('说得好 & 顶');
|
||||
expect(form.get('format')).toBe('fs');
|
||||
expect(form.get('format')).toBe('json');
|
||||
// qzreferrer carries the commenter's own space (matches the impls)
|
||||
expect(form.get('qzreferrer')).toBe('https://user.qzone.qq.com/10000');
|
||||
// the re_feeds param family (3/3 impls) the publish sibling also sends
|
||||
@@ -387,6 +407,17 @@ describe('qzone / commentQzoneMsg (HTTP layer)', () => {
|
||||
expect(form.get('paramstr')).toBe('1');
|
||||
});
|
||||
|
||||
it('threads image direct-url richval into the comment form', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"commentid":987}');
|
||||
const richval = 'https://example.qzone.qq.com/a.jpg\thttps://example.qzone.qq.com/b.jpg';
|
||||
|
||||
await commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'pics', 1, richval);
|
||||
|
||||
const form = new URLSearchParams(spy.mock.calls[0]![2] as string);
|
||||
expect(form.get('richtype')).toBe('1');
|
||||
expect(form.get('richval')).toBe(richval);
|
||||
});
|
||||
|
||||
it('resolves with empty comment_id on success when the response carries no id (field name varies)', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0}');
|
||||
await expect(commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'hi')).resolves.toEqual({ comment_id: '' });
|
||||
@@ -404,6 +435,13 @@ describe('qzone / commentQzoneMsg (HTTP layer)', () => {
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects incomplete comment rich params before any request', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
|
||||
await expect(commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'hi', 1)).rejects.toThrow('richType and richval');
|
||||
await expect(commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'hi', undefined, 'https://example.com/img.jpg')).rejects.toThrow('richType and richval');
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws on a non-zero code (comments disabled / no permission)', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-3000,"message":"forbidden"}');
|
||||
await expect(commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'hi')).rejects.toThrow('comment failed: code=-3000');
|
||||
|
||||
Reference in new issue
Block a user