lint
This commit is contained in:
977 files changed
+198426
-158324
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -1,226 +1,264 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
FriendDressError,
|
||||
getFriendDressWebAPI,
|
||||
} from '@snowluma/protocol/web/friend-dress';
|
||||
import { FriendDressError, getFriendDressWebAPI } from '@snowluma/protocol/web/friend-dress';
|
||||
import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
|
||||
// 真实装扮页 SSR HTML(脱敏:uin 改为 10000、头像 hash 已打码)。
|
||||
// __INITIAL_ASYNCDATA__ 里 7 项装扮:气泡(2)/名片(15)/彩色屏保(22)/来电(17)/
|
||||
// 挂件(4)/头像(23)/头像双击动作(47) —— 其中 2/23 属服务器不回真值的废数据。
|
||||
const SAMPLE_HTML = readFileSync(
|
||||
fileURLToPath(new URL('./fixtures/friend-dress-sample.html', import.meta.url)),
|
||||
'utf8',
|
||||
fileURLToPath(new URL('./fixtures/friend-dress-sample.html', import.meta.url)),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
const cookies = { uin: 'o10001', skey: 'SKEY', p_uin: 'o10001', p_skey: 'PSKEY' };
|
||||
|
||||
/** 把任意 asyncData 对象包成最小可解析的 SSR HTML。 */
|
||||
const wrapHtml = (data: unknown): string =>
|
||||
`<html><script>window.__INITIAL_ASYNCDATA__=${JSON.stringify(data)};(function(){})()</script></html>`;
|
||||
`<html><script>window.__INITIAL_ASYNCDATA__=${JSON.stringify(data)};(function(){})()</script></html>`;
|
||||
|
||||
const mockHtml = (html: string) =>
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(html as never);
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(html as never);
|
||||
|
||||
describe('friend-dress / real sample parsing', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('sends cookie + mobile UA to zb.vip.qq.com with the target uin', async () => {
|
||||
const request = mockHtml(SAMPLE_HTML);
|
||||
await getFriendDressWebAPI(cookies, '10000');
|
||||
it('sends cookie + mobile UA to zb.vip.qq.com with the target uin', async () => {
|
||||
const request = mockHtml(SAMPLE_HTML);
|
||||
await getFriendDressWebAPI(cookies, '10000');
|
||||
|
||||
const [url, method, , headers, limits] = request.mock.calls[0]!;
|
||||
expect(url).toContain('https://zb.vip.qq.com/v2/pages/aioDressPage?');
|
||||
expect(url).toContain('targetUin=10000');
|
||||
// traceDetail 是预编码的 base64 串,必须原样出现(不能被二次编码成 base64%2D…)。
|
||||
expect(url).toContain('&traceDetail=base64-');
|
||||
expect(method).toBe('GET');
|
||||
expect(headers).toMatchObject({
|
||||
Cookie: 'uin=o10001; skey=SKEY; p_uin=o10001; p_skey=PSKEY',
|
||||
const [url, method, , headers, limits] = request.mock.calls[0]!;
|
||||
expect(url).toContain('https://zb.vip.qq.com/v2/pages/aioDressPage?');
|
||||
expect(url).toContain('targetUin=10000');
|
||||
// traceDetail 是预编码的 base64 串,必须原样出现(不能被二次编码成 base64%2D…)。
|
||||
expect(url).toContain('&traceDetail=base64-');
|
||||
expect(method).toBe('GET');
|
||||
expect(headers).toMatchObject({
|
||||
Cookie: 'uin=o10001; skey=SKEY; p_uin=o10001; p_skey=PSKEY',
|
||||
});
|
||||
expect((headers as Record<string, string>)['User-Agent']).toContain('QQ/');
|
||||
expect(limits).toEqual({
|
||||
timeoutMs: 10_000,
|
||||
maxResponseBytes: 2 * 1024 * 1024,
|
||||
});
|
||||
});
|
||||
expect((headers as Record<string, string>)['User-Agent']).toContain('QQ/');
|
||||
expect(limits).toEqual({
|
||||
timeoutMs: 10_000,
|
||||
maxResponseBytes: 2 * 1024 * 1024,
|
||||
|
||||
it('parses the real page: svip, avatar, and only resolvable dress items', async () => {
|
||||
mockHtml(SAMPLE_HTML);
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
|
||||
expect(dress.target_uin).toBe('10000');
|
||||
expect(dress.is_svip).toBe(true);
|
||||
expect(dress.avatar_url).toBe('https://q.qlogo.cn/g?b=qq&nk=10000&s=100');
|
||||
|
||||
// 气泡(2)/头像(23) 是服务器永远回默认款的废数据,必须被剔除。
|
||||
const appIds = dress.items.map((i) => i.app_id);
|
||||
expect(appIds).not.toContain(2);
|
||||
expect(appIds).not.toContain(23);
|
||||
expect(appIds).toEqual([15, 22, 17, 4, 47]);
|
||||
});
|
||||
});
|
||||
|
||||
it('parses the real page: svip, avatar, and only resolvable dress items', async () => {
|
||||
mockHtml(SAMPLE_HTML);
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
it('maps item fields: kind, itemId default 0, price default 0', async () => {
|
||||
mockHtml(SAMPLE_HTML);
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
|
||||
expect(dress.target_uin).toBe('10000');
|
||||
expect(dress.is_svip).toBe(true);
|
||||
expect(dress.avatar_url).toBe('https://q.qlogo.cn/g?b=qq&nk=10000&s=100');
|
||||
const card = dress.items.find((i) => i.app_id === 15)!;
|
||||
expect(card.kind).toBe('名片');
|
||||
expect(card.item_id).toBe(201534);
|
||||
expect(card.name).toBe('二次元少女');
|
||||
expect(card.preview_url).toBe(
|
||||
'https://tianquan.gtimg.cn/card/original/201534/templateThumb.jpg',
|
||||
);
|
||||
expect(card.price).toBe(0);
|
||||
|
||||
// 气泡(2)/头像(23) 是服务器永远回默认款的废数据,必须被剔除。
|
||||
const appIds = dress.items.map((i) => i.app_id);
|
||||
expect(appIds).not.toContain(2);
|
||||
expect(appIds).not.toContain(23);
|
||||
expect(appIds).toEqual([15, 22, 17, 4, 47]);
|
||||
});
|
||||
// 默认挂件没有 itemId 字段 → 0。
|
||||
const widget = dress.items.find((i) => i.app_id === 4)!;
|
||||
expect(widget.item_id).toBe(0);
|
||||
expect(widget.kind).toBe('挂件');
|
||||
});
|
||||
|
||||
it('maps item fields: kind, itemId default 0, price default 0', async () => {
|
||||
mockHtml(SAMPLE_HTML);
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
it('derives the funcall video url from the real web_image.jpg preview', async () => {
|
||||
mockHtml(SAMPLE_HTML);
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
|
||||
const card = dress.items.find((i) => i.app_id === 15)!;
|
||||
expect(card.kind).toBe('名片');
|
||||
expect(card.item_id).toBe(201534);
|
||||
expect(card.name).toBe('二次元少女');
|
||||
expect(card.preview_url).toBe('https://tianquan.gtimg.cn/card/original/201534/templateThumb.jpg');
|
||||
expect(card.price).toBe(0);
|
||||
|
||||
// 默认挂件没有 itemId 字段 → 0。
|
||||
const widget = dress.items.find((i) => i.app_id === 4)!;
|
||||
expect(widget.item_id).toBe(0);
|
||||
expect(widget.kind).toBe('挂件');
|
||||
});
|
||||
|
||||
it('derives the funcall video url from the real web_image.jpg preview', async () => {
|
||||
mockHtml(SAMPLE_HTML);
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
|
||||
const funcall = dress.items.find((i) => i.app_id === 17)!;
|
||||
expect(funcall.preview_url).toBe('https://tianquan.gtimg.cn/funcall/funCall/2730/web_image.jpg');
|
||||
expect(funcall.video_url).toBe('https://tianquan.gtimg.cn/funcall/funCall/2730/media.mp4');
|
||||
});
|
||||
const funcall = dress.items.find((i) => i.app_id === 17)!;
|
||||
expect(funcall.preview_url).toBe(
|
||||
'https://tianquan.gtimg.cn/funcall/funCall/2730/web_image.jpg',
|
||||
);
|
||||
expect(funcall.video_url).toBe('https://tianquan.gtimg.cn/funcall/funCall/2730/media.mp4');
|
||||
});
|
||||
});
|
||||
|
||||
describe('friend-dress / synthetic payloads', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
const base = { targetUin: '10000', isSvip: false, avatarImage: '', rawUsingList: [] as unknown[] };
|
||||
const base = {
|
||||
targetUin: '10000',
|
||||
isSvip: false,
|
||||
avatarImage: '',
|
||||
rawUsingList: [] as unknown[],
|
||||
};
|
||||
|
||||
it('an empty rawUsingList is a valid result, not an error', async () => {
|
||||
mockHtml(wrapHtml(base));
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
expect(dress.items).toEqual([]);
|
||||
expect(dress.is_svip).toBe(false);
|
||||
});
|
||||
it('an empty rawUsingList is a valid result, not an error', async () => {
|
||||
mockHtml(wrapHtml(base));
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
expect(dress.items).toEqual([]);
|
||||
expect(dress.is_svip).toBe(false);
|
||||
});
|
||||
|
||||
it('does NOT return the image url as video when a funcall preview has an unexpected name', async () => {
|
||||
mockHtml(wrapHtml({
|
||||
...base,
|
||||
rawUsingList: [{ appId: 17, itemId: 1, name: 'x', image: 'https://cdn.example/funCall/1/preview.png' }],
|
||||
}));
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
expect(dress.items[0]!.video_url).toBe('');
|
||||
expect(dress.items[0]!.preview_url).toBe('https://cdn.example/funCall/1/preview.png');
|
||||
});
|
||||
it('does NOT return the image url as video when a funcall preview has an unexpected name', async () => {
|
||||
mockHtml(
|
||||
wrapHtml({
|
||||
...base,
|
||||
rawUsingList: [
|
||||
{
|
||||
appId: 17,
|
||||
itemId: 1,
|
||||
name: 'x',
|
||||
image: 'https://cdn.example/funCall/1/preview.png',
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
expect(dress.items[0]!.video_url).toBe('');
|
||||
expect(dress.items[0]!.preview_url).toBe('https://cdn.example/funCall/1/preview.png');
|
||||
});
|
||||
|
||||
it('extracts the card video from immersiveMaterial', async () => {
|
||||
mockHtml(wrapHtml({
|
||||
...base,
|
||||
rawUsingList: [{
|
||||
appId: 15, itemId: 1, name: 'a', image: 'https://cdn.example/a.jpg',
|
||||
extraappinfo: { extraInfo: { immersiveMaterial: '{"videoUrl":"https://cdn.example/a.mp4"}' } },
|
||||
}],
|
||||
}));
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
expect(dress.items[0]!.video_url).toBe('https://cdn.example/a.mp4');
|
||||
});
|
||||
it('extracts the card video from immersiveMaterial', async () => {
|
||||
mockHtml(
|
||||
wrapHtml({
|
||||
...base,
|
||||
rawUsingList: [
|
||||
{
|
||||
appId: 15,
|
||||
itemId: 1,
|
||||
name: 'a',
|
||||
image: 'https://cdn.example/a.jpg',
|
||||
extraappinfo: {
|
||||
extraInfo: {
|
||||
immersiveMaterial: '{"videoUrl":"https://cdn.example/a.mp4"}',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
expect(dress.items[0]!.video_url).toBe('https://cdn.example/a.mp4');
|
||||
});
|
||||
|
||||
it('labels unknown appIds without dropping them', async () => {
|
||||
mockHtml(wrapHtml({
|
||||
...base,
|
||||
rawUsingList: [{ appId: 999, itemId: 7, name: 'n', image: '' }],
|
||||
}));
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
expect(dress.items[0]!.kind).toBe('appId=999');
|
||||
});
|
||||
it('labels unknown appIds without dropping them', async () => {
|
||||
mockHtml(
|
||||
wrapHtml({
|
||||
...base,
|
||||
rawUsingList: [{ appId: 999, itemId: 7, name: 'n', image: '' }],
|
||||
}),
|
||||
);
|
||||
const dress = await getFriendDressWebAPI(cookies, '10000');
|
||||
expect(dress.items[0]!.kind).toBe('appId=999');
|
||||
});
|
||||
});
|
||||
|
||||
describe('friend-dress / error classification', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
const expectKind = async (uin: string, kind: string) => {
|
||||
const e = await getFriendDressWebAPI(cookies, uin).catch((err: unknown) => err);
|
||||
expect(e).toBeInstanceOf(FriendDressError);
|
||||
expect((e as FriendDressError).kind).toBe(kind);
|
||||
return e as FriendDressError;
|
||||
};
|
||||
const expectKind = async (uin: string, kind: string) => {
|
||||
const e = await getFriendDressWebAPI(cookies, uin).catch((err: unknown) => err);
|
||||
expect(e).toBeInstanceOf(FriendDressError);
|
||||
expect((e as FriendDressError).kind).toBe(kind);
|
||||
return e as FriendDressError;
|
||||
};
|
||||
|
||||
it('network: transport failure is not folded into a parse error', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockRejectedValue(new Error('Unexpected status code: 403'));
|
||||
const e = await expectKind('10000', 'network');
|
||||
expect(e.message).toContain('403');
|
||||
});
|
||||
it('network: transport failure is not folded into a parse error', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockRejectedValue(
|
||||
new Error('Unexpected status code: 403'),
|
||||
);
|
||||
const e = await expectKind('10000', 'network');
|
||||
expect(e.message).toContain('403');
|
||||
});
|
||||
|
||||
it('parse: html without __INITIAL_ASYNCDATA__ (login-wall / risk-control shell)', async () => {
|
||||
mockHtml('<html><body>请先登录</body></html>');
|
||||
await expectKind('10000', 'parse');
|
||||
});
|
||||
it('parse: html without __INITIAL_ASYNCDATA__ (login-wall / risk-control shell)', async () => {
|
||||
mockHtml('<html><body>请先登录</body></html>');
|
||||
await expectKind('10000', 'parse');
|
||||
});
|
||||
|
||||
it('parse: __INITIAL_ASYNCDATA__ present but not valid JSON', async () => {
|
||||
mockHtml('<script>window.__INITIAL_ASYNCDATA__={oops};(function(){})()</script>');
|
||||
await expectKind('10000', 'parse');
|
||||
});
|
||||
it('parse: __INITIAL_ASYNCDATA__ present but not valid JSON', async () => {
|
||||
mockHtml('<script>window.__INITIAL_ASYNCDATA__={oops};(function(){})()</script>');
|
||||
await expectKind('10000', 'parse');
|
||||
});
|
||||
|
||||
it('parse: a top-level array never matches the SSR object shape', async () => {
|
||||
mockHtml(wrapHtml([1, 2]));
|
||||
await expectKind('10000', 'parse');
|
||||
});
|
||||
it('parse: a top-level array never matches the SSR object shape', async () => {
|
||||
mockHtml(wrapHtml([1, 2]));
|
||||
await expectKind('10000', 'parse');
|
||||
});
|
||||
|
||||
it('structure: malformed immersiveMaterial is not silently discarded', async () => {
|
||||
mockHtml(wrapHtml({
|
||||
targetUin: '10000',
|
||||
rawUsingList: [{
|
||||
appId: 15,
|
||||
itemId: 2,
|
||||
name: 'broken',
|
||||
image: 'https://cdn.example/b.jpg',
|
||||
extraappinfo: { extraInfo: { immersiveMaterial: '{not json' } },
|
||||
}],
|
||||
}));
|
||||
const e = await expectKind('10000', 'structure');
|
||||
expect(e.message).toContain('immersiveMaterial');
|
||||
});
|
||||
it('structure: malformed immersiveMaterial is not silently discarded', async () => {
|
||||
mockHtml(
|
||||
wrapHtml({
|
||||
targetUin: '10000',
|
||||
rawUsingList: [
|
||||
{
|
||||
appId: 15,
|
||||
itemId: 2,
|
||||
name: 'broken',
|
||||
image: 'https://cdn.example/b.jpg',
|
||||
extraappinfo: { extraInfo: { immersiveMaterial: '{not json' } },
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const e = await expectKind('10000', 'structure');
|
||||
expect(e.message).toContain('immersiveMaterial');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['not a string', { videoUrl: 'https://cdn.example/video.mp4' }],
|
||||
['an array', '[]'],
|
||||
['missing videoUrl', '{}'],
|
||||
['non-string videoUrl', '{"videoUrl":42}'],
|
||||
])('structure: immersiveMaterial %s is not silently discarded', async (_label, material) => {
|
||||
mockHtml(wrapHtml({
|
||||
targetUin: '10000',
|
||||
rawUsingList: [{
|
||||
appId: 15,
|
||||
itemId: 2,
|
||||
name: 'broken',
|
||||
image: 'https://cdn.example/b.jpg',
|
||||
extraappinfo: { extraInfo: { immersiveMaterial: material } },
|
||||
}],
|
||||
}));
|
||||
const e = await expectKind('10000', 'structure');
|
||||
expect(e.message).toContain('immersiveMaterial');
|
||||
});
|
||||
it.each([
|
||||
['not a string', { videoUrl: 'https://cdn.example/video.mp4' }],
|
||||
['an array', '[]'],
|
||||
['missing videoUrl', '{}'],
|
||||
['non-string videoUrl', '{"videoUrl":42}'],
|
||||
])('structure: immersiveMaterial %s is not silently discarded', async (_label, material) => {
|
||||
mockHtml(
|
||||
wrapHtml({
|
||||
targetUin: '10000',
|
||||
rawUsingList: [
|
||||
{
|
||||
appId: 15,
|
||||
itemId: 2,
|
||||
name: 'broken',
|
||||
image: 'https://cdn.example/b.jpg',
|
||||
extraappinfo: { extraInfo: { immersiveMaterial: material } },
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const e = await expectKind('10000', 'structure');
|
||||
expect(e.message).toContain('immersiveMaterial');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['rawUsingList missing', { targetUin: '10000' }],
|
||||
['rawUsingList not an array', { targetUin: '10000', rawUsingList: 'nope' }],
|
||||
['item not an object', { targetUin: '10000', rawUsingList: ['nope'] }],
|
||||
['item appId missing', { targetUin: '10000', rawUsingList: [{}] }],
|
||||
['item appId not a number', { targetUin: '10000', rawUsingList: [{ appId: 'four' }] }],
|
||||
['targetUin not a string', { targetUin: 10000, rawUsingList: [] }],
|
||||
])('structure: %s', async (_label, payload) => {
|
||||
mockHtml(wrapHtml(payload));
|
||||
await expectKind('10000', 'structure');
|
||||
});
|
||||
it.each([
|
||||
['rawUsingList missing', { targetUin: '10000' }],
|
||||
['rawUsingList not an array', { targetUin: '10000', rawUsingList: 'nope' }],
|
||||
['item not an object', { targetUin: '10000', rawUsingList: ['nope'] }],
|
||||
['item appId missing', { targetUin: '10000', rawUsingList: [{}] }],
|
||||
['item appId not a number', { targetUin: '10000', rawUsingList: [{ appId: 'four' }] }],
|
||||
['targetUin not a string', { targetUin: 10000, rawUsingList: [] }],
|
||||
])('structure: %s', async (_label, payload) => {
|
||||
mockHtml(wrapHtml(payload));
|
||||
await expectKind('10000', 'structure');
|
||||
});
|
||||
|
||||
it('uin_mismatch: page answers for a different account than requested', async () => {
|
||||
mockHtml(wrapHtml({ targetUin: '20000', rawUsingList: [] }));
|
||||
const e = await expectKind('10000', 'uin_mismatch');
|
||||
expect(e.message).toContain('20000');
|
||||
expect(e.message).toContain('10000');
|
||||
});
|
||||
it('uin_mismatch: page answers for a different account than requested', async () => {
|
||||
mockHtml(wrapHtml({ targetUin: '20000', rawUsingList: [] }));
|
||||
const e = await expectKind('10000', 'uin_mismatch');
|
||||
expect(e.message).toContain('20000');
|
||||
expect(e.message).toContain('10000');
|
||||
});
|
||||
|
||||
it('structure: targetUin missing cannot prove which account owns the response', async () => {
|
||||
mockHtml(wrapHtml({ rawUsingList: [] }));
|
||||
const e = await expectKind('10000', 'structure');
|
||||
expect(e.message).toContain('targetUin');
|
||||
});
|
||||
it('structure: targetUin missing cannot prove which account owns the response', async () => {
|
||||
mockHtml(wrapHtml({ rawUsingList: [] }));
|
||||
const e = await expectKind('10000', 'structure');
|
||||
expect(e.message).toContain('targetUin');
|
||||
});
|
||||
});
|
||||
@@ -11,177 +11,198 @@ const JPEG_SOURCE = 'base64:///9j/4AAQSkZJRgABAQAAAQABAAD/2wAAAA==';
|
||||
const COVER = Buffer.from('album-cover');
|
||||
|
||||
function controlReq(body: unknown): Record<string, unknown> {
|
||||
const req = (body as { control_req: Array<Record<string, unknown>> }).control_req[0];
|
||||
expect(req).toBeTruthy();
|
||||
return req;
|
||||
const req = (body as { control_req: Array<Record<string, unknown>> }).control_req[0];
|
||||
expect(req).toBeTruthy();
|
||||
return req;
|
||||
}
|
||||
|
||||
describe('group album image upload', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('rejects an MP4 before starting a remote upload', async () => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockRejectedValue(new Error('unexpected remote upload'));
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
it('rejects an MP4 before starting a remote upload', async () => {
|
||||
const request = vi
|
||||
.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockRejectedValue(new Error('unexpected remote upload'));
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
|
||||
await expect(uploadImageToGroupAlbum(
|
||||
{ skey: 'SK', p_skey: 'PSK' },
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
MP4_SOURCE,
|
||||
'10000',
|
||||
)).rejects.toThrow('群相册上传仅支持 JPEG、PNG、GIF、WebP 或 BMP 图片');
|
||||
await expect(
|
||||
uploadImageToGroupAlbum(
|
||||
{ skey: 'SK', p_skey: 'PSK' },
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
MP4_SOURCE,
|
||||
'10000',
|
||||
),
|
||||
).rejects.toThrow('群相册上传仅支持 JPEG、PNG、GIF、WebP 或 BMP 图片');
|
||||
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('group album video upload', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('rejects a JPEG before starting a remote upload', async () => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockRejectedValue(new Error('unexpected remote upload'));
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
const probe = vi.fn();
|
||||
|
||||
await expect(uploadVideoToGroupAlbum(
|
||||
{ skey: 'SK', p_skey: 'PSK' },
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
JPEG_SOURCE,
|
||||
'10000',
|
||||
{ probe },
|
||||
)).rejects.toThrow('群相册视频上传仅支持 MP4 等 ISO BMFF 视频');
|
||||
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(probe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uploads the video with SHA1 then the cover bound to the returned vid', async () => {
|
||||
const sha1 = createHash('sha1').update(MP4_BYTES).digest('hex');
|
||||
const coverMd5 = createHash('md5').update(COVER).digest('hex');
|
||||
const bodies: unknown[] = [];
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockImplementation(async (_url, _method, body) => {
|
||||
bodies.push(body);
|
||||
const appid = controlReq(body).appid;
|
||||
if (appid === 'video_qun') {
|
||||
return { ret: 0, msg: '', data: { session: 'video-session', slice_size: 16384 } };
|
||||
}
|
||||
return { ret: 0, msg: '', data: { session: 'cover-session', slice_size: 16384 } };
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
const fetch = vi.fn(async (url: string) => ({
|
||||
ok: true,
|
||||
json: async () => {
|
||||
if (url.includes('FileUploadVideo')) {
|
||||
return { ret: 0, msg: '', data: { biz: { sVid: 'VID123' } } };
|
||||
}
|
||||
return { ret: 0, msg: '', data: { biz: { sPhotoID: 'PID', sBURL: 'https://example.test/v.jpg' } } };
|
||||
},
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
it('rejects a JPEG before starting a remote upload', async () => {
|
||||
const request = vi
|
||||
.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockRejectedValue(new Error('unexpected remote upload'));
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
const probe = vi.fn();
|
||||
|
||||
const result = await uploadVideoToGroupAlbum(
|
||||
{ skey: 'SK', p_skey: 'PSK' },
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
MP4_SOURCE,
|
||||
'10000',
|
||||
{
|
||||
now: () => 1700000000,
|
||||
probe: async () => ({ duration: 6.077, cover: new Uint8Array(COVER) }),
|
||||
},
|
||||
);
|
||||
await expect(
|
||||
uploadVideoToGroupAlbum(
|
||||
{ skey: 'SK', p_skey: 'PSK' },
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
JPEG_SOURCE,
|
||||
'10000',
|
||||
{ probe },
|
||||
),
|
||||
).rejects.toThrow('群相册视频上传仅支持 MP4 等 ISO BMFF 视频');
|
||||
|
||||
expect(result).toEqual({ id: 'VID123' });
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
expect(String(request.mock.calls[0]![0])).toContain(`FileBatchControl/${sha1}`);
|
||||
expect(String(request.mock.calls[1]![0])).toContain(`FileBatchControl/${coverMd5}`);
|
||||
|
||||
const videoReq = controlReq(bodies[0]);
|
||||
expect(videoReq).toMatchObject({
|
||||
appid: 'video_qun',
|
||||
checksum: sha1,
|
||||
check_type: 1,
|
||||
cmd: 'FileUploadVideo',
|
||||
env: { refer: 'qzone', deviceInfo: 'h5' },
|
||||
});
|
||||
expect(videoReq.biz_req).toMatchObject({
|
||||
iUploadType: 3,
|
||||
iPlayTime: 6077,
|
||||
iIsNew: 111,
|
||||
sTitle: 'video.mp4',
|
||||
extend_info: {
|
||||
video_type: '3',
|
||||
domainid: '5',
|
||||
photo_num: '0',
|
||||
video_num: '1',
|
||||
qun_id: '12345',
|
||||
},
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(probe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const coverReq = controlReq(bodies[1]);
|
||||
expect(coverReq).toMatchObject({
|
||||
appid: 'qun',
|
||||
checksum: coverMd5,
|
||||
check_type: 0,
|
||||
cmd: '',
|
||||
env: { refer: 'huodong', deviceInfo: 'h5' },
|
||||
});
|
||||
expect(coverReq.biz_req).toMatchObject({
|
||||
iUploadType: 2,
|
||||
iBatchID: 1700000000,
|
||||
sAlbumID: 'album-id',
|
||||
sAlbumName: 'album-name',
|
||||
mutliPicInfo: { iBatUploadNum: 1 },
|
||||
stExtendInfo: { mapParams: { vid: 'VID123', photo_num: '0', video_num: '1' } },
|
||||
stExternalMapExt: { is_client_upload_cover: '1', is_pic_video_mix_feeds: '1' },
|
||||
it('uploads the video with SHA1 then the cover bound to the returned vid', async () => {
|
||||
const sha1 = createHash('sha1').update(MP4_BYTES).digest('hex');
|
||||
const coverMd5 = createHash('md5').update(COVER).digest('hex');
|
||||
const bodies: unknown[] = [];
|
||||
const request = vi
|
||||
.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockImplementation(async (_url, _method, body) => {
|
||||
bodies.push(body);
|
||||
const appid = controlReq(body).appid;
|
||||
|
||||
if (appid === 'video_qun') {
|
||||
return {
|
||||
ret: 0,
|
||||
msg: '',
|
||||
data: { session: 'video-session', slice_size: 16384 },
|
||||
};
|
||||
}
|
||||
|
||||
return { ret: 0, msg: '', data: { session: 'cover-session', slice_size: 16384 } };
|
||||
});
|
||||
|
||||
const fetch = vi.fn(async (url: string) => ({
|
||||
ok: true,
|
||||
json: async () => {
|
||||
if (url.includes('FileUploadVideo')) {
|
||||
return { ret: 0, msg: '', data: { biz: { sVid: 'VID123' } } };
|
||||
}
|
||||
|
||||
return {
|
||||
ret: 0,
|
||||
msg: '',
|
||||
data: { biz: { sPhotoID: 'PID', sBURL: 'https://example.test/v.jpg' } },
|
||||
};
|
||||
},
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
|
||||
const result = await uploadVideoToGroupAlbum(
|
||||
{ skey: 'SK', p_skey: 'PSK' },
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
MP4_SOURCE,
|
||||
'10000',
|
||||
{
|
||||
now: () => 1700000000,
|
||||
probe: async () => ({ duration: 6.077, cover: new Uint8Array(COVER) }),
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toEqual({ id: 'VID123' });
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
expect(String(request.mock.calls[0]![0])).toContain(`FileBatchControl/${sha1}`);
|
||||
expect(String(request.mock.calls[1]![0])).toContain(`FileBatchControl/${coverMd5}`);
|
||||
|
||||
const videoReq = controlReq(bodies[0]);
|
||||
expect(videoReq).toMatchObject({
|
||||
appid: 'video_qun',
|
||||
checksum: sha1,
|
||||
check_type: 1,
|
||||
cmd: 'FileUploadVideo',
|
||||
env: { refer: 'qzone', deviceInfo: 'h5' },
|
||||
});
|
||||
expect(videoReq.biz_req).toMatchObject({
|
||||
iUploadType: 3,
|
||||
iPlayTime: 6077,
|
||||
iIsNew: 111,
|
||||
sTitle: 'video.mp4',
|
||||
extend_info: {
|
||||
video_type: '3',
|
||||
domainid: '5',
|
||||
photo_num: '0',
|
||||
video_num: '1',
|
||||
qun_id: '12345',
|
||||
},
|
||||
});
|
||||
|
||||
const coverReq = controlReq(bodies[1]);
|
||||
expect(coverReq).toMatchObject({
|
||||
appid: 'qun',
|
||||
checksum: coverMd5,
|
||||
check_type: 0,
|
||||
cmd: '',
|
||||
env: { refer: 'huodong', deviceInfo: 'h5' },
|
||||
});
|
||||
expect(coverReq.biz_req).toMatchObject({
|
||||
iUploadType: 2,
|
||||
iBatchID: 1700000000,
|
||||
sAlbumID: 'album-id',
|
||||
sAlbumName: 'album-name',
|
||||
mutliPicInfo: { iBatUploadNum: 1 },
|
||||
stExtendInfo: { mapParams: { vid: 'VID123', photo_num: '0', video_num: '1' } },
|
||||
stExternalMapExt: { is_client_upload_cover: '1', is_pic_video_mix_feeds: '1' },
|
||||
});
|
||||
|
||||
const sliceUrls = fetch.mock.calls.map((call) => String(call[0]));
|
||||
expect(sliceUrls.some((url) => url.includes('/sliceUpload/FileUploadVideo?'))).toBe(true);
|
||||
expect(sliceUrls.some((url) => url.includes('/sliceUpload/FileUpload?'))).toBe(true);
|
||||
});
|
||||
|
||||
const sliceUrls = fetch.mock.calls.map((call) => String(call[0]));
|
||||
expect(sliceUrls.some((url) => url.includes('/sliceUpload/FileUploadVideo?'))).toBe(true);
|
||||
expect(sliceUrls.some((url) => url.includes('/sliceUpload/FileUpload?'))).toBe(true);
|
||||
});
|
||||
it('fails when the video slices do not return a vid', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
ret: 0,
|
||||
msg: '',
|
||||
data: { session: 'video-session', slice_size: 16384 },
|
||||
});
|
||||
const fetch = vi.fn(async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ ret: 0, msg: '', data: { biz: {} } }),
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
|
||||
it('fails when the video slices do not return a vid', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
ret: 0,
|
||||
msg: '',
|
||||
data: { session: 'video-session', slice_size: 16384 },
|
||||
await expect(
|
||||
uploadVideoToGroupAlbum(
|
||||
{ skey: 'SK', p_skey: 'PSK' },
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
MP4_SOURCE,
|
||||
'10000',
|
||||
{
|
||||
now: () => 1700000000,
|
||||
probe: async () => ({ duration: 6, cover: new Uint8Array(COVER) }),
|
||||
},
|
||||
),
|
||||
).rejects.toThrow('视频上传未返回视频 id');
|
||||
|
||||
expect(RequestUtil.HttpGetJson).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
const fetch = vi.fn(async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ ret: 0, msg: '', data: { biz: {} } }),
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
|
||||
await expect(uploadVideoToGroupAlbum(
|
||||
{ skey: 'SK', p_skey: 'PSK' },
|
||||
'12345',
|
||||
'album-id',
|
||||
'album-name',
|
||||
MP4_SOURCE,
|
||||
'10000',
|
||||
{
|
||||
now: () => 1700000000,
|
||||
probe: async () => ({ duration: 6, cover: new Uint8Array(COVER) }),
|
||||
},
|
||||
)).rejects.toThrow('视频上传未返回视频 id');
|
||||
|
||||
expect(RequestUtil.HttpGetJson).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -1,80 +1,84 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
getGroupEssenceMsgAll,
|
||||
type GroupEssenceMsgRet,
|
||||
getGroupEssenceMsgAll,
|
||||
type GroupEssenceMsgRet,
|
||||
} from '@snowluma/protocol/web/group-essence';
|
||||
import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
|
||||
const cookie = { skey: 'test-skey' };
|
||||
|
||||
function page(isEnd: boolean): GroupEssenceMsgRet {
|
||||
return {
|
||||
retcode: 0,
|
||||
data: {
|
||||
is_end: isEnd,
|
||||
msg_list: [],
|
||||
},
|
||||
};
|
||||
return {
|
||||
retcode: 0,
|
||||
data: {
|
||||
is_end: isEnd,
|
||||
msg_list: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('group essence pagination', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('rejects instead of returning a partial list when a later page fails', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockResolvedValueOnce(page(false) as never)
|
||||
.mockRejectedValueOnce(new Error('socket closed'));
|
||||
it('rejects instead of returning a partial list when a later page fails', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockResolvedValueOnce(page(false) as never)
|
||||
.mockRejectedValueOnce(new Error('socket closed'));
|
||||
|
||||
await expect(getGroupEssenceMsgAll(cookie, '123456789'))
|
||||
.rejects.toThrow('socket closed');
|
||||
});
|
||||
await expect(getGroupEssenceMsgAll(cookie, '123456789')).rejects.toThrow('socket closed');
|
||||
});
|
||||
|
||||
it('surfaces a non-zero QQ response code', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retcode: 100,
|
||||
retmsg: 'permission denied',
|
||||
data: {
|
||||
is_end: true,
|
||||
msg_list: [],
|
||||
},
|
||||
} satisfies GroupEssenceMsgRet as never);
|
||||
it('surfaces a non-zero QQ response code', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retcode: 100,
|
||||
retmsg: 'permission denied',
|
||||
data: {
|
||||
is_end: true,
|
||||
msg_list: [],
|
||||
},
|
||||
} satisfies GroupEssenceMsgRet as never);
|
||||
|
||||
await expect(getGroupEssenceMsgAll(cookie, '123456789'))
|
||||
.rejects.toThrow(/retcode 100.*permission denied/);
|
||||
});
|
||||
await expect(getGroupEssenceMsgAll(cookie, '123456789')).rejects.toThrow(
|
||||
/retcode 100.*permission denied/,
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an omitted list', { is_end: true }],
|
||||
['a null list', { is_end: true, msg_list: null }],
|
||||
])('normalizes an ended success response with %s to an empty page', async (_case, data) => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retcode: 0,
|
||||
data,
|
||||
} as never);
|
||||
it.each([
|
||||
['an omitted list', { is_end: true }],
|
||||
['a null list', { is_end: true, msg_list: null }],
|
||||
])('normalizes an ended success response with %s to an empty page', async (_case, data) => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retcode: 0,
|
||||
data,
|
||||
} as never);
|
||||
|
||||
await expect(getGroupEssenceMsgAll(cookie, '123456789')).resolves.toEqual([{
|
||||
retcode: 0,
|
||||
data: { is_end: true, msg_list: [] },
|
||||
}]);
|
||||
expect(request).toHaveBeenCalledOnce();
|
||||
});
|
||||
await expect(getGroupEssenceMsgAll(cookie, '123456789')).resolves.toEqual([
|
||||
{
|
||||
retcode: 0,
|
||||
data: { is_end: true, msg_list: [] },
|
||||
},
|
||||
]);
|
||||
expect(request).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('rejects a missing message list before the response explicitly ends', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retcode: 0,
|
||||
data: { is_end: false },
|
||||
} as never);
|
||||
it('rejects a missing message list before the response explicitly ends', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retcode: 0,
|
||||
data: { is_end: false },
|
||||
} as never);
|
||||
|
||||
await expect(getGroupEssenceMsgAll(cookie, '123456789'))
|
||||
.rejects.toThrow(/invalid group essence response.*msg_list/);
|
||||
});
|
||||
await expect(getGroupEssenceMsgAll(cookie, '123456789')).rejects.toThrow(
|
||||
/invalid group essence response.*msg_list/,
|
||||
);
|
||||
});
|
||||
|
||||
it('fails when the configured page limit cannot reach the end', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue(page(false) as never);
|
||||
it('fails when the configured page limit cannot reach the end', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue(page(false) as never);
|
||||
|
||||
await expect(getGroupEssenceMsgAll(cookie, '123456789'))
|
||||
.rejects.toThrow(/pagination exceeded 20 pages/);
|
||||
});
|
||||
await expect(getGroupEssenceMsgAll(cookie, '123456789')).rejects.toThrow(
|
||||
/pagination exceeded 20 pages/,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,157 +1,178 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||
calculateBkn,
|
||||
getGroupNoticeWebAPI,
|
||||
groupNoticeImageUrl,
|
||||
parseGroupNoticeImageUploadResponse,
|
||||
resolveGroupNoticeOptions,
|
||||
setGroupNoticeWebAPI,
|
||||
type WebApiGroupNoticeRet,
|
||||
GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||
calculateBkn,
|
||||
getGroupNoticeWebAPI,
|
||||
groupNoticeImageUrl,
|
||||
parseGroupNoticeImageUploadResponse,
|
||||
resolveGroupNoticeOptions,
|
||||
setGroupNoticeWebAPI,
|
||||
type WebApiGroupNoticeRet,
|
||||
} from '@snowluma/protocol/web/group-notice';
|
||||
import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
|
||||
describe('group-notice / publish HTTP layer', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
const cookies = { skey: 'BODY_KEY', p_skey: 'URL_KEY', uin: 'o10000' };
|
||||
const cookies = { skey: 'BODY_KEY', p_skey: 'URL_KEY', uin: 'o10000' };
|
||||
|
||||
it('publishes a regular announcement with the exact options and image metadata', async () => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ ec: 0 } as never);
|
||||
it('publishes a regular announcement with the exact options and image metadata', async () => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ ec: 0 } as never);
|
||||
|
||||
await setGroupNoticeWebAPI(cookies, '12345', 'regular notice', {
|
||||
pinned: 1,
|
||||
isShowEditCard: 0,
|
||||
tipWindowType: 0,
|
||||
confirmRequired: 0,
|
||||
picId: 'pic-id',
|
||||
imgWidth: 640,
|
||||
imgHeight: 360,
|
||||
await setGroupNoticeWebAPI(cookies, '12345', 'regular notice', {
|
||||
pinned: 1,
|
||||
isShowEditCard: 0,
|
||||
tipWindowType: 0,
|
||||
confirmRequired: 0,
|
||||
picId: 'pic-id',
|
||||
imgWidth: 640,
|
||||
imgHeight: 360,
|
||||
});
|
||||
|
||||
const [url, method, rawBody, headers, isJsonRet, isArgJson] = request.mock.calls[0]!;
|
||||
expect(url).toBe(
|
||||
`https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${calculateBkn('URL_KEY')}`,
|
||||
);
|
||||
expect(method).toBe('POST');
|
||||
const body = new URLSearchParams(rawBody as string);
|
||||
expect(Object.fromEntries(body)).toMatchObject({
|
||||
qid: '12345',
|
||||
bkn: calculateBkn('BODY_KEY'),
|
||||
text: 'regular notice',
|
||||
pinned: '1',
|
||||
type: '1',
|
||||
pic: 'pic-id',
|
||||
imgWidth: '640',
|
||||
imgHeight: '360',
|
||||
});
|
||||
expect(JSON.parse(body.get('settings')!)).toEqual({
|
||||
is_show_edit_card: 0,
|
||||
tip_window_type: 0,
|
||||
confirm_required: 0,
|
||||
});
|
||||
expect(headers).toMatchObject({ 'Content-Type': 'application/x-www-form-urlencoded' });
|
||||
expect(isJsonRet).toBe(true);
|
||||
expect(isArgJson).toBe(false);
|
||||
});
|
||||
|
||||
const [url, method, rawBody, headers, isJsonRet, isArgJson] = request.mock.calls[0]!;
|
||||
expect(url).toBe(`https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${calculateBkn('URL_KEY')}`);
|
||||
expect(method).toBe('POST');
|
||||
const body = new URLSearchParams(rawBody as string);
|
||||
expect(Object.fromEntries(body)).toMatchObject({
|
||||
qid: '12345',
|
||||
bkn: calculateBkn('BODY_KEY'),
|
||||
text: 'regular notice',
|
||||
pinned: '1',
|
||||
type: '1',
|
||||
pic: 'pic-id',
|
||||
imgWidth: '640',
|
||||
imgHeight: '360',
|
||||
it('routes semantic new-member announcements to the instruction endpoint with type 20', async () => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ ec: 0 } as never);
|
||||
|
||||
await setGroupNoticeWebAPI(cookies, '12345', 'welcome', { sendToNewMembers: true });
|
||||
|
||||
const [url, , rawBody] = request.mock.calls[0]!;
|
||||
expect(url).toContain('/cgi-bin/announce/add_qun_instruction?');
|
||||
expect(new URLSearchParams(rawBody as string).get('type')).toBe(
|
||||
String(GROUP_NOTICE_TYPE_NEW_MEMBERS),
|
||||
);
|
||||
});
|
||||
expect(JSON.parse(body.get('settings')!)).toEqual({
|
||||
is_show_edit_card: 0,
|
||||
tip_window_type: 0,
|
||||
confirm_required: 0,
|
||||
|
||||
it('keeps raw type=20 compatibility while selecting the correct endpoint', async () => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ ec: 0 } as never);
|
||||
|
||||
await setGroupNoticeWebAPI(cookies, '12345', 'welcome', { type: 20 });
|
||||
|
||||
expect(request.mock.calls[0]![0]).toContain('/cgi-bin/announce/add_qun_instruction?');
|
||||
});
|
||||
expect(headers).toMatchObject({ 'Content-Type': 'application/x-www-form-urlencoded' });
|
||||
expect(isJsonRet).toBe(true);
|
||||
expect(isArgJson).toBe(false);
|
||||
});
|
||||
|
||||
it('routes semantic new-member announcements to the instruction endpoint with type 20', async () => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ ec: 0 } as never);
|
||||
it('fails before I/O when raw type and semantic target conflict', async () => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson');
|
||||
|
||||
await setGroupNoticeWebAPI(cookies, '12345', 'welcome', { sendToNewMembers: true });
|
||||
|
||||
const [url, , rawBody] = request.mock.calls[0]!;
|
||||
expect(url).toContain('/cgi-bin/announce/add_qun_instruction?');
|
||||
expect(new URLSearchParams(rawBody as string).get('type')).toBe(String(GROUP_NOTICE_TYPE_NEW_MEMBERS));
|
||||
});
|
||||
|
||||
it('keeps raw type=20 compatibility while selecting the correct endpoint', async () => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ ec: 0 } as never);
|
||||
|
||||
await setGroupNoticeWebAPI(cookies, '12345', 'welcome', { type: 20 });
|
||||
|
||||
expect(request.mock.calls[0]![0]).toContain('/cgi-bin/announce/add_qun_instruction?');
|
||||
});
|
||||
|
||||
it('fails before I/O when raw type and semantic target conflict', async () => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson');
|
||||
|
||||
await expect(setGroupNoticeWebAPI(cookies, '12345', 'bad', {
|
||||
type: 1,
|
||||
sendToNewMembers: true,
|
||||
})).rejects.toThrow('conflicts');
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects unsupported raw types and non-binary options', () => {
|
||||
expect(() => resolveGroupNoticeOptions({ type: 6 })).toThrow('type must be 1');
|
||||
expect(() => resolveGroupNoticeOptions({ pinned: 2 })).toThrow('pinned must be 0 or 1');
|
||||
expect(() => resolveGroupNoticeOptions({ tipWindowType: -1 })).toThrow('tipWindowType must be 0 or 1');
|
||||
});
|
||||
|
||||
it('preserves the established regular-announcement defaults', () => {
|
||||
expect(resolveGroupNoticeOptions()).toMatchObject({
|
||||
pinned: 0,
|
||||
type: 1,
|
||||
sendToNewMembers: false,
|
||||
isShowEditCard: 1,
|
||||
tipWindowType: 1,
|
||||
confirmRequired: 1,
|
||||
await expect(
|
||||
setGroupNoticeWebAPI(cookies, '12345', 'bad', {
|
||||
type: 1,
|
||||
sendToNewMembers: true,
|
||||
}),
|
||||
).rejects.toThrow('conflicts');
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('propagates transport failures instead of returning undefined', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockRejectedValue(new Error('Unexpected status code: 403'));
|
||||
await expect(setGroupNoticeWebAPI(cookies, '12345', 'notice')).rejects.toThrow('403');
|
||||
});
|
||||
it('rejects unsupported raw types and non-binary options', () => {
|
||||
expect(() => resolveGroupNoticeOptions({ type: 6 })).toThrow('type must be 1');
|
||||
expect(() => resolveGroupNoticeOptions({ pinned: 2 })).toThrow('pinned must be 0 or 1');
|
||||
expect(() => resolveGroupNoticeOptions({ tipWindowType: -1 })).toThrow(
|
||||
'tipWindowType must be 0 or 1',
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves the established regular-announcement defaults', () => {
|
||||
expect(resolveGroupNoticeOptions()).toMatchObject({
|
||||
pinned: 0,
|
||||
type: 1,
|
||||
sendToNewMembers: false,
|
||||
isShowEditCard: 1,
|
||||
tipWindowType: 1,
|
||||
confirmRequired: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('propagates transport failures instead of returning undefined', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockRejectedValue(
|
||||
new Error('Unexpected status code: 403'),
|
||||
);
|
||||
await expect(setGroupNoticeWebAPI(cookies, '12345', 'notice')).rejects.toThrow('403');
|
||||
});
|
||||
});
|
||||
|
||||
describe('group-notice / image download url', () => {
|
||||
it('builds the public CDN url from a picture id', () => {
|
||||
expect(groupNoticeImageUrl('pic-1')).toBe('https://gdynamic.qpic.cn/gdynamic/pic-1/0');
|
||||
});
|
||||
it('builds the public CDN url from a picture id', () => {
|
||||
expect(groupNoticeImageUrl('pic-1')).toBe('https://gdynamic.qpic.cn/gdynamic/pic-1/0');
|
||||
});
|
||||
|
||||
it('rejects empty or path-like ids', () => {
|
||||
expect(() => groupNoticeImageUrl('')).toThrow('empty');
|
||||
expect(() => groupNoticeImageUrl(' ')).toThrow('empty');
|
||||
expect(() => groupNoticeImageUrl('a/b')).toThrow('malformed');
|
||||
expect(() => groupNoticeImageUrl('a?x=1')).toThrow('malformed');
|
||||
});
|
||||
it('rejects empty or path-like ids', () => {
|
||||
expect(() => groupNoticeImageUrl('')).toThrow('empty');
|
||||
expect(() => groupNoticeImageUrl(' ')).toThrow('empty');
|
||||
expect(() => groupNoticeImageUrl('a/b')).toThrow('malformed');
|
||||
expect(() => groupNoticeImageUrl('a?x=1')).toThrow('malformed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('group-notice / image upload response', () => {
|
||||
it('parses HTML-escaped image metadata', () => {
|
||||
expect(parseGroupNoticeImageUploadResponse(JSON.stringify({
|
||||
ec: 0,
|
||||
id: '{"id":"pic-1","w":"640","h":"360"}',
|
||||
}))).toEqual({ id: 'pic-1', width: 640, height: 360 });
|
||||
});
|
||||
it('parses HTML-escaped image metadata', () => {
|
||||
expect(
|
||||
parseGroupNoticeImageUploadResponse(
|
||||
JSON.stringify({
|
||||
ec: 0,
|
||||
id: '{"id":"pic-1","w":"640","h":"360"}',
|
||||
}),
|
||||
),
|
||||
).toEqual({ id: 'pic-1', width: 640, height: 360 });
|
||||
});
|
||||
|
||||
it('surfaces server and malformed-response failures', () => {
|
||||
expect(() => parseGroupNoticeImageUploadResponse(JSON.stringify({ ec: 14, em: 'denied' }))).toThrow('ec=14 em=denied');
|
||||
expect(() => parseGroupNoticeImageUploadResponse('not json')).toThrow('invalid JSON');
|
||||
expect(() => parseGroupNoticeImageUploadResponse(JSON.stringify({ ec: 0, id: '{"id":"pic","w":0,"h":10}' })))
|
||||
.toThrow('malformed image metadata');
|
||||
});
|
||||
it('surfaces server and malformed-response failures', () => {
|
||||
expect(() =>
|
||||
parseGroupNoticeImageUploadResponse(JSON.stringify({ ec: 14, em: 'denied' })),
|
||||
).toThrow('ec=14 em=denied');
|
||||
expect(() => parseGroupNoticeImageUploadResponse('not json')).toThrow('invalid JSON');
|
||||
expect(() =>
|
||||
parseGroupNoticeImageUploadResponse(
|
||||
JSON.stringify({ ec: 0, id: '{"id":"pic","w":0,"h":10}' }),
|
||||
),
|
||||
).toThrow('malformed image metadata');
|
||||
});
|
||||
});
|
||||
|
||||
describe('group-notice / list HTTP layer', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('requests both regular and new-member collections and preserves server errors', async () => {
|
||||
const response: WebApiGroupNoticeRet = { ec: 14, em: 'permission denied' };
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue(response as never);
|
||||
it('requests both regular and new-member collections and preserves server errors', async () => {
|
||||
const response: WebApiGroupNoticeRet = { ec: 14, em: 'permission denied' };
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue(response as never);
|
||||
|
||||
await expect(getGroupNoticeWebAPI({ skey: 'SK', p_skey: 'PSK' }, '9876')).resolves.toBe(response);
|
||||
await expect(getGroupNoticeWebAPI({ skey: 'SK', p_skey: 'PSK' }, '9876')).resolves.toBe(
|
||||
response,
|
||||
);
|
||||
|
||||
const [url, method, rawBody] = request.mock.calls[0]!;
|
||||
expect(url).toContain('/cgi-bin/announce/list_announce?');
|
||||
expect(method).toBe('POST');
|
||||
const body = new URLSearchParams(rawBody as string);
|
||||
expect(body.get('i')).toBe('1');
|
||||
expect(body.get('ni')).toBe('1');
|
||||
});
|
||||
const [url, method, rawBody] = request.mock.calls[0]!;
|
||||
expect(url).toContain('/cgi-bin/announce/list_announce?');
|
||||
expect(method).toBe('POST');
|
||||
const body = new URLSearchParams(rawBody as string);
|
||||
expect(body.get('i')).toBe('1');
|
||||
expect(body.get('ni')).toBe('1');
|
||||
});
|
||||
|
||||
it('propagates transport failures instead of hiding them as an empty list', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockRejectedValue(new Error('socket closed'));
|
||||
await expect(getGroupNoticeWebAPI({ skey: 'SK' }, '9876')).rejects.toThrow('socket closed');
|
||||
});
|
||||
it('propagates transport failures instead of hiding them as an empty list', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockRejectedValue(new Error('socket closed'));
|
||||
await expect(getGroupNoticeWebAPI({ skey: 'SK' }, '9876')).rejects.toThrow('socket closed');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,10 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { getDaySignedListWebAPI, mapDaySignedList, type DaySignedInfo, type DaySignedListResponse } from '@snowluma/protocol/web/group-signin';
|
||||
import {
|
||||
getDaySignedListWebAPI,
|
||||
mapDaySignedList,
|
||||
type DaySignedInfo,
|
||||
type DaySignedListResponse,
|
||||
} from '@snowluma/protocol/web/group-signin';
|
||||
import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
|
||||
// The signed-in list comes back from qun.qq.com's GetDaySignedList trpc
|
||||
@@ -9,65 +14,119 @@ import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
// HTTP port and a silent off-by-one would be invisible end-to-end.
|
||||
|
||||
function resp(infos: DaySignedInfo[]): DaySignedListResponse {
|
||||
return { retCode: 0, response: { page: [{ infos, offset: 0, total: infos.length }] }, funcCode: 0 };
|
||||
return {
|
||||
retCode: 0,
|
||||
response: { page: [{ infos, offset: 0, total: infos.length }] },
|
||||
funcCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
describe('group-signin / mapDaySignedList', () => {
|
||||
it('renames fields and de-skews signInRank', () => {
|
||||
const out = mapDaySignedList(resp([
|
||||
{ uid: '10001', uidGroupNick: 'Alice', signedTimeStamp: '1700000000', signInRank: 1 },
|
||||
{ uid: '10002', uidGroupNick: 'Bob', signedTimeStamp: '1700000050', signInRank: 3 },
|
||||
{ uid: '10003', uidGroupNick: 'Carol', signedTimeStamp: '1700000100', signInRank: 5 },
|
||||
]));
|
||||
expect(out).toEqual([
|
||||
{ user_id: 10001, nick: 'Alice', time: 1700000000, rank: 1 },
|
||||
{ user_id: 10002, nick: 'Bob', time: 1700000050, rank: 2 },
|
||||
{ user_id: 10003, nick: 'Carol', time: 1700000100, rank: 3 },
|
||||
]);
|
||||
});
|
||||
it('renames fields and de-skews signInRank', () => {
|
||||
const out = mapDaySignedList(
|
||||
resp([
|
||||
{
|
||||
uid: '10001',
|
||||
uidGroupNick: 'Alice',
|
||||
signedTimeStamp: '1700000000',
|
||||
signInRank: 1,
|
||||
},
|
||||
{ uid: '10002', uidGroupNick: 'Bob', signedTimeStamp: '1700000050', signInRank: 3 },
|
||||
{
|
||||
uid: '10003',
|
||||
uidGroupNick: 'Carol',
|
||||
signedTimeStamp: '1700000100',
|
||||
signInRank: 5,
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(out).toEqual([
|
||||
{ user_id: 10001, nick: 'Alice', time: 1700000000, rank: 1 },
|
||||
{ user_id: 10002, nick: 'Bob', time: 1700000050, rank: 2 },
|
||||
{ user_id: 10003, nick: 'Carol', time: 1700000100, rank: 3 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns [] when infos is empty', () => {
|
||||
expect(mapDaySignedList(resp([]))).toEqual([]);
|
||||
});
|
||||
it('returns [] when infos is empty', () => {
|
||||
expect(mapDaySignedList(resp([]))).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns [] when page is missing entirely', () => {
|
||||
expect(mapDaySignedList({ retCode: 0, response: {}, funcCode: 0 })).toEqual([]);
|
||||
});
|
||||
it('returns [] when page is missing entirely', () => {
|
||||
expect(mapDaySignedList({ retCode: 0, response: {}, funcCode: 0 })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('group-signin / getDaySignedListWebAPI (HTTP layer)', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
const cookies = { p_skey: 'PSK', skey: 'SK', uin: 'o10000', p_uin: 'o10000' };
|
||||
// g_tk = djb2-31bit over p_skey 'PSK'
|
||||
const expectedGtk = (() => { let h = 5381; for (const c of 'PSK') h += (h << 5) + c.charCodeAt(0); return (h & 0x7FFFFFFF).toString(); })();
|
||||
const cookies = { p_skey: 'PSK', skey: 'SK', uin: 'o10000', p_uin: 'o10000' };
|
||||
// g_tk = djb2-31bit over p_skey 'PSK'
|
||||
const expectedGtk = (() => {
|
||||
let h = 5381;
|
||||
|
||||
it('POSTs the exact url + json body and maps the result', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retCode: 0, funcCode: 0,
|
||||
response: { page: [{ infos: [{ uid: '777', uidGroupNick: 'Z', signedTimeStamp: '1700000000', signInRank: 3 }], offset: 0, total: 1 }] },
|
||||
} satisfies DaySignedListResponse as never);
|
||||
for (const c of 'PSK') {
|
||||
h += (h << 5) + c.charCodeAt(0);
|
||||
}
|
||||
|
||||
const out = await getDaySignedListWebAPI(cookies, '54321', '10000', new Date(2026, 0, 2));
|
||||
return (h & 0x7fffffff).toString();
|
||||
})();
|
||||
|
||||
expect(out).toEqual([{ user_id: 777, nick: 'Z', time: 1700000000, rank: 2 }]);
|
||||
const [url, method, body, headers, isJsonRet, isArgJson] = spy.mock.calls[0]!;
|
||||
expect(url).toBe(`https://qun.qq.com/v2/signin/trpc/GetDaySignedList?g_tk=${expectedGtk}`);
|
||||
expect(method).toBe('POST');
|
||||
expect(body).toEqual({ dayYmd: '20260102', offset: 0, limit: 100, uid: '10000', groupId: '54321' });
|
||||
expect((headers as Record<string, string>)['Content-Type']).toBe('application/json');
|
||||
expect((headers as Record<string, string>).Cookie).toContain('p_skey=PSK');
|
||||
expect(isJsonRet).toBe(true);
|
||||
expect(isArgJson).toBe(true);
|
||||
});
|
||||
it('POSTs the exact url + json body and maps the result', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retCode: 0,
|
||||
funcCode: 0,
|
||||
response: {
|
||||
page: [
|
||||
{
|
||||
infos: [
|
||||
{
|
||||
uid: '777',
|
||||
uidGroupNick: 'Z',
|
||||
signedTimeStamp: '1700000000',
|
||||
signInRank: 3,
|
||||
},
|
||||
],
|
||||
offset: 0,
|
||||
total: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
} satisfies DaySignedListResponse as never);
|
||||
|
||||
it('propagates a transport error instead of swallowing it to []', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockRejectedValue(new Error('Unexpected status code: 403'));
|
||||
await expect(getDaySignedListWebAPI(cookies, '1', '1')).rejects.toThrow('403');
|
||||
});
|
||||
const out = await getDaySignedListWebAPI(cookies, '54321', '10000', new Date(2026, 0, 2));
|
||||
|
||||
it('throws when the response has no page (auth/cookie failure), not []', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ retCode: 0, funcCode: 0, response: {} } satisfies DaySignedListResponse as never);
|
||||
await expect(getDaySignedListWebAPI(cookies, '1', '1')).rejects.toThrow('无法获取该群组打卡列表');
|
||||
});
|
||||
expect(out).toEqual([{ user_id: 777, nick: 'Z', time: 1700000000, rank: 2 }]);
|
||||
const [url, method, body, headers, isJsonRet, isArgJson] = spy.mock.calls[0]!;
|
||||
expect(url).toBe(`https://qun.qq.com/v2/signin/trpc/GetDaySignedList?g_tk=${expectedGtk}`);
|
||||
expect(method).toBe('POST');
|
||||
expect(body).toEqual({
|
||||
dayYmd: '20260102',
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
uid: '10000',
|
||||
groupId: '54321',
|
||||
});
|
||||
expect((headers as Record<string, string>)['Content-Type']).toBe('application/json');
|
||||
expect((headers as Record<string, string>).Cookie).toContain('p_skey=PSK');
|
||||
expect(isJsonRet).toBe(true);
|
||||
expect(isArgJson).toBe(true);
|
||||
});
|
||||
|
||||
it('propagates a transport error instead of swallowing it to []', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockRejectedValue(
|
||||
new Error('Unexpected status code: 403'),
|
||||
);
|
||||
await expect(getDaySignedListWebAPI(cookies, '1', '1')).rejects.toThrow('403');
|
||||
});
|
||||
|
||||
it('throws when the response has no page (auth/cookie failure), not []', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retCode: 0,
|
||||
funcCode: 0,
|
||||
response: {},
|
||||
} satisfies DaySignedListResponse as never);
|
||||
await expect(getDaySignedListWebAPI(cookies, '1', '1')).rejects.toThrow(
|
||||
'无法获取该群组打卡列表',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -7,67 +7,69 @@ import { mapFeeds, parseQzoneCallback } from '@snowluma/protocol/web/qzone';
|
||||
// is a JS object literal (unquoted keys, single-quoted strings, \xNN escapes,
|
||||
// trailing `undefined`) — JSON.parse throws on it; parseQzoneCallback must not.
|
||||
const SAMPLE = readFileSync(
|
||||
fileURLToPath(new URL('./fixtures/qzone-feeds-sample.jsonp', import.meta.url)),
|
||||
'utf8',
|
||||
fileURLToPath(new URL('./fixtures/qzone-feeds-sample.jsonp', import.meta.url)),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
interface RawFeeds {
|
||||
code?: number;
|
||||
data?: { data?: unknown[]; hasmore?: number | string };
|
||||
code?: number;
|
||||
data?: { data?: unknown[]; hasmore?: number | string };
|
||||
}
|
||||
|
||||
describe('qzone feeds JS-literal parsing (issue #182)', () => {
|
||||
it('JSON.parse chokes on the real body (regression baseline)', () => {
|
||||
const inner = SAMPLE.slice(SAMPLE.indexOf('{'), SAMPLE.lastIndexOf('}') + 1);
|
||||
expect(() => JSON.parse(inner)).toThrow();
|
||||
});
|
||||
it('JSON.parse chokes on the real body (regression baseline)', () => {
|
||||
const inner = SAMPLE.slice(SAMPLE.indexOf('{'), SAMPLE.lastIndexOf('}') + 1);
|
||||
expect(() => JSON.parse(inner)).toThrow();
|
||||
});
|
||||
|
||||
it('parseQzoneCallback evaluates the JS-literal payload', () => {
|
||||
const data = parseQzoneCallback<RawFeeds>(SAMPLE);
|
||||
expect(data.code).toBe(0);
|
||||
expect(Array.isArray(data.data?.data)).toBe(true);
|
||||
// The array carries a trailing `undefined` hole alongside the real feed.
|
||||
expect(data.data!.data!.length).toBe(2);
|
||||
expect(data.data!.data!.some((x) => x === undefined)).toBe(true);
|
||||
});
|
||||
it('parseQzoneCallback evaluates the JS-literal payload', () => {
|
||||
const data = parseQzoneCallback<RawFeeds>(SAMPLE);
|
||||
expect(data.code).toBe(0);
|
||||
expect(Array.isArray(data.data?.data)).toBe(true);
|
||||
// The array carries a trailing `undefined` hole alongside the real feed.
|
||||
expect(data.data!.data!.length).toBe(2);
|
||||
expect(data.data!.data!.some((x) => x === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it('mapFeeds drops the undefined hole and normalises the feed', () => {
|
||||
const data = parseQzoneCallback(SAMPLE);
|
||||
const result = mapFeeds(data as any);
|
||||
expect(result.feeds).toHaveLength(1);
|
||||
const f = result.feeds[0]!;
|
||||
expect(f.uin).toBe(20050606);
|
||||
expect(f.nickname).toBe('官方Qzone');
|
||||
expect(f.appid).toBe(311);
|
||||
expect(f.time).toBe(1780711209);
|
||||
expect(f.key).toBe('aef23101297f236ae4f10600');
|
||||
// \xNN escapes decoded by the JS eval, html passed through verbatim.
|
||||
expect(f.html).toContain('<li class="f-single f-s-s"');
|
||||
expect(f.html).toContain('官方Qzone');
|
||||
});
|
||||
it('mapFeeds drops the undefined hole and normalises the feed', () => {
|
||||
const data = parseQzoneCallback(SAMPLE);
|
||||
const result = mapFeeds(data as any);
|
||||
expect(result.feeds).toHaveLength(1);
|
||||
const f = result.feeds[0]!;
|
||||
expect(f.uin).toBe(20050606);
|
||||
expect(f.nickname).toBe('官方Qzone');
|
||||
expect(f.appid).toBe(311);
|
||||
expect(f.time).toBe(1780711209);
|
||||
expect(f.key).toBe('aef23101297f236ae4f10600');
|
||||
// \xNN escapes decoded by the JS eval, html passed through verbatim.
|
||||
expect(f.html).toContain('<li class="f-single f-s-s"');
|
||||
expect(f.html).toContain('官方Qzone');
|
||||
});
|
||||
|
||||
it('parses as inert data — never resolves identifiers or executes code', () => {
|
||||
// The parser has no notion of globals, member access, or calls: any such
|
||||
// token is rejected, so a tampered body cannot reach `process`/`Function`
|
||||
// etc. (the whole reason we do NOT eval this payload).
|
||||
expect(() => parseQzoneCallback('_preloadCallback({x: process})')).toThrow();
|
||||
expect(() => parseQzoneCallback('_preloadCallback({x: callback.constructor})')).toThrow();
|
||||
expect(() => parseQzoneCallback('_preloadCallback({x: (function(){return 1})()})')).toThrow();
|
||||
expect(() => parseQzoneCallback('_preloadCallback(eval("1+1"))')).toThrow();
|
||||
});
|
||||
it('parses as inert data — never resolves identifiers or executes code', () => {
|
||||
// The parser has no notion of globals, member access, or calls: any such
|
||||
// token is rejected, so a tampered body cannot reach `process`/`Function`
|
||||
// etc. (the whole reason we do NOT eval this payload).
|
||||
expect(() => parseQzoneCallback('_preloadCallback({x: process})')).toThrow();
|
||||
expect(() => parseQzoneCallback('_preloadCallback({x: callback.constructor})')).toThrow();
|
||||
expect(() =>
|
||||
parseQzoneCallback('_preloadCallback({x: (function(){return 1})()})'),
|
||||
).toThrow();
|
||||
expect(() => parseQzoneCallback('_preloadCallback(eval("1+1"))')).toThrow();
|
||||
});
|
||||
|
||||
it('does not pollute Object.prototype via a __proto__ key', () => {
|
||||
parseQzoneCallback('_preloadCallback({"__proto__":{"polluted":1},"code":0})');
|
||||
expect(({} as any).polluted).toBeUndefined();
|
||||
});
|
||||
it('does not pollute Object.prototype via a __proto__ key', () => {
|
||||
parseQzoneCallback('_preloadCallback({"__proto__":{"polluted":1},"code":0})');
|
||||
expect(({} as any).polluted).toBeUndefined();
|
||||
});
|
||||
|
||||
it('decodes JS string escapes (\\xNN, \\/) literally, not as markup', () => {
|
||||
const d = parseQzoneCallback<{ s?: string }>("_preloadCallback({s:'\\x3Cb\\x3E&\\/x'})");
|
||||
expect(d.s).toBe('<b>&/x');
|
||||
});
|
||||
it('decodes JS string escapes (\\xNN, \\/) literally, not as markup', () => {
|
||||
const d = parseQzoneCallback<{ s?: string }>("_preloadCallback({s:'\\x3Cb\\x3E&\\/x'})");
|
||||
expect(d.s).toBe('<b>&/x');
|
||||
});
|
||||
|
||||
it('rejects a body that captures no object', () => {
|
||||
expect(() => parseQzoneCallback('_preloadCallback(42)')).toThrow('invalid feeds response');
|
||||
expect(() => parseQzoneCallback('void 0')).toThrow('invalid feeds response');
|
||||
});
|
||||
it('rejects a body that captures no object', () => {
|
||||
expect(() => parseQzoneCallback('_preloadCallback(42)')).toThrow('invalid feeds response');
|
||||
expect(() => parseQzoneCallback('void 0')).toThrow('invalid feeds response');
|
||||
});
|
||||
});
|
||||
@@ -11,133 +11,138 @@ import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
const cookies = { p_skey: 'PSK', skey: 'SK', uin: 'o10000', p_uin: 'o10000' };
|
||||
|
||||
describe('qzone / buildQzoneUpdatePayload', () => {
|
||||
it('rebuilds a text-only payload with ugcright_id defaulting to tid', () => {
|
||||
const body = buildQzoneUpdatePayload(
|
||||
{ tid: 'T1', uin: 10000, content: 'hello', ugc_right: 1 },
|
||||
'10000',
|
||||
);
|
||||
expect(body.get('tid')).toBe('T1');
|
||||
expect(body.get('con')).toBe('hello');
|
||||
expect(body.get('richtype')).toBe('');
|
||||
expect(body.get('richval')).toBe('');
|
||||
expect(body.get('pic_bo')).toBe('');
|
||||
expect(body.get('ugcright_id')).toBe('T1');
|
||||
expect(body.get('hostuin')).toBe('10000');
|
||||
expect(body.get('format')).toBe('fs');
|
||||
});
|
||||
it('rebuilds a text-only payload with ugcright_id defaulting to tid', () => {
|
||||
const body = buildQzoneUpdatePayload(
|
||||
{ tid: 'T1', uin: 10000, content: 'hello', ugc_right: 1 },
|
||||
'10000',
|
||||
);
|
||||
expect(body.get('tid')).toBe('T1');
|
||||
expect(body.get('con')).toBe('hello');
|
||||
expect(body.get('richtype')).toBe('');
|
||||
expect(body.get('richval')).toBe('');
|
||||
expect(body.get('pic_bo')).toBe('');
|
||||
expect(body.get('ugcright_id')).toBe('T1');
|
||||
expect(body.get('hostuin')).toBe('10000');
|
||||
expect(body.get('format')).toBe('fs');
|
||||
});
|
||||
|
||||
it('rebuilds richval from pic_id and pic_bo from the bo= query param', () => {
|
||||
const body = buildQzoneUpdatePayload(
|
||||
{
|
||||
tid: 'T2',
|
||||
uin: 10000,
|
||||
content: 'pics',
|
||||
conlist: [{ con: 'pi' }, { con: 'cs' }],
|
||||
richtype: 1,
|
||||
pic: [
|
||||
{
|
||||
pic_id: 'X,ALBUM1,LLOC1,extra',
|
||||
pictype: 22,
|
||||
height: 800,
|
||||
width: 600,
|
||||
url1: 'https://photo.example/a.jpg?bo=abc%2Cdef&x=1',
|
||||
},
|
||||
],
|
||||
},
|
||||
'10000',
|
||||
);
|
||||
expect(body.get('con')).toBe('pics');
|
||||
expect(body.get('richtype')).toBe('1');
|
||||
expect(body.get('richval')).toBe(',ALBUM1,LLOC1,LLOC1,22,800,600,,0,0');
|
||||
expect(body.get('pic_bo')).toBe('abc,def\tabc,def');
|
||||
});
|
||||
it('rebuilds richval from pic_id and pic_bo from the bo= query param', () => {
|
||||
const body = buildQzoneUpdatePayload(
|
||||
{
|
||||
tid: 'T2',
|
||||
uin: 10000,
|
||||
content: 'pics',
|
||||
conlist: [{ con: 'pi' }, { con: 'cs' }],
|
||||
richtype: 1,
|
||||
pic: [
|
||||
{
|
||||
pic_id: 'X,ALBUM1,LLOC1,extra',
|
||||
pictype: 22,
|
||||
height: 800,
|
||||
width: 600,
|
||||
url1: 'https://photo.example/a.jpg?bo=abc%2Cdef&x=1',
|
||||
},
|
||||
],
|
||||
},
|
||||
'10000',
|
||||
);
|
||||
expect(body.get('con')).toBe('pics');
|
||||
expect(body.get('richtype')).toBe('1');
|
||||
expect(body.get('richval')).toBe(',ALBUM1,LLOC1,LLOC1,22,800,600,,0,0');
|
||||
expect(body.get('pic_bo')).toBe('abc,def\tabc,def');
|
||||
});
|
||||
|
||||
it('throws when an image post detail carries unusable pic info', () => {
|
||||
expect(() =>
|
||||
buildQzoneUpdatePayload({ tid: 'T3', richtype: 1, pic: [{ pic_id: 'broken' }] }, '10000'),
|
||||
).toThrow('unsupported pic info');
|
||||
expect(() => buildQzoneUpdatePayload({ tid: 'T3', richtype: 1, pic: [] }, '10000')).toThrow(
|
||||
'missing pic info',
|
||||
);
|
||||
});
|
||||
it('throws when an image post detail carries unusable pic info', () => {
|
||||
expect(() =>
|
||||
buildQzoneUpdatePayload(
|
||||
{ tid: 'T3', richtype: 1, pic: [{ pic_id: 'broken' }] },
|
||||
'10000',
|
||||
),
|
||||
).toThrow('unsupported pic info');
|
||||
expect(() => buildQzoneUpdatePayload({ tid: 'T3', richtype: 1, pic: [] }, '10000')).toThrow(
|
||||
'missing pic info',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when the detail has no tid', () => {
|
||||
expect(() => buildQzoneUpdatePayload({}, '10000')).toThrow('missing tid');
|
||||
});
|
||||
it('throws when the detail has no tid', () => {
|
||||
expect(() => buildQzoneUpdatePayload({}, '10000')).toThrow('missing tid');
|
||||
});
|
||||
});
|
||||
|
||||
describe('qzone / updateQzoneMsgRight (HTTP layer)', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
const detailBody =
|
||||
'_Callback({"code":0,"subcode":0,"tid":"T1","uin":10000,"content":"hello","ugc_right":1});';
|
||||
const detailBody =
|
||||
'_Callback({"code":0,"subcode":0,"tid":"T1","uin":10000,"content":"hello","ugc_right":1});';
|
||||
|
||||
it('GETs the detail then POSTs the rebuilt payload with the new ugc_right', async () => {
|
||||
const spy = vi
|
||||
.spyOn(RequestUtil, 'HttpGetText')
|
||||
.mockResolvedValueOnce(detailBody)
|
||||
.mockResolvedValueOnce('frameElement.callback({"code":0,"subcode":0,"ugc_right":64});');
|
||||
it('GETs the detail then POSTs the rebuilt payload with the new ugc_right', async () => {
|
||||
const spy = vi
|
||||
.spyOn(RequestUtil, 'HttpGetText')
|
||||
.mockResolvedValueOnce(detailBody)
|
||||
.mockResolvedValueOnce('frameElement.callback({"code":0,"subcode":0,"ugc_right":64});');
|
||||
|
||||
const out = await updateQzoneMsgRight(cookies, '10000', 'T1', 64);
|
||||
expect(out).toEqual({ ugc_right: 64 });
|
||||
const out = await updateQzoneMsgRight(cookies, '10000', 'T1', 64);
|
||||
expect(out).toEqual({ ugc_right: 64 });
|
||||
|
||||
const [detailUrl, detailMethod] = spy.mock.calls[0]!;
|
||||
expect(detailMethod).toBe('GET');
|
||||
expect(detailUrl).toContain(
|
||||
'https://h5.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msgdetail_v6?',
|
||||
);
|
||||
const dq = new URLSearchParams((detailUrl as string).split('?')[1]);
|
||||
expect(dq.get('tid')).toBe('T1');
|
||||
expect(dq.get('uin')).toBe('10000');
|
||||
const [detailUrl, detailMethod] = spy.mock.calls[0]!;
|
||||
expect(detailMethod).toBe('GET');
|
||||
expect(detailUrl).toContain(
|
||||
'https://h5.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msgdetail_v6?',
|
||||
);
|
||||
const dq = new URLSearchParams((detailUrl as string).split('?')[1]);
|
||||
expect(dq.get('tid')).toBe('T1');
|
||||
expect(dq.get('uin')).toBe('10000');
|
||||
|
||||
const [updateUrl, updateMethod, updateBody] = spy.mock.calls[1]!;
|
||||
expect(updateMethod).toBe('POST');
|
||||
expect(updateUrl).toContain(
|
||||
'https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_update?',
|
||||
);
|
||||
const uq = new URLSearchParams(updateBody as string);
|
||||
expect(uq.get('tid')).toBe('T1');
|
||||
expect(uq.get('con')).toBe('hello');
|
||||
expect(uq.get('ugc_right')).toBe('64');
|
||||
expect(uq.get('allow_uins')).toBeNull();
|
||||
});
|
||||
const [updateUrl, updateMethod, updateBody] = spy.mock.calls[1]!;
|
||||
expect(updateMethod).toBe('POST');
|
||||
expect(updateUrl).toContain(
|
||||
'https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_update?',
|
||||
);
|
||||
const uq = new URLSearchParams(updateBody as string);
|
||||
expect(uq.get('tid')).toBe('T1');
|
||||
expect(uq.get('con')).toBe('hello');
|
||||
expect(uq.get('ugc_right')).toBe('64');
|
||||
expect(uq.get('allow_uins')).toBeNull();
|
||||
});
|
||||
|
||||
it('sets allow_uins (deduped) for ugc_right 16 and requires it', async () => {
|
||||
const spy = vi
|
||||
.spyOn(RequestUtil, 'HttpGetText')
|
||||
.mockResolvedValueOnce(detailBody)
|
||||
.mockResolvedValueOnce('{"code":0,"subcode":0}');
|
||||
it('sets allow_uins (deduped) for ugc_right 16 and requires it', async () => {
|
||||
const spy = vi
|
||||
.spyOn(RequestUtil, 'HttpGetText')
|
||||
.mockResolvedValueOnce(detailBody)
|
||||
.mockResolvedValueOnce('{"code":0,"subcode":0}');
|
||||
|
||||
await updateQzoneMsgRight(cookies, '10000', 'T1', 16, '10001|10001|10002');
|
||||
const uq = new URLSearchParams(spy.mock.calls[1]![2] as string);
|
||||
expect(uq.get('ugc_right')).toBe('16');
|
||||
expect(uq.get('allow_uins')).toBe('10001|10002');
|
||||
await updateQzoneMsgRight(cookies, '10000', 'T1', 16, '10001|10001|10002');
|
||||
const uq = new URLSearchParams(spy.mock.calls[1]![2] as string);
|
||||
expect(uq.get('ugc_right')).toBe('16');
|
||||
expect(uq.get('allow_uins')).toBe('10001|10002');
|
||||
|
||||
await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 128)).rejects.toThrow(
|
||||
'target_uins is required',
|
||||
);
|
||||
});
|
||||
await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 128)).rejects.toThrow(
|
||||
'target_uins is required',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an invalid ugc_right before any request', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
|
||||
await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 2)).rejects.toThrow(
|
||||
'ugc_right must be one of',
|
||||
);
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects an invalid ugc_right before any request', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
|
||||
await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 2)).rejects.toThrow(
|
||||
'ugc_right must be one of',
|
||||
);
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws on a non-zero detail code and skips the update POST', async () => {
|
||||
const spy = vi
|
||||
.spyOn(RequestUtil, 'HttpGetText')
|
||||
.mockResolvedValueOnce('{"code":-3000,"subcode":-3000,"message":"need login"}');
|
||||
await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 64)).rejects.toThrow('code=-3000');
|
||||
expect(spy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('throws on a non-zero detail code and skips the update POST', async () => {
|
||||
const spy = vi
|
||||
.spyOn(RequestUtil, 'HttpGetText')
|
||||
.mockResolvedValueOnce('{"code":-3000,"subcode":-3000,"message":"need login"}');
|
||||
await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 64)).rejects.toThrow('code=-3000');
|
||||
expect(spy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('throws on a non-zero update subcode', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText')
|
||||
.mockResolvedValueOnce(detailBody)
|
||||
.mockResolvedValueOnce('{"code":0,"subcode":-200,"message":"denied"}');
|
||||
await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 64)).rejects.toThrow('subcode=-200');
|
||||
});
|
||||
it('throws on a non-zero update subcode', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText')
|
||||
.mockResolvedValueOnce(detailBody)
|
||||
.mockResolvedValueOnce('{"code":0,"subcode":-200,"message":"denied"}');
|
||||
await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 64)).rejects.toThrow(
|
||||
'subcode=-200',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -4,9 +4,13 @@ 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();
|
||||
let h = 5381;
|
||||
|
||||
for (const c of 'PSK') {
|
||||
h += (h << 5) + c.charCodeAt(0);
|
||||
}
|
||||
|
||||
return (h & 0x7fffffff).toString();
|
||||
})();
|
||||
|
||||
const successBody = `<script>frameElement.callback({
|
||||
@@ -23,83 +27,91 @@ const successBody = `<script>frameElement.callback({
|
||||
});</script>`;
|
||||
|
||||
describe('qzone / uploadQzoneImage', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('POSTs the upload form and returns richval + direct url', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(successBody);
|
||||
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');
|
||||
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,
|
||||
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');
|
||||
});
|
||||
|
||||
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');
|
||||
it('accepts base64:// data-URI sources and strips the prefix before upload', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(successBody);
|
||||
|
||||
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');
|
||||
});
|
||||
await uploadQzoneImageFromSource(cookies, '10000', 'base64://data:image/png;base64,AQID');
|
||||
|
||||
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,
|
||||
const form = new URLSearchParams(spy.mock.calls[0]![2] as string);
|
||||
expect(form.get('picfile')).toBe('AQID');
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects invalid base64 before any request', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
|
||||
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', 'not base64?')).rejects.toThrow('valid base64');
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
await expect(uploadQzoneImage(cookies, '10000', 'AQID')).resolves.toMatchObject({
|
||||
richval: ',12345,abc123,abc123,0,0,0,,0,0',
|
||||
type: 0,
|
||||
width: 0,
|
||||
height: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('throws on non-zero code or subcode from Qzone', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
|
||||
it('rejects invalid base64 before any request', 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');
|
||||
await expect(uploadQzoneImage(cookies, '10000', 'not base64?')).rejects.toThrow(
|
||||
'valid base64',
|
||||
);
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
spy.mockResolvedValueOnce('callback({"code":0,"subcode":-2,"message":"sub failed"});');
|
||||
await expect(uploadQzoneImage(cookies, '10000', 'AQID')).rejects.toThrow('subcode=-2');
|
||||
});
|
||||
it('throws on non-zero code or subcode from Qzone', async () => {
|
||||
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
|
||||
|
||||
it('throws when the success response lacks required upload fields', async () => {
|
||||
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('callback({"code":0,"data":{"albumid":"12345"}});');
|
||||
spy.mockResolvedValueOnce('callback({"code":-1,"message":"upload failed"});');
|
||||
await expect(uploadQzoneImage(cookies, '10000', 'AQID')).rejects.toThrow('code=-1');
|
||||
|
||||
await expect(uploadQzoneImage(cookies, '10000', 'AQID')).rejects.toThrow('响应缺少必要字段');
|
||||
});
|
||||
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(
|
||||
'响应缺少必要字段',
|
||||
);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user