feat(qzone): 完善空间 API 并兼容 SnowLuma API 格式 (#2124)
* feat(qzone): 接入内置空间动态、说说和赞评接口 新增好友动态、个人说说、详情及点赞、取消赞、评论和回复动作。 纯文本发表接入QQ内置空间接口,保留原有图片发表和删除路径。 保留完整动态身份和原始数据,约束游标、权限转换及请求错误处理。 验证:全工作区类型检查,367项测试通过、1项既有条件测试跳过, 变更文件ESLint及WebUI、Shell、Framework、OpenAPI构建通过。 * feat(qzone): 补齐空间管理、评论分页及 SnowLuma 兼容 * fix(qzone): 兼容真实 FormSender 回执与评论字段 * fix(qzone): 兼容黑名单回执中的空间名称 * docs(qzone): remove redundant API readme
This commit is contained in:
48 files changed
+7534
-23
No files matched your search
@@ -10,4 +10,5 @@ export * from './file';
|
||||
export * from './online';
|
||||
export * from './flash';
|
||||
export * from './database';
|
||||
export * from './qzone';
|
||||
export * from './qzone-public';
|
||||
@@ -0,0 +1,947 @@
|
||||
import type { InstanceContext, NapCatCore } from '@/napcat-core';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { TextDecoder } from 'node:util';
|
||||
import {
|
||||
buildQzonePublishRequest,
|
||||
buildQzoneText,
|
||||
getQzoneGtk,
|
||||
getQzoneTid,
|
||||
normalizeQzoneFeed,
|
||||
parseQzoneRpcResponse,
|
||||
validateQzoneFeedReference,
|
||||
type QzoneComment,
|
||||
type QzoneDetail,
|
||||
type QzoneFeed,
|
||||
type QzoneFeedPage,
|
||||
type QzoneFeedReference,
|
||||
type QzoneMsgPage,
|
||||
type QzoneUnionId,
|
||||
type QzoneUser,
|
||||
} from '../data/qzone-rpc';
|
||||
import {
|
||||
buildQzoneBanBody,
|
||||
buildQzoneProfileBody,
|
||||
buildQzoneRightBody,
|
||||
normalizeQzoneRight,
|
||||
parseQzoneProfile,
|
||||
parseQzoneWebResponse,
|
||||
QzoneWebError,
|
||||
type QzoneProfile,
|
||||
type QzoneProfileUpdate,
|
||||
} from '../data/qzone-web';
|
||||
import {
|
||||
normalizeQzoneComment,
|
||||
normalizeQzoneReply,
|
||||
type QzoneCommentPage,
|
||||
type QzoneReplyPage,
|
||||
} from '../data/qzone-comments';
|
||||
import { buildQzoneUploadImageBody, parseQzonePublishTime } from '../data/qzone';
|
||||
import {
|
||||
buildSlQzoneCommentBody,
|
||||
buildSlQzoneLikeBody,
|
||||
parseSlQzoneComment,
|
||||
parseSlQzoneMsgDetail,
|
||||
parseSlQzoneMsgList,
|
||||
type SlQzoneCommentOptions,
|
||||
type SlQzoneCommentResult,
|
||||
type SlQzoneMsgDetail,
|
||||
type SlQzoneMsgList,
|
||||
} from '../data/qzone-snowluma';
|
||||
import {
|
||||
advanceSlQzoneFeedState,
|
||||
initialSlQzoneFeedState,
|
||||
parseSlQzoneFeeds,
|
||||
slQzoneFeedPosition,
|
||||
type SlQzoneFeedPage,
|
||||
type SlQzoneFeedState,
|
||||
} from '../data/qzone-snowluma-feeds';
|
||||
|
||||
const RPC_ROOT = 'https://h5.qzone.qq.com/http2rpc/gotrpc/v1/';
|
||||
const READER = 'trpc.qzone.feeds_reader.FeedsReader';
|
||||
const WRITER = 'trpc.qzone.feeds_writer.FeedsWriter';
|
||||
const INTERACTION = 'trpc.qzone.interaction_writer.InteractionWriter';
|
||||
const REQUEST_TIMEOUT_MS = 15000;
|
||||
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
||||
const MAX_REFERENCE_BYTES = 64 * 1024;
|
||||
const MAX_CURSOR_LENGTH = 16384;
|
||||
const MAX_ATTACH_LENGTH = 8192;
|
||||
const CURSOR_TTL_MS = 10 * 60 * 1000;
|
||||
const MAX_CURSORS = 128;
|
||||
const WEB_ROOT = 'https://h5.qzone.qq.com/proxy/domain/';
|
||||
const SL_FEED_SKIP_LIMIT = 20;
|
||||
const SL_FEED_DEADLINE_MS = 45000;
|
||||
|
||||
const WEB_METHODS = {
|
||||
GetProfile: { path: 'base.qzone.qq.com/cgi-bin/user/cgi_userinfo_get_all', method: 'GET', requireCode: true },
|
||||
SetProfile: { path: 'w.qzone.qq.com/cgi-bin/user/cgi_apply_updateuserinfo_new', method: 'POST', requireCode: true },
|
||||
GetOwnMsgDetail: { path: 'taotao.qq.com/cgi-bin/emotion_cgi_msgdetail_v6', method: 'GET', requireCode: false },
|
||||
SetMsgRight: { path: 'taotao.qzone.qq.com/cgi-bin/emotion_cgi_update', method: 'POST', requireCode: false },
|
||||
SetBan: { path: 'w.qzone.qq.com/cgi-bin/right/cgi_black_action_new', method: 'POST', requireCode: false },
|
||||
GetSlMsgList: { path: 'taotao.qzone.qq.com/cgi-bin/emotion_cgi_msglist_v6', method: 'GET', requireCode: false },
|
||||
GetSlMsgListFallback: { path: 'taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6', method: 'GET', requireCode: false, root: 'https://user.qzone.qq.com/proxy/domain/', ownerReferer: true },
|
||||
LikeSlMsg: { path: 'w.qzone.qq.com/cgi-bin/likes/internal_dolike_app', method: 'POST', requireCode: false },
|
||||
UnlikeSlMsg: { path: 'w.qzone.qq.com/cgi-bin/likes/internal_unlike_app', method: 'POST', requireCode: false },
|
||||
CommentSlMsg: { path: 'taotao.qzone.qq.com/cgi-bin/emotion_cgi_re_feeds', method: 'POST', requireCode: false },
|
||||
ReplySlMsg: { path: 'taotao.qzone.qq.com/cgi-bin/emotion_cgi_addreply_ugc', method: 'POST', requireCode: true },
|
||||
} as const;
|
||||
|
||||
interface QzoneHttpRequest {
|
||||
url: string;
|
||||
method: 'GET' | 'POST';
|
||||
body?: string;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
// 固定路由,不向调用方暴露任意 RPC、URL 或取票能力。
|
||||
const RPC_METHODS = {
|
||||
GetFriendFeeds: { service: READER, command: '0x97e5', type: '0', write: false },
|
||||
GetShuoshuoList: { service: READER, command: '0x9a97', type: '1', write: false },
|
||||
GetFeedDetail: { service: READER, command: '0x97b1', type: '1', write: false },
|
||||
GetComment: { service: READER, command: '0x9bfd', type: '1', write: false },
|
||||
GetReplies: { service: READER, command: '0x9bfe', type: '1', write: false },
|
||||
PublishFeed: { service: WRITER, command: '0x9775', type: '1', write: true },
|
||||
DoLike: { service: INTERACTION, command: '0x9699', type: '1', write: true },
|
||||
UnLike: { service: INTERACTION, command: '0x969c', type: '1', write: true },
|
||||
AddComment: { service: INTERACTION, command: '0x9676', type: '1', write: true },
|
||||
AddReply: { service: INTERACTION, command: '0x9677', type: '1', write: true },
|
||||
} as const;
|
||||
|
||||
interface PageCursor {
|
||||
account: string;
|
||||
kind: 'friends' | 'moods' | 'comments' | 'replies' | 'sl-feeds';
|
||||
target: string;
|
||||
issuedAt: number;
|
||||
attachInfo: string;
|
||||
refreshId?: string;
|
||||
lastUnionId?: QzoneUnionId;
|
||||
feedReference?: QzoneFeedReference;
|
||||
parentComment?: QzoneComment;
|
||||
slFeedState?: SlQzoneFeedState;
|
||||
slFeedPage?: number;
|
||||
slFeedPositions?: string[];
|
||||
}
|
||||
|
||||
function isRecord (value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function validUin (value: unknown): value is string {
|
||||
return typeof value === 'string' && /^[1-9]\d{0,19}$/.test(value);
|
||||
}
|
||||
|
||||
function validIdentity (value: unknown, maxLength = 4096): value is string {
|
||||
return typeof value === 'string' && value.trim().length > 0 && value.length <= maxLength;
|
||||
}
|
||||
|
||||
function validateUser (value: unknown): QzoneUser {
|
||||
if (!isRecord(value) || !validUin(value['uin']) ||
|
||||
(value['uid'] !== undefined && value['uid'] !== null && value['uid'] !== '' && !validIdentity(value['uid'])) ||
|
||||
(value['nick'] !== undefined && (typeof value['nick'] !== 'string' || value['nick'].length > 4096))) {
|
||||
throw new Error('QQ空间用户信息无效');
|
||||
}
|
||||
// A raw parent may carry uid:null; keep the parent intact and omit only this target's absent UID.
|
||||
const user = { ...value };
|
||||
if (user['uid'] === null) delete user['uid'];
|
||||
return user as unknown as QzoneUser;
|
||||
}
|
||||
|
||||
function validateComment (value: unknown): QzoneComment {
|
||||
if (!isRecord(value) || !validIdentity(value['id'], 8192)) {
|
||||
throw new Error('QQ空间评论缺少有效标识');
|
||||
}
|
||||
validateUser(value['user']);
|
||||
let size: number;
|
||||
try {
|
||||
size = Buffer.byteLength(JSON.stringify(value));
|
||||
} catch {
|
||||
throw new Error('QQ空间评论格式无效');
|
||||
}
|
||||
if (size > MAX_REFERENCE_BYTES) {
|
||||
throw new Error('QQ空间评论对象过大');
|
||||
}
|
||||
return value as QzoneComment;
|
||||
}
|
||||
|
||||
function assertReadJson (value: unknown, depth = 0): void {
|
||||
if (depth > 32) throw new Error('QQ空间父评论嵌套过深');
|
||||
if (value === null || typeof value === 'string' || typeof value === 'boolean') return;
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return;
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) assertReadJson(item, depth + 1);
|
||||
return;
|
||||
}
|
||||
if (!isRecord(value) || (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)) {
|
||||
throw new Error('QQ空间父评论必须为JSON数据');
|
||||
}
|
||||
for (const item of Object.values(value)) {
|
||||
if (item !== undefined) assertReadJson(item, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
function readParentSnapshot (value: unknown): QzoneComment {
|
||||
if (!isRecord(value) || !(validIdentity(value['id'], 8192) ||
|
||||
(typeof value['id'] === 'number' && Number.isSafeInteger(value['id']) && value['id'] >= 0))) {
|
||||
throw new Error('QQ空间父评论缺少有效标识');
|
||||
}
|
||||
if (value['user'] !== undefined && !isRecord(value['user'])) throw new Error('QQ空间父评论用户信息无效');
|
||||
assertReadJson(value);
|
||||
if (Buffer.byteLength(JSON.stringify(value)) > MAX_REFERENCE_BYTES) throw new Error('QQ空间父评论不能超过64KiB');
|
||||
return structuredClone(value) as QzoneComment;
|
||||
}
|
||||
|
||||
function referenceSnapshot (value: unknown): QzoneFeedReference {
|
||||
return structuredClone(validateQzoneFeedReference(value));
|
||||
}
|
||||
|
||||
function canonicalJson (value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
|
||||
if (isRecord(value)) {
|
||||
return `{${Object.keys(value).filter(key => value[key] !== undefined).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
|
||||
}
|
||||
const json = JSON.stringify(value);
|
||||
if (json === undefined) throw new Error('QQ空间分页上下文格式无效');
|
||||
return json;
|
||||
}
|
||||
|
||||
function commentScope (reference: QzoneFeedReference, parent?: QzoneComment): string {
|
||||
return createHash('sha256').update(canonicalJson(parent === undefined
|
||||
? reference
|
||||
: { reference, parent: { id: parent.id, user: parent.user } })).digest('hex');
|
||||
}
|
||||
|
||||
function observedCount (value: unknown): number | null {
|
||||
if (typeof value !== 'number' && !(typeof value === 'string' && /^\d+$/.test(value))) return null;
|
||||
const count = typeof value === 'number' ? value : Number(value);
|
||||
return Number.isSafeInteger(count) && count >= 0 ? count : null;
|
||||
}
|
||||
|
||||
async function withTimeout<T> (work: () => Promise<T>, message: string, duration = REQUEST_TIMEOUT_MS): Promise<T> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
return await Promise.race([
|
||||
Promise.resolve().then(work),
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(message)), duration);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
export class NTQQQzoneApi {
|
||||
context: InstanceContext;
|
||||
core: NapCatCore;
|
||||
private readonly cursors = new Map<string, PageCursor>();
|
||||
private readonly rightUpdates = new Set<string>();
|
||||
|
||||
constructor (context: InstanceContext, core: NapCatCore) {
|
||||
this.context = context;
|
||||
this.core = core;
|
||||
}
|
||||
|
||||
private currentUser (): QzoneUser {
|
||||
const info = this.core.selfInfo;
|
||||
if (!info || !validUin(info.uin) || !validIdentity(info.uid)) {
|
||||
throw new Error('QQ空间需要已登录的当前账号');
|
||||
}
|
||||
return validateUser({ uin: info.uin, uid: info.uid, nick: info.nick ?? '' });
|
||||
}
|
||||
|
||||
private accountKey (user: QzoneUser): string {
|
||||
return `${user.uin}:${user.uid ?? ''}`;
|
||||
}
|
||||
|
||||
private assertAccount (user: QzoneUser): void {
|
||||
if (this.accountKey(this.currentUser()) !== this.accountKey(user)) {
|
||||
throw new Error('QQ账号已切换,请重新获取QQ空间数据');
|
||||
}
|
||||
}
|
||||
|
||||
private readCursor (token: string | undefined, user: QzoneUser, kind: PageCursor['kind'], target: string): PageCursor | undefined {
|
||||
if (token === undefined) return undefined;
|
||||
if (typeof token !== 'string' || token.length === 0 || token.length > MAX_CURSOR_LENGTH) {
|
||||
throw new Error('QQ空间游标无效,请重新获取第一页');
|
||||
}
|
||||
const cursor = this.cursors.get(token);
|
||||
const now = Date.now();
|
||||
if (!cursor || cursor.issuedAt > now || now - cursor.issuedAt >= CURSOR_TTL_MS ||
|
||||
cursor.account !== this.accountKey(user) || cursor.kind !== kind || cursor.target !== target) {
|
||||
throw new Error('QQ空间游标无效或已过期,请重新获取第一页');
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
|
||||
private saveCursor (cursor: Omit<PageCursor, 'issuedAt'>, prefix = ''): string {
|
||||
const now = Date.now();
|
||||
for (const [token, entry] of this.cursors) {
|
||||
if (entry.issuedAt > now || now - entry.issuedAt >= CURSOR_TTL_MS) this.cursors.delete(token);
|
||||
}
|
||||
while (this.cursors.size >= MAX_CURSORS) {
|
||||
const oldest = this.cursors.keys().next().value;
|
||||
if (oldest === undefined) break;
|
||||
this.cursors.delete(oldest);
|
||||
}
|
||||
const token = `${prefix}${randomUUID()}`;
|
||||
this.cursors.set(token, { ...structuredClone(cursor), issuedAt: now });
|
||||
return token;
|
||||
}
|
||||
|
||||
private parsePage (data: Record<string, unknown>): { feeds: QzoneFeed[]; hasMore: boolean; attachInfo: string; } {
|
||||
if (!Array.isArray(data['feeds']) ||
|
||||
(data['has_more'] !== undefined && typeof data['has_more'] !== 'boolean')) {
|
||||
throw new Error('QQ空间列表响应格式异常');
|
||||
}
|
||||
const feeds = data['feeds'].map((item: unknown) => {
|
||||
if (!isRecord(item) || !isRecord(item['feed'])) throw new Error('QQ空间动态响应格式异常');
|
||||
return item['feed'] as QzoneFeed;
|
||||
});
|
||||
const hasMore = data['has_more'] === true;
|
||||
const attachInfo = data['attach_info'];
|
||||
if (hasMore && (typeof attachInfo !== 'string' || attachInfo.length === 0 || attachInfo.length > MAX_ATTACH_LENGTH)) {
|
||||
throw new Error('QQ空间续页信息无效,请重新获取第一页');
|
||||
}
|
||||
return { feeds, hasMore, attachInfo: typeof attachInfo === 'string' ? attachInfo : '' };
|
||||
}
|
||||
|
||||
private async authHeaders (user: QzoneUser, deadline?: number): Promise<{ cookie: string; gtk: number; skey: string; pskey: string; }> {
|
||||
const remaining = deadline === undefined ? REQUEST_TIMEOUT_MS : Math.min(REQUEST_TIMEOUT_MS, deadline - Date.now());
|
||||
if (remaining <= 0) throw new Error('QQ空间读取超过时间预算,请使用游标分页');
|
||||
const results = await withTimeout(() => Promise.allSettled([
|
||||
this.core.apis.UserApi.getSKey(),
|
||||
this.core.apis.UserApi.getPSkey(['qzone.qq.com']),
|
||||
]), 'QQ空间取票超时,请稍后重试', remaining);
|
||||
this.assertAccount(user);
|
||||
const skey = results[0].status === 'fulfilled' ? results[0].value : undefined;
|
||||
const ticket = results[1].status === 'fulfilled' ? results[1].value : undefined;
|
||||
const pskey = ticket?.result === 0 ? ticket.domainPskeyMap?.get('qzone.qq.com') : undefined;
|
||||
const validKey = (key: unknown): key is string => typeof key === 'string' && key.length > 0 && key.length <= 4096 &&
|
||||
[...key].every(char => char.charCodeAt(0) > 32 && char.charCodeAt(0) !== 127 && char !== ';' && char !== ',');
|
||||
const sk = validKey(skey) ? skey : '';
|
||||
const pk = validKey(pskey) ? pskey : '';
|
||||
if (!sk && !pk) throw new Error('QQ空间取票失败,请确认当前账号登录状态');
|
||||
const cookies = [`uin=o${user.uin}`, `p_uin=o${user.uin}`];
|
||||
if (sk) cookies.push(`skey=${sk}`);
|
||||
if (pk) cookies.push(`p_skey=${pk}`);
|
||||
return { cookie: cookies.join('; '), gtk: getQzoneGtk(pk || sk), skey: sk, pskey: pk };
|
||||
}
|
||||
|
||||
private async requestText (user: QzoneUser, build: (gtk: number, auth: { skey: string; pskey: string; }) => QzoneHttpRequest, write: boolean, deadline?: number): Promise<string> {
|
||||
const auth = await this.authHeaders(user, deadline);
|
||||
const request = build(auth.gtk, auth);
|
||||
const remaining = deadline === undefined ? REQUEST_TIMEOUT_MS : Math.min(REQUEST_TIMEOUT_MS, deadline - Date.now());
|
||||
if (remaining <= 0) throw new Error('QQ空间读取超过时间预算,请使用游标分页');
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), remaining);
|
||||
let text: string;
|
||||
try {
|
||||
this.assertAccount(user);
|
||||
const response = await fetch(request.url, {
|
||||
method: request.method,
|
||||
redirect: 'error',
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
Cookie: auth.cookie,
|
||||
Origin: 'https://h5.qzone.qq.com',
|
||||
Referer: 'https://h5.qzone.qq.com/pc-qzone/index.html',
|
||||
...request.headers,
|
||||
},
|
||||
...(request.body !== undefined ? { body: request.body } : {}),
|
||||
});
|
||||
if (response.status !== 200 || !response.body) {
|
||||
await response.body?.cancel();
|
||||
throw new Error('Invalid response');
|
||||
}
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const chunk = await reader.read();
|
||||
if (chunk.done) break;
|
||||
size += chunk.value.byteLength;
|
||||
if (size > MAX_RESPONSE_BYTES) {
|
||||
await reader.cancel();
|
||||
throw new Error('Response too large');
|
||||
}
|
||||
chunks.push(chunk.value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
text = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size));
|
||||
} catch {
|
||||
throw new Error(write
|
||||
? 'QQ空间请求未能确认结果,请先查询状态,勿自动重试'
|
||||
: 'QQ空间请求失败或超时,请稍后重试');
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
this.assertAccount(user);
|
||||
return text;
|
||||
}
|
||||
|
||||
private async rpc (method: keyof typeof RPC_METHODS, request: Record<string, unknown>, user: QzoneUser): Promise<Record<string, unknown>> {
|
||||
const route = RPC_METHODS[method];
|
||||
const text = await this.requestText(user, gtk => ({
|
||||
url: `${RPC_ROOT}${route.service}/${method}?g_tk=${gtk}`,
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-oidb': JSON.stringify({ uint32_command: route.command, uint32_service_type: route.type }),
|
||||
'x-web-qua': 'V1_HT5_QZ_9.9.32_001_IDC_B',
|
||||
},
|
||||
}), route.write);
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(text);
|
||||
} catch {
|
||||
throw new Error(route.write
|
||||
? 'QQ空间响应无法解析,操作结果未知,请先查询状态,勿自动重试'
|
||||
: 'QQ空间响应格式异常');
|
||||
}
|
||||
return parseQzoneRpcResponse(value);
|
||||
}
|
||||
|
||||
private async web (method: keyof typeof WEB_METHODS, params: URLSearchParams, user: QzoneUser): Promise<Record<string, unknown>> {
|
||||
const route = WEB_METHODS[method];
|
||||
const write = route.method === 'POST';
|
||||
const text = await this.requestText(user, gtk => {
|
||||
const url = new URL(`${'root' in route ? route.root : WEB_ROOT}${route.path}`);
|
||||
url.searchParams.set('g_tk', String(gtk));
|
||||
if (!write) {
|
||||
for (const [key, value] of params) url.searchParams.set(key, value);
|
||||
}
|
||||
const headers: Record<string, string> = {};
|
||||
if ('ownerReferer' in route) headers['Referer'] = `https://user.qzone.qq.com/${params.get('uin')}`;
|
||||
if (write) headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
||||
return {
|
||||
url: url.href,
|
||||
method: route.method,
|
||||
headers,
|
||||
...(write ? { body: params.toString() } : {}),
|
||||
};
|
||||
}, write);
|
||||
try {
|
||||
return parseQzoneWebResponse(text, route.requireCode);
|
||||
} catch (error) {
|
||||
if (!write) throw error;
|
||||
// Parser errors contain only local descriptions and numeric status codes.
|
||||
throw new Error(`${(error as Error).message};未确认成功,请先查询状态,勿自动重试`);
|
||||
}
|
||||
}
|
||||
|
||||
async getProfile (targetUin?: string): Promise<QzoneProfile> {
|
||||
const user = this.currentUser();
|
||||
const target = targetUin ?? user.uin;
|
||||
if (!validUin(target)) throw new Error('target_uin 必须是有效QQ号');
|
||||
const response = await this.web('GetProfile', new URLSearchParams({
|
||||
uin: target, vuin: user.uin, fupdate: '1', rd: String(Math.random()),
|
||||
}), user);
|
||||
return parseQzoneProfile(response);
|
||||
}
|
||||
|
||||
private slTarget (user: QzoneUser, targetUin?: string): string {
|
||||
const target = targetUin ?? user.uin;
|
||||
if (!validUin(target)) throw new Error('target_uin 必须是有效QQ号');
|
||||
return target;
|
||||
}
|
||||
|
||||
private slPagination (pos: number, num: number): void {
|
||||
if (!Number.isSafeInteger(pos) || pos < 0 || !Number.isSafeInteger(num) || num < 1 || num > 100) {
|
||||
throw new Error('pos 必须为非负安全整数,num 必须在1到100之间');
|
||||
}
|
||||
}
|
||||
|
||||
async getSnowlumaMsgList (targetUin?: string, pos = 0, num = 20): Promise<SlQzoneMsgList> {
|
||||
this.slPagination(pos, num);
|
||||
const user = this.currentUser();
|
||||
const target = this.slTarget(user, targetUin);
|
||||
const params = new URLSearchParams({
|
||||
uin: target,
|
||||
ftype: '0',
|
||||
sort: '0',
|
||||
pos: String(pos),
|
||||
num: String(num),
|
||||
replynum: '100',
|
||||
callback: '_preloadCallback',
|
||||
code_version: '1',
|
||||
format: 'jsonp',
|
||||
need_private_comment: '1',
|
||||
});
|
||||
let response: Record<string, unknown>;
|
||||
try {
|
||||
response = await this.web('GetSlMsgList', params, user);
|
||||
} catch (error) {
|
||||
// 仅对已明确拒绝的只读请求切换已知代理域,不跟随重定向、不重放写操作。
|
||||
if (!(error instanceof QzoneWebError) || error.field !== 'code' || error.code !== -10000) throw error;
|
||||
response = await this.web('GetSlMsgListFallback', new URLSearchParams({
|
||||
uin: target, ftype: '0', sort: '0', pos: String(pos), num: String(num), code_version: '1', format: 'json',
|
||||
}), user);
|
||||
}
|
||||
return parseSlQzoneMsgList(response);
|
||||
}
|
||||
|
||||
async getSnowlumaMsgDetail (tid: string, targetUin?: string, pos = 0, num = 20): Promise<SlQzoneMsgDetail> {
|
||||
if (!validIdentity(tid, 8192)) throw new Error('tid 必须是有效的说说标识');
|
||||
this.slPagination(pos, num);
|
||||
const user = this.currentUser();
|
||||
const target = this.slTarget(user, targetUin);
|
||||
const response = await this.web('GetOwnMsgDetail', new URLSearchParams({
|
||||
tid,
|
||||
uin: target,
|
||||
t1_source: '1',
|
||||
not_trunc_con: '1',
|
||||
need_right: '1',
|
||||
not_adapt_outpic: '1',
|
||||
pos: String(pos),
|
||||
num: String(num),
|
||||
}), user);
|
||||
return parseSlQzoneMsgDetail(response, tid);
|
||||
}
|
||||
|
||||
async setSnowlumaLike (tid: string, targetUin: string | undefined, enable: boolean, abstime = 0): Promise<void> {
|
||||
const user = this.currentUser();
|
||||
const target = this.slTarget(user, targetUin);
|
||||
const body = buildSlQzoneLikeBody(user.uin, target, tid, enable, abstime);
|
||||
await this.web(enable ? 'LikeSlMsg' : 'UnlikeSlMsg', new URLSearchParams(body), user);
|
||||
}
|
||||
|
||||
async commentSnowluma (tid: string, content: string, targetUin?: string, options?: SlQzoneCommentOptions): Promise<SlQzoneCommentResult> {
|
||||
const user = this.currentUser();
|
||||
const target = this.slTarget(user, targetUin);
|
||||
const body = buildSlQzoneCommentBody(user.uin, target, tid, content, options);
|
||||
const response = await this.web(options?.comment_id !== undefined ? 'ReplySlMsg' : 'CommentSlMsg', new URLSearchParams(body), user);
|
||||
return parseSlQzoneComment(response, options);
|
||||
}
|
||||
|
||||
async uploadCommentImage (base64: string): Promise<{ url: string; }> {
|
||||
if (typeof base64 !== 'string' || !base64 || base64.length > 32 * 1024 * 1024 || !/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) {
|
||||
throw new Error('QQ空间评论图片数据无效或超过限制');
|
||||
}
|
||||
const user = this.currentUser();
|
||||
const text = await this.requestText(user, (gtk, auth) => ({
|
||||
url: `https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${gtk}`,
|
||||
method: 'POST',
|
||||
body: buildQzoneUploadImageBody({ uin: user.uin, skey: auth.skey, pskey: auth.pskey, g_tk: String(gtk), base64 }),
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
}), true);
|
||||
let response: Record<string, unknown>;
|
||||
try {
|
||||
// The upload CGI acknowledges with ret:0 rather than code:0.
|
||||
response = parseQzoneWebResponse(text);
|
||||
} catch (error) {
|
||||
throw new Error(`${(error as Error).message};图片上传结果未确认,请先查询状态,勿自动重试`);
|
||||
}
|
||||
const data = response['data'];
|
||||
if (!isRecord(data) || typeof data['url'] !== 'string' || data['url'].trim() !== data['url'] ||
|
||||
[...data['url']].some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) {
|
||||
throw new Error('QQ空间上传未返回可用图片地址');
|
||||
}
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(data['url']);
|
||||
} catch {
|
||||
throw new Error('QQ空间上传图片地址无效');
|
||||
}
|
||||
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) throw new Error('QQ空间上传图片地址无效');
|
||||
return { url: url.href };
|
||||
}
|
||||
|
||||
async getSnowlumaFeeds (pageNum = 1, count = 10, cursor?: string): Promise<SlQzoneFeedPage> {
|
||||
if (!Number.isSafeInteger(pageNum) || pageNum < 1 || !Number.isSafeInteger(count) || count < 1 || count > 50) {
|
||||
throw new Error('page_num 必须为正安全整数,count 必须在1到50之间');
|
||||
}
|
||||
const user = this.currentUser();
|
||||
const previous = this.readCursor(cursor, user, 'sl-feeds', '');
|
||||
if (previous && (!previous.slFeedState || !previous.slFeedPage)) throw new Error('QQ空间动态游标无效');
|
||||
const requestedPage = previous?.slFeedPage ?? pageNum;
|
||||
if (previous && pageNum !== 1 && pageNum !== requestedPage) throw new Error('page_num 与动态游标不匹配');
|
||||
if (!previous && pageNum > SL_FEED_SKIP_LIMIT) throw new Error('跳页超过20页读取预算,请从首页使用游标续页');
|
||||
let state = previous?.slFeedState ? structuredClone(previous.slFeedState) : initialSlQzoneFeedState();
|
||||
const position = (value: SlQzoneFeedState): string => createHash('sha256').update(slQzoneFeedPosition(value)).digest('hex');
|
||||
const visited = new Set(previous?.slFeedPositions ?? [position(state)]);
|
||||
const deadline = Date.now() + SL_FEED_DEADLINE_MS;
|
||||
for (let page = previous?.slFeedPage ?? 1; page <= requestedPage; page++) {
|
||||
const text = await this.requestText(user, gtk => {
|
||||
const params = new URLSearchParams({
|
||||
uin: user.uin,
|
||||
scope: '0',
|
||||
view: '1',
|
||||
gid: '',
|
||||
flag: '1',
|
||||
filter: 'all',
|
||||
applist: 'all',
|
||||
refresh: '0',
|
||||
firstGetGroup: '0',
|
||||
mixnocache: '0',
|
||||
scene: '0',
|
||||
sidomain: 'qzonestyle.gtimg.cn',
|
||||
callback: '_preloadCallback',
|
||||
format: 'jsonp',
|
||||
useutf8: '1',
|
||||
outputhtmlfeed: '1',
|
||||
count: String(count),
|
||||
usertime: String(Math.floor(Date.now() / 1000)),
|
||||
rd: String(Math.random()),
|
||||
windowId: String(Math.random()),
|
||||
g_tk: String(gtk),
|
||||
});
|
||||
for (const [key, value] of Object.entries(state)) params.set(key === 'aisortNextTime' ? 'getAisort' : key, value);
|
||||
return { url: `${WEB_ROOT}ic2.qzone.qq.com/cgi-bin/feeds/feeds3_html_more?${params}`, method: 'GET' };
|
||||
}, false, deadline);
|
||||
const data = parseSlQzoneFeeds(text);
|
||||
if (!data.has_more) return page < requestedPage ? { feeds: [], has_more: false, next_cursor: null } : { feeds: data.feeds, has_more: false, next_cursor: null };
|
||||
if (!data.main) throw new Error('QQ空间动态缺少续页状态');
|
||||
const next = advanceSlQzoneFeedState(state, data.main);
|
||||
const nextPosition = position(next);
|
||||
if (visited.has(nextPosition)) throw new Error('QQ空间动态续页位置未推进,请重新读取');
|
||||
visited.add(nextPosition);
|
||||
if (page === requestedPage) {
|
||||
const token = this.saveCursor({
|
||||
account: this.accountKey(user),
|
||||
kind: 'sl-feeds',
|
||||
target: '',
|
||||
attachInfo: '',
|
||||
slFeedState: next,
|
||||
slFeedPage: page + 1,
|
||||
slFeedPositions: [...visited].slice(-32),
|
||||
}, 'slqf:');
|
||||
return { feeds: data.feeds, has_more: true, next_cursor: token };
|
||||
}
|
||||
state = next;
|
||||
}
|
||||
throw new Error('QQ空间动态页码无效');
|
||||
}
|
||||
|
||||
async setProfile (profile: QzoneProfileUpdate): Promise<void> {
|
||||
const user = this.currentUser();
|
||||
const body = buildQzoneProfileBody(user.uin, profile);
|
||||
await this.web('SetProfile', new URLSearchParams(body), user);
|
||||
}
|
||||
|
||||
async setMsgRight (tid: string, ugcRight: number, targetUins?: string[]): Promise<{ ugc_right: number; }> {
|
||||
if (!validIdentity(tid, 8192)) throw new Error('tid 必须是有效的说说标识');
|
||||
const normalized = normalizeQzoneRight(ugcRight, targetUins);
|
||||
const user = this.currentUser();
|
||||
const lockKey = `${this.accountKey(user)}:${tid}`;
|
||||
if (this.rightUpdates.has(lockKey)) throw new Error('该说说正在修改权限,请稍后重试');
|
||||
this.rightUpdates.add(lockKey);
|
||||
try {
|
||||
const detail = await this.web('GetOwnMsgDetail', new URLSearchParams({
|
||||
tid, uin: user.uin, t1_source: '1', not_trunc_con: '1', need_right: '1', not_adapt_outpic: '1',
|
||||
}), user);
|
||||
const body = buildQzoneRightBody(detail, user.uin, tid, normalized.right, normalized.targetUins);
|
||||
const result = await this.web('SetMsgRight', new URLSearchParams(body), user);
|
||||
if (result['ugc_right'] === undefined) return { ugc_right: normalized.right };
|
||||
const returnedRight = typeof result['ugc_right'] === 'string' && /^\d+$/.test(result['ugc_right'])
|
||||
? Number(result['ugc_right'])
|
||||
: result['ugc_right'];
|
||||
if (typeof returnedRight !== 'number' || ![1, 4, 16, 64, 128].includes(returnedRight)) {
|
||||
throw new Error('QQ空间返回的权限无效,请回读说说确认,勿自动重试');
|
||||
}
|
||||
if (returnedRight !== normalized.right) throw new Error('QQ空间返回权限与请求不一致,请回读说说确认,勿自动重试');
|
||||
return { ugc_right: returnedRight };
|
||||
} finally {
|
||||
this.rightUpdates.delete(lockKey);
|
||||
}
|
||||
}
|
||||
|
||||
async setBan (targetUin: string, enable = true): Promise<void> {
|
||||
const user = this.currentUser();
|
||||
const body = buildQzoneBanBody(user.uin, targetUin, enable);
|
||||
await this.web('SetBan', new URLSearchParams(body), user);
|
||||
}
|
||||
|
||||
async getFriendFeeds (cursor?: string): Promise<QzoneFeedPage> {
|
||||
const user = this.currentUser();
|
||||
const previous = this.readCursor(cursor, user, 'friends', '');
|
||||
const refreshId = previous?.refreshId ?? `${user.uin}_${Date.now()}`;
|
||||
const request: Record<string, unknown> = { refresh_id: refreshId };
|
||||
if (previous) {
|
||||
request['attach_info'] = previous.attachInfo;
|
||||
if (previous.lastUnionId) request['last_client_feed_union_id'] = previous.lastUnionId;
|
||||
}
|
||||
const page = this.parsePage(await this.rpc('GetFriendFeeds', request, user));
|
||||
let lastUnionId = previous?.lastUnionId;
|
||||
if (page.hasMore) {
|
||||
for (let index = page.feeds.length - 1; index >= 0; index--) {
|
||||
const feed = page.feeds[index];
|
||||
if (!feed || feed.cell_common?.feed_type === 3 || !feed.cell_common?.union_id) continue;
|
||||
try {
|
||||
lastUnionId = validateQzoneFeedReference({ union_id: feed.cell_common.union_id }).union_id;
|
||||
break;
|
||||
} catch {
|
||||
// 未知动态仍保留在返回页;只有可用身份才能作为后续分页锚点。
|
||||
}
|
||||
}
|
||||
}
|
||||
const nextCursor = page.hasMore
|
||||
? this.saveCursor({
|
||||
account: this.accountKey(user), kind: 'friends', target: '', attachInfo: page.attachInfo, refreshId, lastUnionId,
|
||||
})
|
||||
: null;
|
||||
return { feeds: page.feeds.map(normalizeQzoneFeed), has_more: page.hasMore, next_cursor: nextCursor };
|
||||
}
|
||||
|
||||
async getMsgList (targetUin?: string, cursor?: string): Promise<QzoneMsgPage> {
|
||||
const user = this.currentUser();
|
||||
const target = targetUin ?? user.uin;
|
||||
if (!validUin(target)) throw new Error('target_uin 必须是有效QQ号');
|
||||
const previous = this.readCursor(cursor, user, 'moods', target);
|
||||
let uid = user.uid;
|
||||
if (target !== user.uin) {
|
||||
try {
|
||||
uid = await withTimeout(() => this.core.apis.UserApi.getUidByUinV2(target), 'QQ空间账号解析超时');
|
||||
} catch {
|
||||
throw new Error('无法解析目标QQ号,请确认账号可访问');
|
||||
}
|
||||
}
|
||||
if (!validIdentity(uid) || uid.includes('*')) throw new Error('无法解析目标QQ号,请确认账号可访问');
|
||||
this.assertAccount(user);
|
||||
const data = await this.rpc('GetShuoshuoList', {
|
||||
host_uid: uid, host_uin: target, attach_info: previous?.attachInfo ?? '', feed_action_domain_type: 1,
|
||||
}, user);
|
||||
const page = this.parsePage(data);
|
||||
if (data['seal_off_memory'] !== undefined && data['seal_off_memory'] !== null && !isRecord(data['seal_off_memory'])) {
|
||||
throw new Error('QQ空间封存状态响应格式异常');
|
||||
}
|
||||
const nextCursor = page.hasMore
|
||||
? this.saveCursor({
|
||||
account: this.accountKey(user), kind: 'moods', target, attachInfo: page.attachInfo,
|
||||
})
|
||||
: null;
|
||||
return {
|
||||
msglist: page.feeds.map(normalizeQzoneFeed),
|
||||
has_more: page.hasMore,
|
||||
next_cursor: nextCursor,
|
||||
...(isRecord(data['seal_off_memory']) ? { seal_off_memory: data['seal_off_memory'] } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
private async detailResponse (ref: QzoneFeedReference, user: QzoneUser): Promise<Record<string, unknown>> {
|
||||
return await this.rpc('GetFeedDetail', {
|
||||
union_id: ref.union_id,
|
||||
cell_feed_transfer: ref.cell_feed_transfer,
|
||||
feed_action_domain_type: ref.feed_action_domain_type ?? 1,
|
||||
from_page: 1,
|
||||
}, user);
|
||||
}
|
||||
|
||||
private detailFeed (data: Record<string, unknown>): QzoneFeed {
|
||||
if (!isRecord(data['feed']) || !isRecord(data['feed']['feed'])) {
|
||||
throw new Error('QQ空间未返回说说详情,内容可能不可访问或已删除');
|
||||
}
|
||||
const feed = data['feed']['feed'] as QzoneFeed;
|
||||
if (feed.cell_comment !== undefined && !isRecord(feed.cell_comment)) {
|
||||
throw new Error('QQ空间评论响应格式异常');
|
||||
}
|
||||
const comments = feed.cell_comment?.comments;
|
||||
if (comments !== undefined && (!Array.isArray(comments) || comments.some(comment => !isRecord(comment)))) {
|
||||
throw new Error('QQ空间评论响应格式异常');
|
||||
}
|
||||
return feed;
|
||||
}
|
||||
|
||||
private currentReference (ref: QzoneFeedReference, feed: QzoneFeed): QzoneFeedReference {
|
||||
const current = referenceSnapshot(ref);
|
||||
const common = feed.cell_common;
|
||||
if (isRecord(common)) {
|
||||
if (common['union_id'] !== undefined && common['union_id'] !== null) current.union_id = common['union_id'] as QzoneUnionId;
|
||||
if (typeof common['domain_type'] === 'number' && Number.isInteger(common['domain_type']) && common['domain_type'] >= 1 && common['domain_type'] <= 3) {
|
||||
current.feed_action_domain_type = common['domain_type'];
|
||||
}
|
||||
if (validIdentity(common['cur_like_key'], 8192)) current.like_key = common['cur_like_key'];
|
||||
}
|
||||
if (feed.cell_feed_transfer !== undefined && feed.cell_feed_transfer !== null) current.cell_feed_transfer = feed.cell_feed_transfer;
|
||||
return referenceSnapshot(current);
|
||||
}
|
||||
|
||||
private commentCell (value: unknown): { comments: QzoneComment[]; count: number | null; } {
|
||||
if (value === undefined) return { comments: [], count: null };
|
||||
if (!isRecord(value) || (value['comments'] !== undefined && (!Array.isArray(value['comments']) || value['comments'].some(item => !isRecord(item))))) {
|
||||
throw new Error('QQ空间评论响应格式异常');
|
||||
}
|
||||
return { comments: (value['comments'] ?? []) as QzoneComment[], count: observedCount(value['num']) };
|
||||
}
|
||||
|
||||
private commentPageState (data: Record<string, unknown>, field: 'attach_info' | 'reply_attach_info', previous?: string): { hasMore: boolean; attachInfo: string; } {
|
||||
if (data['has_more'] !== undefined && typeof data['has_more'] !== 'boolean') throw new Error('QQ空间评论分页状态无效');
|
||||
const hasMore = data['has_more'] === true;
|
||||
const attachInfo = data[field];
|
||||
if (hasMore && (typeof attachInfo !== 'string' || !attachInfo.length || attachInfo.length > MAX_ATTACH_LENGTH || attachInfo === previous)) {
|
||||
throw new Error('QQ空间评论续页信息缺失或未推进,请重新读取');
|
||||
}
|
||||
return { hasMore, attachInfo: typeof attachInfo === 'string' ? attachInfo : '' };
|
||||
}
|
||||
|
||||
private saveCommentCursor (user: QzoneUser, boundRef: QzoneFeedReference, requestRef: QzoneFeedReference, attachInfo: string): string {
|
||||
return this.saveCursor({
|
||||
account: this.accountKey(user), kind: 'comments', target: commentScope(boundRef), attachInfo, feedReference: requestRef,
|
||||
});
|
||||
}
|
||||
|
||||
async getMsgDetail (reference: QzoneFeedReference): Promise<QzoneDetail> {
|
||||
const ref = referenceSnapshot(reference);
|
||||
const user = this.currentUser();
|
||||
const data = await this.detailResponse(ref, user);
|
||||
const feed = this.detailFeed(data);
|
||||
const item = normalizeQzoneFeed(feed);
|
||||
const state = this.commentPageState(data, 'attach_info');
|
||||
// 旧详情仍返回原来的规范化引用;分页请求在内部保留 H5 返回的完整新上下文。
|
||||
const nextCursor = state.hasMore && item.feed_ref
|
||||
? this.saveCommentCursor(user, item.feed_ref, this.currentReference(ref, feed), state.attachInfo)
|
||||
: null;
|
||||
return {
|
||||
...item,
|
||||
comments: feed.cell_comment?.comments ?? [],
|
||||
comment_has_more: state.hasMore,
|
||||
comment_next_cursor: nextCursor,
|
||||
};
|
||||
}
|
||||
|
||||
async getComments (reference: QzoneFeedReference, cursor?: string): Promise<QzoneCommentPage> {
|
||||
const ref = referenceSnapshot(reference);
|
||||
const user = this.currentUser();
|
||||
const previous = this.readCursor(cursor, user, 'comments', commentScope(ref));
|
||||
let current = ref;
|
||||
let data: Record<string, unknown>;
|
||||
let cell: { comments: QzoneComment[]; count: number | null; };
|
||||
if (previous) {
|
||||
if (!previous.feedReference) throw new Error('QQ空间评论游标无效,请重新读取');
|
||||
current = referenceSnapshot(previous.feedReference);
|
||||
data = await this.rpc('GetComment', {
|
||||
union_id: current.union_id, attach_info: previous.attachInfo, cell_feed_transfer: current.cell_feed_transfer,
|
||||
}, user);
|
||||
const commentCell = data['cell_comment'];
|
||||
// 空末页可能省略 repeated 字段,只有明确结束时才接受,避免把畸形响应当作读完。
|
||||
if (commentCell === undefined && data['has_more'] === false) {
|
||||
cell = { comments: [], count: null };
|
||||
} else {
|
||||
if (!isRecord(commentCell) || (commentCell['comments'] === undefined && data['has_more'] !== false)) {
|
||||
throw new Error('QQ空间评论响应缺少有效cell_comment对象或评论列表');
|
||||
}
|
||||
cell = this.commentCell(commentCell);
|
||||
}
|
||||
} else {
|
||||
data = await this.detailResponse(ref, user);
|
||||
const feed = this.detailFeed(data);
|
||||
current = this.currentReference(ref, feed);
|
||||
cell = this.commentCell(feed.cell_comment);
|
||||
}
|
||||
const comments = cell.comments.map(normalizeQzoneComment);
|
||||
const state = this.commentPageState(data, 'attach_info', previous?.attachInfo);
|
||||
const nextCursor = state.hasMore ? this.saveCommentCursor(user, current, current, state.attachInfo) : null;
|
||||
return {
|
||||
feed_ref: current,
|
||||
comment_num: cell.count,
|
||||
comments,
|
||||
has_more: state.hasMore,
|
||||
next_cursor: nextCursor,
|
||||
raw: data,
|
||||
};
|
||||
}
|
||||
|
||||
async getCommentReplies (reference: QzoneFeedReference, parent: QzoneComment, cursor?: string): Promise<QzoneReplyPage> {
|
||||
const ref = referenceSnapshot(reference);
|
||||
const parentSnapshot = readParentSnapshot(parent);
|
||||
const user = this.currentUser();
|
||||
const scope = commentScope(ref, parentSnapshot);
|
||||
const previous = this.readCursor(cursor, user, 'replies', scope);
|
||||
let current = ref;
|
||||
let requestParent = parentSnapshot;
|
||||
if (previous) {
|
||||
if (!previous.feedReference || !previous.parentComment) throw new Error('QQ空间回复游标无效,请重新读取');
|
||||
current = referenceSnapshot(previous.feedReference);
|
||||
requestParent = readParentSnapshot(previous.parentComment);
|
||||
}
|
||||
const initialAttach = requestParent['reply_attach_info'];
|
||||
if (initialAttach !== undefined && initialAttach !== null && (typeof initialAttach !== 'string' || initialAttach.length > MAX_ATTACH_LENGTH)) {
|
||||
throw new Error('QQ空间父评论的回复续页信息无效');
|
||||
}
|
||||
const attachInfo = previous?.attachInfo ?? (typeof initialAttach === 'string' ? initialAttach : '');
|
||||
const data = await this.rpc('GetReplies', {
|
||||
union_id: current.union_id,
|
||||
cur_comment: requestParent,
|
||||
comment_attach_info: '',
|
||||
reply_attach_info: attachInfo,
|
||||
page_size: 20,
|
||||
cell_feed_transfer: current.cell_feed_transfer,
|
||||
}, user);
|
||||
const replyList = data['replys'];
|
||||
if ((replyList === undefined && data['has_more'] !== false) ||
|
||||
(replyList !== undefined && (!Array.isArray(replyList) || replyList.some(item => !isRecord(item))))) {
|
||||
throw new Error('QQ空间回复响应格式异常');
|
||||
}
|
||||
const replies = ((replyList ?? []) as QzoneComment[]).map(normalizeQzoneReply);
|
||||
const state = this.commentPageState(data, 'reply_attach_info', attachInfo);
|
||||
const nextParent = state.hasMore
|
||||
? readParentSnapshot({
|
||||
...requestParent, reply_attach_info: state.attachInfo, has_more_reply: state.hasMore,
|
||||
})
|
||||
: undefined;
|
||||
const nextCursor = state.hasMore
|
||||
? this.saveCursor({
|
||||
account: this.accountKey(user),
|
||||
kind: 'replies',
|
||||
target: scope,
|
||||
attachInfo: state.attachInfo,
|
||||
feedReference: current,
|
||||
// 保留首次完整父对象和内联回复,只推进分页元数据,不累计整段历史到请求中。
|
||||
parentComment: nextParent,
|
||||
})
|
||||
: null;
|
||||
return {
|
||||
feed_ref: current,
|
||||
comment_id: String(requestParent.id),
|
||||
replies,
|
||||
reply_num: data['reply_num'] === undefined ? observedCount(requestParent['reply_num']) : observedCount(data['reply_num']),
|
||||
has_more: state.hasMore,
|
||||
next_cursor: nextCursor,
|
||||
raw: data,
|
||||
};
|
||||
}
|
||||
|
||||
async publishMsg (content: string, ugcRight = 1, targetUins?: string[]): Promise<{ tid: string; time: number; }> {
|
||||
const user = this.currentUser();
|
||||
const request = buildQzonePublishRequest(user, content, ugcRight, targetUins);
|
||||
const data = await this.rpc('PublishFeed', request, user);
|
||||
const tid = isRecord(data['feed']) ? getQzoneTid(data['feed'] as QzoneFeed) : null;
|
||||
if (!tid) throw new Error('QQ空间发表响应缺少说说标识,结果未知,请先查询列表确认,勿自动重试');
|
||||
return { tid, time: parseQzonePublishTime((data['feed'] as QzoneFeed).cell_common?.time) };
|
||||
}
|
||||
|
||||
async setLike (reference: QzoneFeedReference, enable: boolean): Promise<void> {
|
||||
const ref = validateQzoneFeedReference(reference);
|
||||
if (typeof ref.like_key !== 'string' || !ref.like_key.trim() || ref.like_key.length > 8192) {
|
||||
throw new Error('缺少QQ空间点赞标识,请先重新获取说说详情');
|
||||
}
|
||||
if (typeof enable !== 'boolean') throw new Error('QQ空间点赞状态必须是布尔值');
|
||||
const user = this.currentUser();
|
||||
const data = await this.rpc(enable ? 'DoLike' : 'UnLike', {
|
||||
like_key: ref.like_key, union_id: ref.union_id, like_type: 1, cell_feed_transfer: ref.cell_feed_transfer,
|
||||
}, user);
|
||||
if (!isRecord(data['like'])) throw new Error('QQ空间未返回点赞结果,请先查询状态,勿自动重试');
|
||||
}
|
||||
|
||||
async comment (reference: QzoneFeedReference, content: string, parentComment?: QzoneComment, replyUser?: QzoneUser): Promise<{ comment_id: string; comment: QzoneComment; }> {
|
||||
const ref = validateQzoneFeedReference(reference);
|
||||
const segments = buildQzoneText(content);
|
||||
if (replyUser !== undefined && parentComment === undefined) throw new Error('reply_user 必须与父评论一同提供');
|
||||
const parent = parentComment === undefined ? undefined : validateComment(parentComment);
|
||||
const target = parent ? validateUser(replyUser ?? parent.user) : undefined;
|
||||
const user = this.currentUser();
|
||||
const data = await this.rpc(parent ? 'AddReply' : 'AddComment', {
|
||||
union_id: ref.union_id,
|
||||
cell_feed_transfer: ref.cell_feed_transfer,
|
||||
...(parent ? { comment: parent, reply: { content: segments, target_user: target, user } } : { comment: { user, content: segments } }),
|
||||
}, user);
|
||||
const result = data[parent ? 'reply' : 'comment'];
|
||||
if (!isRecord(result) || !validIdentity(result['id'], 8192)) {
|
||||
throw new Error('QQ空间未返回有效评论标识,结果未知,请先查询详情确认,勿自动重试');
|
||||
}
|
||||
return { comment_id: result['id'], comment: result as QzoneComment };
|
||||
}
|
||||
}
|
||||
@@ -749,9 +749,16 @@ export class NTQQWebApi {
|
||||
}
|
||||
|
||||
private async getQzoneAuth () {
|
||||
const uin = this.core.selfInfo.uin;
|
||||
const uid = this.core.selfInfo.uid;
|
||||
if (!uin || !uid) throw new Error('QQ空间需要已登录的当前账号');
|
||||
const assertAccount = () => {
|
||||
if (this.core.selfInfo.uin !== uin || this.core.selfInfo.uid !== uid) throw new Error('QQ账号已切换,请重新确认QQ空间操作');
|
||||
};
|
||||
const skey = await this.core.apis.UserApi.getSKey() || '';
|
||||
assertAccount();
|
||||
const pskey = (await this.core.apis.UserApi.getPSkey(['qzone.qq.com'])).domainPskeyMap.get('qzone.qq.com') || '';
|
||||
const uin = this.core.selfInfo.uin || '10001';
|
||||
assertAccount();
|
||||
const g_tk = this.getBknFromSKey(skey);
|
||||
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
|
||||
return { skey, pskey, uin, g_tk, cookie };
|
||||
@@ -786,7 +793,7 @@ export class NTQQWebApi {
|
||||
* @param ugcRight 查看权限 1所有人可见 4好友可见 16部分好友可见 64仅自己可见 128部分好友不可见
|
||||
* @param targetUins 权限作用QQ号数组, ugcRight为16/128时使用
|
||||
*/
|
||||
async publishQzoneMsg (content: string, richvals: string[], ugcRight: number, targetUins?: number[]) {
|
||||
async publishQzoneMsg (content: string, richvals: string[], ugcRight: number, targetUins?: Array<string | number>) {
|
||||
const { uin, g_tk, cookie } = await this.getQzoneAuth();
|
||||
const richval = richvals.length > 0 ? richvals.join('\t') : undefined;
|
||||
const allowUins = targetUins && targetUins.length > 0 ? targetUins.join('|') : undefined;
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import {
|
||||
normalizeQzoneMediaImages,
|
||||
normalizeQzoneRichContent,
|
||||
type QzoneComment,
|
||||
type QzoneFeedReference,
|
||||
} from './qzone-rpc';
|
||||
|
||||
export interface QzoneReplyItem {
|
||||
reply_id: string | null;
|
||||
user_id: string | null;
|
||||
uid: string | null;
|
||||
nickname: string | null;
|
||||
time: number | null;
|
||||
content: string | null;
|
||||
images: string[] | null;
|
||||
like_count: number | null;
|
||||
liked: boolean | null;
|
||||
target_user_id: string | null;
|
||||
target_uid: string | null;
|
||||
target_nickname: string | null;
|
||||
reply: QzoneComment;
|
||||
}
|
||||
|
||||
export interface QzoneCommentItem {
|
||||
comment_id: string | null;
|
||||
user_id: string | null;
|
||||
uid: string | null;
|
||||
nickname: string | null;
|
||||
time: number | null;
|
||||
content: string | null;
|
||||
images: string[] | null;
|
||||
like_count: number | null;
|
||||
liked: boolean | null;
|
||||
reply_num: number | null;
|
||||
has_more_replies: boolean | null;
|
||||
replies: QzoneReplyItem[];
|
||||
comment: QzoneComment;
|
||||
}
|
||||
|
||||
export interface QzoneCommentPage {
|
||||
feed_ref: QzoneFeedReference;
|
||||
comment_num: number | null;
|
||||
comments: QzoneCommentItem[];
|
||||
has_more: boolean;
|
||||
next_cursor: string | null;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface QzoneReplyPage {
|
||||
feed_ref: QzoneFeedReference;
|
||||
comment_id: string;
|
||||
replies: QzoneReplyItem[];
|
||||
reply_num: number | null;
|
||||
has_more: boolean;
|
||||
next_cursor: string | null;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function object (value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
return prototype === Object.prototype || prototype === null ? value as Record<string, unknown> : undefined;
|
||||
}
|
||||
|
||||
function identifier (value: unknown): string | null {
|
||||
if (typeof value === 'string') return value.trim().length > 0 && value.length <= 8192 ? value : null;
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? String(value) : null;
|
||||
}
|
||||
|
||||
function userId (value: unknown): string | null {
|
||||
if (typeof value === 'string' && /^\d+$/.test(value) && /[1-9]/.test(value)) return value;
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? String(value) : null;
|
||||
}
|
||||
|
||||
function count (value: unknown): number | null {
|
||||
if (typeof value !== 'number' && !(typeof value === 'string' && /^\d+$/.test(value))) return null;
|
||||
const result = Number(value);
|
||||
return Number.isSafeInteger(result) && result >= 0 ? result : null;
|
||||
}
|
||||
|
||||
function nickname (value: unknown): string | null {
|
||||
return typeof value === 'string' ? value : null;
|
||||
}
|
||||
|
||||
function likeState (value: unknown): boolean | null {
|
||||
return value === 1 ? true : value === 0 ? false : null;
|
||||
}
|
||||
|
||||
function author (value: unknown): { user_id: string | null; uid: string | null; nickname: string | null; } {
|
||||
const user = object(value);
|
||||
const uid = user?.['uid'];
|
||||
return {
|
||||
user_id: userId(user?.['uin']),
|
||||
uid: typeof uid === 'string' ? identifier(uid) : null,
|
||||
nickname: nickname(user?.['nick']),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeQzoneReply (value: QzoneComment): QzoneReplyItem {
|
||||
const reply = object(value);
|
||||
if (!reply) throw new Error('QQ空间回复数据格式异常');
|
||||
const user = author(reply['user']);
|
||||
const target = author(reply['target_user']);
|
||||
const like = object(reply['like']);
|
||||
return {
|
||||
reply_id: identifier(reply['id']),
|
||||
...user,
|
||||
// The renderer uses time in Unix seconds. create_time is not this wire field.
|
||||
time: count(reply['time']),
|
||||
content: normalizeQzoneRichContent(reply['content']),
|
||||
images: normalizeQzoneMediaImages(reply['media_items']),
|
||||
like_count: count(like?.['count']),
|
||||
liked: likeState(like?.['status']),
|
||||
target_user_id: target.user_id,
|
||||
target_uid: target.uid,
|
||||
target_nickname: target.nickname,
|
||||
reply: value,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeQzoneComment (value: QzoneComment): QzoneCommentItem {
|
||||
const comment = object(value);
|
||||
if (!comment) throw new Error('QQ空间评论数据格式异常');
|
||||
const user = author(comment['user']);
|
||||
const like = object(comment['like']);
|
||||
const inline = comment['replys'];
|
||||
if (inline !== undefined && inline !== null && !Array.isArray(inline)) throw new Error('QQ空间内联回复列表格式异常');
|
||||
const replies = (inline ?? []) as unknown[];
|
||||
return {
|
||||
comment_id: identifier(comment['id']),
|
||||
...user,
|
||||
time: count(comment['time']),
|
||||
content: normalizeQzoneRichContent(comment['content']),
|
||||
images: normalizeQzoneMediaImages(comment['media_items']),
|
||||
like_count: count(like?.['count']),
|
||||
liked: likeState(like?.['status']),
|
||||
reply_num: count(comment['reply_num']),
|
||||
has_more_replies: typeof comment['has_more_reply'] === 'boolean' ? comment['has_more_reply'] : null,
|
||||
// These are only the inline replies returned on this page, not an exhaustiveness claim.
|
||||
replies: replies.map((reply) => {
|
||||
if (!object(reply)) throw new Error('QQ空间内联回复数据格式异常');
|
||||
return normalizeQzoneReply(reply as QzoneComment);
|
||||
}),
|
||||
comment: value,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
import { Buffer } from 'node:buffer';
|
||||
|
||||
export const QZONE_REFERENCE_MAX_BYTES = 64 * 1024;
|
||||
const MAX_IDENTITY_LENGTH = 8192;
|
||||
const MAX_TEXT_LENGTH = 2000;
|
||||
|
||||
export interface QzoneUnionExtension {
|
||||
ext_id_type?: number;
|
||||
numeric?: number | string;
|
||||
str?: string;
|
||||
unsigned_numeric?: number | string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface QzoneUnionId {
|
||||
uf_key?: string;
|
||||
ugc_id?: string;
|
||||
feed_id?: string;
|
||||
ext_ids?: QzoneUnionExtension[];
|
||||
serialized_data?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface QzoneUser {
|
||||
uin: string;
|
||||
uid?: string;
|
||||
nick?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface QzoneRichMsg {
|
||||
type: number;
|
||||
content?: string;
|
||||
media_items?: unknown[];
|
||||
name?: string;
|
||||
uid?: string;
|
||||
uin?: string;
|
||||
url?: string;
|
||||
who?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface QzoneRawCommentUser {
|
||||
uin?: string;
|
||||
uid?: string | null;
|
||||
nick?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface QzoneComment {
|
||||
id?: string | number;
|
||||
user?: QzoneRawCommentUser;
|
||||
content?: QzoneRichMsg[];
|
||||
replys?: QzoneComment[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface QzoneFeed {
|
||||
cell_common?: {
|
||||
union_id?: QzoneUnionId;
|
||||
time?: number | string;
|
||||
app_id?: number;
|
||||
feed_type?: number;
|
||||
feed_sub_type?: number;
|
||||
feed_biz_type?: number;
|
||||
client_key?: string;
|
||||
cur_like_key?: string;
|
||||
domain_type?: number;
|
||||
operate_mask?: number;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
cell_user_info?: { user?: QzoneUser; [key: string]: unknown; };
|
||||
cell_summary?: { summary?: QzoneRichMsg[]; [key: string]: unknown; };
|
||||
cell_media?: { media_items?: unknown[]; [key: string]: unknown; };
|
||||
cell_comment?: { num?: number | string; comments?: QzoneComment[]; [key: string]: unknown; };
|
||||
cell_like?: { num?: number | string; liked?: boolean; [key: string]: unknown; };
|
||||
cell_feed_transfer?: unknown;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface QzoneFeedReference {
|
||||
union_id: QzoneUnionId;
|
||||
cell_feed_transfer?: unknown;
|
||||
feed_action_domain_type?: number;
|
||||
like_key?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface QzoneFeedItem {
|
||||
tid: string | null;
|
||||
user_id: string | null;
|
||||
content: string | null;
|
||||
time: number | null;
|
||||
comment_num: number | null;
|
||||
like_num: number | null;
|
||||
images: string[] | null;
|
||||
feed_ref: QzoneFeedReference | null;
|
||||
feed: QzoneFeed;
|
||||
}
|
||||
|
||||
export interface QzoneFeedPage {
|
||||
feeds: QzoneFeedItem[];
|
||||
has_more: boolean;
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
export interface QzoneMsgPage {
|
||||
msglist: QzoneFeedItem[];
|
||||
has_more: boolean;
|
||||
next_cursor: string | null;
|
||||
seal_off_memory?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface QzoneDetail extends QzoneFeedItem {
|
||||
comments: QzoneComment[];
|
||||
comment_has_more?: boolean;
|
||||
comment_next_cursor?: string | null;
|
||||
}
|
||||
|
||||
function record (value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
return prototype === Object.prototype || prototype === null ? value as Record<string, unknown> : undefined;
|
||||
}
|
||||
|
||||
function identity (value: unknown): string | null {
|
||||
return typeof value === 'string' && value.trim().length > 0 && value.length <= MAX_IDENTITY_LENGTH ? value : null;
|
||||
}
|
||||
|
||||
function nonnegativeInteger (value: unknown): number | null {
|
||||
if (typeof value !== 'number' && !(typeof value === 'string' && /^\d+$/.test(value))) return null;
|
||||
const number = typeof value === 'number' ? value : Number(value);
|
||||
return Number.isSafeInteger(number) && number >= 0 ? number : null;
|
||||
}
|
||||
|
||||
function numericIdentifier (value: unknown): string | null {
|
||||
if (typeof value === 'string' && /^\d+$/.test(value) && /[1-9]/.test(value)) return value;
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? String(value) : null;
|
||||
}
|
||||
|
||||
export function getQzoneGtk (key: string): number {
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < key.length; i++) hash += (hash << 5) + key.charCodeAt(i);
|
||||
return hash & 0x7fffffff;
|
||||
}
|
||||
|
||||
export function getQzoneTid (feed: QzoneFeed): string | null {
|
||||
const common = record(feed?.cell_common);
|
||||
const union = record(common?.['union_id']);
|
||||
if (!union) return null;
|
||||
const extensions = union['ext_ids'];
|
||||
if (Array.isArray(extensions)) {
|
||||
const extension = extensions.map(record).find(item => item?.['ext_id_type'] === 5);
|
||||
if (extension) {
|
||||
const tid = identity(extension['str']) ?? numericIdentifier(extension['unsigned_numeric']) ?? numericIdentifier(extension['numeric']);
|
||||
if (tid !== null) return tid;
|
||||
}
|
||||
}
|
||||
// Other feed kinds also have ugc_id; an album ID is not a mood tid.
|
||||
if (common?.['feed_sub_type'] !== 1 && common?.['app_id'] !== 311) return null;
|
||||
return identity(union['ugc_id']);
|
||||
}
|
||||
|
||||
export function normalizeQzoneRichContent (value: unknown): string | null {
|
||||
if (!Array.isArray(value)) return null;
|
||||
const parts: string[] = [];
|
||||
for (const item of value) {
|
||||
const segment = record(item);
|
||||
if (!segment) return null;
|
||||
switch (segment['type']) {
|
||||
case 0:
|
||||
case 2:
|
||||
case 4:
|
||||
if (typeof segment['content'] !== 'string') return null;
|
||||
parts.push(segment['content']);
|
||||
break;
|
||||
case 1:
|
||||
case 5:
|
||||
if (typeof segment['name'] !== 'string') return null;
|
||||
parts.push(segment['type'] === 1 ? `@${segment['name']}` : segment['name']);
|
||||
break;
|
||||
case 3:
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
function imageUrl (value: unknown): string | null {
|
||||
if (typeof value !== 'string' || !value) return null;
|
||||
const url = value.startsWith('//') ? `https:${value}` : value;
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return (parsed.protocol === 'https:' || parsed.protocol === 'http:') && !parsed.username && !parsed.password ? url : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeQzoneMediaImages (value: unknown): string[] | null {
|
||||
if (!Array.isArray(value)) return null;
|
||||
const images: string[] = [];
|
||||
for (const item of value) {
|
||||
const media = record(item);
|
||||
if (!media) return null;
|
||||
if (media['type'] === 1) continue; // Video covers are not post images.
|
||||
if (media['type'] !== 0) return null;
|
||||
const image = record(media['image']);
|
||||
if (!image) return null;
|
||||
const variants = Array.isArray(image['photo_url']) ? image['photo_url'].map(record) : [];
|
||||
let selected: string | null = null;
|
||||
// Same original-image preference as the H5 client: download, origin, big, current.
|
||||
for (const spec of [6, 0, 1, 5]) {
|
||||
const variant = variants.find(candidate => candidate?.['spec'] === spec);
|
||||
selected = imageUrl(record(variant?.['url'])?.['url']);
|
||||
if (selected !== null) break;
|
||||
}
|
||||
selected ??= imageUrl(record(image['default_url'])?.['url']);
|
||||
if (selected === null) return null;
|
||||
images.push(selected);
|
||||
}
|
||||
return images;
|
||||
}
|
||||
|
||||
function assertJson (value: unknown, depth = 0): void {
|
||||
if (depth > 32) throw new Error('QQ空间动态引用嵌套过深');
|
||||
if (value === null || typeof value === 'string' || typeof value === 'boolean') return;
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return;
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) assertJson(item, depth + 1);
|
||||
return;
|
||||
}
|
||||
const object = record(value);
|
||||
if (!object) throw new Error('QQ空间动态引用必须为JSON数据');
|
||||
for (const item of Object.values(object)) {
|
||||
if (item !== undefined) assertJson(item, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
export function validateQzoneFeedReference (value: unknown): QzoneFeedReference {
|
||||
const reference = record(value);
|
||||
const union = record(reference?.['union_id']);
|
||||
if (!reference || !union) throw new Error('QQ空间动态引用缺少union_id');
|
||||
const keys = ['uf_key', 'ugc_id', 'feed_id', 'serialized_data'];
|
||||
let hasIdentity = false;
|
||||
for (const key of keys) {
|
||||
if (union[key] === undefined) continue;
|
||||
const field = union[key];
|
||||
if (typeof field !== 'string' || field.length > MAX_IDENTITY_LENGTH) throw new Error('QQ空间动态标识无效');
|
||||
// Protobuf JSON may include empty defaults alongside an issued identity.
|
||||
if (field.trim().length > 0) hasIdentity = true;
|
||||
}
|
||||
if (!hasIdentity) throw new Error('QQ空间动态引用缺少有效标识');
|
||||
if (union['ext_ids'] !== undefined && (!Array.isArray(union['ext_ids']) || union['ext_ids'].some(item => !record(item)))) {
|
||||
throw new Error('QQ空间动态扩展标识无效');
|
||||
}
|
||||
const domain = reference['feed_action_domain_type'];
|
||||
if (domain !== undefined && (typeof domain !== 'number' || !Number.isInteger(domain) || domain < 1 || domain > 3)) {
|
||||
throw new Error('QQ空间动态所属域无效');
|
||||
}
|
||||
if (reference['like_key'] !== undefined && identity(reference['like_key']) === null) throw new Error('QQ空间点赞标识无效');
|
||||
assertJson(reference);
|
||||
let serialized: string;
|
||||
try {
|
||||
const encoded = JSON.stringify(reference);
|
||||
if (typeof encoded !== 'string') throw new Error('Invalid JSON');
|
||||
serialized = encoded;
|
||||
} catch {
|
||||
throw new Error('QQ空间动态引用无法序列化');
|
||||
}
|
||||
if (Buffer.byteLength(serialized, 'utf8') > QZONE_REFERENCE_MAX_BYTES) throw new Error('QQ空间动态引用不能超过64KiB');
|
||||
return reference as unknown as QzoneFeedReference;
|
||||
}
|
||||
|
||||
export function normalizeQzoneFeed (feed: QzoneFeed): QzoneFeedItem {
|
||||
if (!record(feed)) throw new Error('QQ空间动态数据格式无效');
|
||||
const common = record(feed.cell_common);
|
||||
const user = record(record(feed.cell_user_info)?.['user']);
|
||||
let reference: QzoneFeedReference | null = null;
|
||||
if (record(common?.['union_id'])) {
|
||||
const candidate: Record<string, unknown> = { union_id: common?.['union_id'] };
|
||||
if (feed.cell_feed_transfer !== undefined) candidate['cell_feed_transfer'] = feed.cell_feed_transfer;
|
||||
const domain = common?.['domain_type'];
|
||||
if (typeof domain === 'number' && Number.isInteger(domain) && domain >= 1 && domain <= 3) candidate['feed_action_domain_type'] = domain;
|
||||
if (identity(common?.['cur_like_key']) !== null) candidate['like_key'] = common?.['cur_like_key'];
|
||||
try {
|
||||
reference = validateQzoneFeedReference(candidate);
|
||||
} catch {
|
||||
// Preserve the raw feed while declining to issue an unusable action handle.
|
||||
}
|
||||
}
|
||||
return {
|
||||
tid: getQzoneTid(feed),
|
||||
user_id: numericIdentifier(user?.['uin']),
|
||||
content: normalizeQzoneRichContent(record(feed.cell_summary)?.['summary']),
|
||||
time: nonnegativeInteger(common?.['time']),
|
||||
comment_num: nonnegativeInteger(record(feed.cell_comment)?.['num']),
|
||||
like_num: nonnegativeInteger(record(feed.cell_like)?.['num']),
|
||||
images: normalizeQzoneMediaImages(record(feed.cell_media)?.['media_items']),
|
||||
feed_ref: reference,
|
||||
feed,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildQzoneText (content: string): QzoneRichMsg[] {
|
||||
if (typeof content !== 'string' || !content.trim()) throw new Error('QQ空间正文不能为空');
|
||||
if (content.length > MAX_TEXT_LENGTH) throw new Error('QQ空间正文不能超过2000字');
|
||||
return [{ content, media_items: [], name: '', type: 0, uid: '', uin: '', url: '', who: 0 }];
|
||||
}
|
||||
|
||||
export function buildQzonePublishRequest (
|
||||
user: QzoneUser,
|
||||
content: string,
|
||||
ugcRight: number,
|
||||
targetUins?: string[],
|
||||
now = Math.floor(Date.now() / 1000),
|
||||
key?: string
|
||||
): { feed: QzoneFeed; from: number; } {
|
||||
if (!user || typeof user.uin !== 'string' || numericIdentifier(user.uin) === null) throw new Error('QQ空间当前账号无效');
|
||||
if (user.uid !== undefined && typeof user.uid !== 'string') throw new Error('QQ空间当前账号UID无效');
|
||||
if (user.nick !== undefined && typeof user.nick !== 'string') throw new Error('QQ空间当前账号昵称无效');
|
||||
const permissions = new Map([[1, 1], [4, 2], [16, 3], [128, 4], [64, 5]]);
|
||||
const flag = permissions.get(ugcRight);
|
||||
if (flag === undefined) throw new Error('ugc_right仅支持1、4、16、64、128');
|
||||
if (targetUins !== undefined && (!Array.isArray(targetUins) || targetUins.some(uin => typeof uin !== 'string' || numericIdentifier(uin) === null))) {
|
||||
throw new Error('target_uins必须为有效QQ号数组');
|
||||
}
|
||||
if ((ugcRight === 16 || ugcRight === 128) && !targetUins?.length) throw new Error('ugc_right为16或128时target_uins不能为空');
|
||||
if (!Number.isSafeInteger(now) || now < 0) throw new Error('QQ空间发表时间无效');
|
||||
const clientKey = key ?? `${user.uin}_${now}_${Math.floor(Math.random() * 1e10)}`;
|
||||
if (identity(clientKey) === null) throw new Error('QQ空间发表请求标识无效');
|
||||
const right: Record<string, unknown> = { flag: [flag] };
|
||||
if (ugcRight === 16) right['white_uins'] = [...targetUins!];
|
||||
if (ugcRight === 128) right['black_uins'] = [...targetUins!];
|
||||
return {
|
||||
feed: {
|
||||
cell_common: {
|
||||
time: now,
|
||||
client_key: clientKey,
|
||||
feed_type: 1,
|
||||
feed_sub_type: 1,
|
||||
union_id: { uf_key: clientKey, ugc_id: clientKey, feed_id: clientKey },
|
||||
feed_biz_type: 0,
|
||||
},
|
||||
cell_user_info: { user: { uin: user.uin, uid: user.uid ?? '', nick: user.nick ?? '' } },
|
||||
cell_summary: { summary: buildQzoneText(content) },
|
||||
cell_permission: { right },
|
||||
},
|
||||
from: 3,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseQzoneRpcResponse (value: unknown): Record<string, unknown> {
|
||||
const response = record(value);
|
||||
if (!response || response['retcode'] !== 0) {
|
||||
const code = response?.['retcode'];
|
||||
const suffix = typeof code === 'number' && Number.isSafeInteger(code) ? ` (retcode=${code})` : '';
|
||||
throw new Error(`QQ空间请求失败${suffix}`);
|
||||
}
|
||||
const data = record(response['data']);
|
||||
if (!data) throw new Error('QQ空间响应缺少有效data对象');
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
import JSON5 from 'json5';
|
||||
import { Parser } from 'htmlparser2';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
export interface SlQzoneFeed {
|
||||
uin: number;
|
||||
nickname: string;
|
||||
time: number;
|
||||
appid: number;
|
||||
key: string;
|
||||
html: string;
|
||||
tid: string | null;
|
||||
content: string | null;
|
||||
content_complete: boolean | null;
|
||||
images: string[] | null;
|
||||
like_count: number | null;
|
||||
comment_count: number | null;
|
||||
}
|
||||
|
||||
export interface SlQzoneFeedPage {
|
||||
feeds: SlQzoneFeed[];
|
||||
has_more: boolean;
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
export interface SlQzoneFeedState {
|
||||
begintime: string;
|
||||
dayspac: string;
|
||||
pagenum: string;
|
||||
aisortEndTime: string;
|
||||
aisortOffset: string;
|
||||
aisortBeginTime: string;
|
||||
aisortNextTime: string;
|
||||
icServerTime: string;
|
||||
externparam: string;
|
||||
daylist: string;
|
||||
uinlist: string;
|
||||
}
|
||||
|
||||
export interface SlQzoneParsedFeeds {
|
||||
feeds: SlQzoneFeed[];
|
||||
has_more: boolean;
|
||||
main: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
const MAX_INPUT_BYTES = 8 * 1024 * 1024;
|
||||
const MAX_HTML_BYTES = 2 * 1024 * 1024;
|
||||
const MAX_DEPTH = 64;
|
||||
const MAX_TOKENS = 200000;
|
||||
const MAX_HTML_NODES = 50000;
|
||||
const STATE_NUMBERS = ['begintime', 'dayspac', 'pagenum', 'aisortEndTime', 'aisortOffset', 'aisortBeginTime', 'aisortNextTime', 'icServerTime'] as const;
|
||||
const STATE_STRINGS = ['externparam', 'daylist', 'uinlist'] as const;
|
||||
const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
||||
|
||||
function record (value: unknown): value is Record<string, unknown> {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
return prototype === Object.prototype || prototype === null;
|
||||
}
|
||||
|
||||
function count (value: unknown): number | null {
|
||||
if (typeof value !== 'number' && !(typeof value === 'string' && /^\d+$/.test(value))) return null;
|
||||
const number = Number(value);
|
||||
return Number.isSafeInteger(number) && number >= 0 ? number : null;
|
||||
}
|
||||
|
||||
function scalar (value: unknown, label: string): string {
|
||||
if (value === undefined || value === null) return '';
|
||||
if (typeof value !== 'string') throw new Error(`QQ空间动态${label}格式异常`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function wireNumber (value: unknown, label: string): number {
|
||||
if (value === undefined || value === null) return 0;
|
||||
const result = count(value);
|
||||
if (result === null) throw new Error(`QQ空间动态${label}格式异常`);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Only adapt data syntax that JSON5 lacks: undefined values and elided array slots. */
|
||||
function json5DataSource (source: string, undefinedMarker: string): string {
|
||||
const chunks: string[] = [];
|
||||
const nesting: Array<{ array: boolean; awaiting: boolean; }> = [];
|
||||
let offset = 0;
|
||||
let tokens = 0;
|
||||
const statusKeys = new Set<string>();
|
||||
const markValue = () => {
|
||||
const parent = nesting[nesting.length - 1];
|
||||
if (parent?.array) parent.awaiting = false;
|
||||
};
|
||||
const nextSignificant = (start: number): number => {
|
||||
let index = start;
|
||||
while (index < source.length) {
|
||||
if (/\s/.test(source[index]!)) index++;
|
||||
else if (source.startsWith('//', index)) {
|
||||
const end = source.indexOf('\n', index + 2);
|
||||
index = end < 0 ? source.length : end + 1;
|
||||
} else if (source.startsWith('/*', index)) {
|
||||
const end = source.indexOf('*/', index + 2);
|
||||
if (end < 0) throw new Error('QQ空间动态字面量注释未结束');
|
||||
index = end + 2;
|
||||
} else break;
|
||||
}
|
||||
return index;
|
||||
};
|
||||
const checkStatusKey = (raw: string, quoted: boolean, end: number) => {
|
||||
if (nesting.length !== 1 || nesting[0]?.array || source[nextSignificant(end)] !== ':') return;
|
||||
let key: unknown = raw;
|
||||
if (quoted) key = JSON5.parse(raw);
|
||||
else if (raw.includes('\\')) key = Object.keys(JSON5.parse(`{${raw}:0}`))[0];
|
||||
if (key !== 'code' && key !== 'subcode') return;
|
||||
if (statusKeys.has(key)) throw new Error('QQ空间动态响应状态字段重复');
|
||||
statusKeys.add(key);
|
||||
};
|
||||
while (offset < source.length) {
|
||||
if (++tokens > MAX_TOKENS) throw new Error('QQ空间动态字面量节点过多');
|
||||
const char = source[offset]!;
|
||||
if (/\s/.test(char)) {
|
||||
const start = offset++;
|
||||
while (offset < source.length && /\s/.test(source[offset]!)) offset++;
|
||||
chunks.push(source.slice(start, offset));
|
||||
continue;
|
||||
}
|
||||
if (source.startsWith('//', offset) || source.startsWith('/*', offset)) {
|
||||
const start = offset;
|
||||
if (source[offset + 1] === '/') {
|
||||
const end = source.indexOf('\n', offset + 2);
|
||||
offset = end < 0 ? source.length : end + 1;
|
||||
} else {
|
||||
const end = source.indexOf('*/', offset + 2);
|
||||
if (end < 0) throw new Error('QQ空间动态字面量注释未结束');
|
||||
offset = end + 2;
|
||||
}
|
||||
chunks.push(source.slice(start, offset));
|
||||
continue;
|
||||
}
|
||||
if (char === '"' || char === "'") {
|
||||
const start = offset++;
|
||||
let closed = false;
|
||||
while (offset < source.length) {
|
||||
const current = source[offset++]!;
|
||||
if (current === '\\') offset++;
|
||||
else if (current === char) {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!closed) throw new Error('QQ空间动态字面量字符串未结束');
|
||||
const literal = source.slice(start, offset);
|
||||
checkStatusKey(literal, true, offset);
|
||||
chunks.push(literal);
|
||||
markValue();
|
||||
continue;
|
||||
}
|
||||
if (char === '[' || char === '{') {
|
||||
markValue();
|
||||
nesting.push({ array: char === '[', awaiting: true });
|
||||
if (nesting.length > MAX_DEPTH) throw new Error('QQ空间动态字面量嵌套过深');
|
||||
chunks.push(char);
|
||||
offset++;
|
||||
continue;
|
||||
}
|
||||
if (char === ']' || char === '}') {
|
||||
const current = nesting.pop();
|
||||
if (!current || current.array !== (char === ']')) throw new Error('QQ空间动态字面量括号不匹配');
|
||||
chunks.push(char);
|
||||
offset++;
|
||||
continue;
|
||||
}
|
||||
if (char === ',') {
|
||||
const current = nesting[nesting.length - 1];
|
||||
if (current?.array) {
|
||||
if (current.awaiting) chunks.push('null');
|
||||
current.awaiting = true;
|
||||
}
|
||||
chunks.push(char);
|
||||
offset++;
|
||||
continue;
|
||||
}
|
||||
if (char === ':') {
|
||||
chunks.push(char);
|
||||
offset++;
|
||||
continue;
|
||||
}
|
||||
const start = offset++;
|
||||
while (offset < source.length && !/[\s[\]{},:'"]/.test(source[offset]!) && !source.startsWith('//', offset) && !source.startsWith('/*', offset)) offset++;
|
||||
const token = source.slice(start, offset);
|
||||
checkStatusKey(token, false, offset);
|
||||
chunks.push(token === 'undefined' && source[nextSignificant(offset)] !== ':' ? JSON.stringify(undefinedMarker) : token);
|
||||
markValue();
|
||||
}
|
||||
if (nesting.length) throw new Error('QQ空间动态字面量括号未结束');
|
||||
return chunks.join('');
|
||||
}
|
||||
|
||||
function parseDataBody (text: string): Record<string, unknown> {
|
||||
if (typeof text !== 'string' || Buffer.byteLength(text) > MAX_INPUT_BYTES) throw new Error('QQ空间动态响应过大或无效');
|
||||
let source = text.trim();
|
||||
if (!source.startsWith('{')) {
|
||||
const prefix = /^(?:_preloadCallback|_Callback|callback)\s*\(/.exec(source);
|
||||
const suffix = /\)\s*;?\s*$/.exec(source);
|
||||
if (!prefix || !suffix || suffix.index < prefix[0].length) throw new Error('QQ空间动态回调格式异常');
|
||||
source = source.slice(prefix[0].length, suffix.index).trim();
|
||||
}
|
||||
if (!source.startsWith('{')) throw new Error('QQ空间动态缺少对象响应');
|
||||
let value: unknown;
|
||||
try {
|
||||
// Content-addressed marker keeps optional object fields absent instead of changing undefined into null.
|
||||
const undefinedMarker = `\u0000qz:${createHash('sha256').update(source).digest('hex')}`;
|
||||
value = JSON5.parse(json5DataSource(source, undefinedMarker), (key, item: unknown) => {
|
||||
if (DANGEROUS_KEYS.has(key) || (typeof item === 'number' && !Number.isFinite(item))) throw new Error('Unsupported data');
|
||||
return item === undefinedMarker ? undefined : item;
|
||||
});
|
||||
} catch {
|
||||
throw new Error('QQ空间动态字面量格式异常');
|
||||
}
|
||||
if (!record(value)) throw new Error('QQ空间动态缺少对象响应');
|
||||
return value;
|
||||
}
|
||||
|
||||
interface HtmlElement {
|
||||
tag: string;
|
||||
attributes: Record<string, string>;
|
||||
parent?: HtmlElement;
|
||||
children: Array<HtmlElement | string>;
|
||||
}
|
||||
|
||||
function classes (element: HtmlElement): string[] {
|
||||
return (element.attributes['class'] ?? '').split(/\s+/);
|
||||
}
|
||||
|
||||
const EXCLUDED_CLASSES = new Set(['mod-comments', 'comments-list', 'f-item-passive', 'f-ct-video']);
|
||||
const EXCLUDED_TAGS = new Set(['script', 'style', 'noscript', 'template']);
|
||||
|
||||
function excluded (element: HtmlElement): boolean {
|
||||
return EXCLUDED_TAGS.has(element.tag) || classes(element).some(name => EXCLUDED_CLASSES.has(name));
|
||||
}
|
||||
|
||||
function descendants (root: HtmlElement, prune: boolean): HtmlElement[] {
|
||||
const result: HtmlElement[] = [];
|
||||
const pending: HtmlElement[] = [root];
|
||||
while (pending.length) {
|
||||
const current = pending.pop()!;
|
||||
if (current !== root && prune && excluded(current)) continue;
|
||||
result.push(current);
|
||||
for (let index = current.children.length - 1; index >= 0; index--) {
|
||||
const child = current.children[index];
|
||||
if (typeof child !== 'string' && child) pending.push(child);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function htmlTree (html: string): HtmlElement {
|
||||
if (Buffer.byteLength(html) > MAX_HTML_BYTES) throw new Error('QQ空间动态HTML过大');
|
||||
const root: HtmlElement = { tag: '#root', attributes: {}, children: [] };
|
||||
const stack = [root];
|
||||
let nodes = 0;
|
||||
const parser = new Parser({
|
||||
onopentag (tag, attributes) {
|
||||
if (++nodes > MAX_HTML_NODES || stack.length > MAX_DEPTH) throw new Error('QQ空间动态HTML结构过大');
|
||||
const parent = stack[stack.length - 1]!;
|
||||
const element: HtmlElement = { tag, attributes: { ...attributes }, parent, children: [] };
|
||||
parent.children.push(element);
|
||||
stack.push(element);
|
||||
},
|
||||
onclosetag (tag) {
|
||||
for (let index = stack.length - 1; index > 0; index--) {
|
||||
if (stack[index]?.tag === tag) {
|
||||
stack.length = index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
ontext (text) {
|
||||
if (++nodes > MAX_HTML_NODES) throw new Error('QQ空间动态HTML结构过大');
|
||||
stack[stack.length - 1]!.children.push(text);
|
||||
},
|
||||
}, { decodeEntities: true, lowerCaseTags: true, lowerCaseAttributeNames: true });
|
||||
parser.end(html);
|
||||
return root;
|
||||
}
|
||||
|
||||
function contentText (element: HtmlElement): string {
|
||||
const pieces: string[] = [];
|
||||
const blocks = new Set(['p', 'div', 'li', 'section', 'article', 'blockquote', 'ul', 'ol']);
|
||||
const visit = (node: HtmlElement | string) => {
|
||||
if (typeof node === 'string') {
|
||||
pieces.push(node.replace(/\s+/g, ' '));
|
||||
return;
|
||||
}
|
||||
if (excluded(node) || node.attributes['data-cmd'] === 'qz_toggle' || classes(node).includes('load_img')) return;
|
||||
if (node.tag === 'br') pieces.push('\n');
|
||||
else if (node.tag === 'img') pieces.push(node.attributes['alt'] ?? '');
|
||||
else {
|
||||
if (blocks.has(node.tag)) pieces.push('\n');
|
||||
for (const child of node.children) visit(child);
|
||||
if (blocks.has(node.tag)) pieces.push('\n');
|
||||
}
|
||||
};
|
||||
visit(element);
|
||||
return pieces.join('').replace(/[^\S\n]*\n[^\S\n]*/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
|
||||
}
|
||||
|
||||
function imageUrl (value: string | undefined): string | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const url = new URL(value.startsWith('//') ? `https:${value}` : value);
|
||||
return (url.protocol === 'https:' || url.protocol === 'http:') && !url.username && !url.password ? url.href : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function projectHtml (feed: SlQzoneFeed): void {
|
||||
const document = htmlTree(feed.html);
|
||||
const roots = descendants(document, true).filter(node => classes(node).includes('f-item') && node.attributes['data-key'] === feed.key);
|
||||
if (!feed.key || roots.length !== 1) return;
|
||||
const root = roots[0]!;
|
||||
if (excluded(root)) return;
|
||||
const elements = descendants(root, true);
|
||||
const metadata = elements.find(node => node.attributes['name'] === 'feed_data' && node.attributes['data-fkey'] === feed.key && node.attributes['data-uin'] === String(feed.uin));
|
||||
const tid = metadata?.attributes['data-tid'];
|
||||
if (feed.appid === 311 && tid?.trim() && tid.length <= 8192) feed.tid = tid;
|
||||
const textElements = elements.filter(node => classes(node).includes('f-info'));
|
||||
const full = textElements.find(node => classes(node).includes('qz_info_complete') && contentText(node).length > 0);
|
||||
const selected = full ?? textElements.find(node => !classes(node).includes('qz_info_complete'));
|
||||
if (selected) {
|
||||
feed.content = contentText(selected);
|
||||
feed.content_complete = full !== undefined || !descendants(selected, true).some(node => node.attributes['data-cmd'] === 'qz_toggle');
|
||||
}
|
||||
const pictures = new Set<string>();
|
||||
for (const element of elements) {
|
||||
if (!classes(element).includes('img-item') || element.attributes['data-v_itemid'] !== undefined || element.attributes['data-videotype'] !== undefined) continue;
|
||||
const fullUrl = imageUrl(element.attributes['data-originurl'] ?? element.attributes['data-url3']);
|
||||
if (fullUrl) pictures.add(fullUrl);
|
||||
else {
|
||||
for (const image of descendants(element, true)) {
|
||||
if (image.tag !== 'img') continue;
|
||||
const url = imageUrl(image.attributes['truesrc'] ?? image.attributes['src']);
|
||||
if (url) pictures.add(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
feed.images = [...pictures];
|
||||
if (feed.like_count === null) {
|
||||
let card = root;
|
||||
for (let parent = root.parent; parent; parent = parent.parent) {
|
||||
if (classes(parent).includes('f-single')) {
|
||||
card = parent;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const button = descendants(card, true).find(node => classes(node).includes('qz_like_btn_v3'));
|
||||
feed.like_count = count(button?.attributes['data-likecnt']);
|
||||
}
|
||||
}
|
||||
|
||||
function moreFlag (value: unknown): boolean {
|
||||
if (value === true || value === 1 || value === '1') return true;
|
||||
if (value === false || value === 0 || value === '0') return false;
|
||||
throw new Error('QQ空间动态缺少明确的分页结束标志');
|
||||
}
|
||||
|
||||
export function parseSlQzoneFeeds (text: string): SlQzoneParsedFeeds {
|
||||
const response = parseDataBody(text);
|
||||
if (response['code'] !== 0 || (response['subcode'] !== undefined && response['subcode'] !== 0)) throw new Error('QQ空间好友动态请求失败');
|
||||
const data = response['data'];
|
||||
if (!record(data) || !Array.isArray(data['data']) || data['data'].length > 1000) throw new Error('QQ空间好友动态列表格式异常');
|
||||
const mainValue = data['main'];
|
||||
if (mainValue !== undefined && !record(mainValue)) throw new Error('QQ空间好友动态分页信息无效');
|
||||
const main = record(mainValue) ? mainValue : null;
|
||||
if (main && main['error'] !== undefined && main['error'] !== '') throw new Error('QQ空间好友动态服务端报告失败');
|
||||
const hasMore = moreFlag(main ? main['hasMoreFeeds'] : data['hasmore']);
|
||||
if (hasMore && !main) throw new Error('QQ空间好友动态缺少续页状态');
|
||||
const feeds: SlQzoneFeed[] = [];
|
||||
for (const value of data['data']) {
|
||||
if (value === null || value === undefined) continue;
|
||||
if (!record(value)) throw new Error('QQ空间好友动态条目格式异常');
|
||||
const key = scalar(value['key'] ?? value['feedskey'], '标识');
|
||||
if (key.length > 8192) throw new Error('QQ空间动态标识过长');
|
||||
const feed: SlQzoneFeed = {
|
||||
uin: wireNumber(value['uin'], '账号'),
|
||||
nickname: scalar(value['nickname'], '昵称'),
|
||||
time: wireNumber(value['abstime'], '时间'),
|
||||
appid: wireNumber(value['appid'], '应用'),
|
||||
key,
|
||||
html: scalar(value['html'], 'HTML'),
|
||||
tid: null,
|
||||
content: null,
|
||||
content_complete: null,
|
||||
images: null,
|
||||
like_count: count(value['likecnt']),
|
||||
comment_count: count(value['commentcnt']),
|
||||
};
|
||||
projectHtml(feed);
|
||||
feeds.push(feed);
|
||||
}
|
||||
return { feeds, has_more: hasMore, main };
|
||||
}
|
||||
|
||||
export function initialSlQzoneFeedState (): SlQzoneFeedState {
|
||||
return {
|
||||
begintime: '0',
|
||||
dayspac: '0',
|
||||
pagenum: '1',
|
||||
aisortEndTime: '0',
|
||||
aisortOffset: '0',
|
||||
aisortBeginTime: '0',
|
||||
aisortNextTime: '0',
|
||||
icServerTime: '0',
|
||||
externparam: '',
|
||||
daylist: '',
|
||||
uinlist: '',
|
||||
};
|
||||
}
|
||||
|
||||
export function advanceSlQzoneFeedState (previous: SlQzoneFeedState, main: Record<string, unknown>): SlQzoneFeedState {
|
||||
const next = { ...previous };
|
||||
for (const field of STATE_NUMBERS) {
|
||||
const value = main[field];
|
||||
if (value === undefined || value === '') continue;
|
||||
if ((typeof value !== 'number' && typeof value !== 'string') || !/^\d+$/.test(String(value)) ||
|
||||
(typeof value === 'number' && !Number.isSafeInteger(value)) || String(value).length > 32) {
|
||||
throw new Error('QQ空间动态分页数值无效');
|
||||
}
|
||||
const canonical = BigInt(value).toString();
|
||||
if (field === 'pagenum' && canonical === '0') throw new Error('QQ空间动态分页页码无效');
|
||||
next[field] = canonical;
|
||||
}
|
||||
for (const field of STATE_STRINGS) {
|
||||
const value = main[field];
|
||||
if (value === undefined || (value === '' && field !== 'uinlist')) continue;
|
||||
if (typeof value !== 'string' || value.length > 32768) throw new Error('QQ空间动态分页字符串无效');
|
||||
next[field] = value;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function slQzoneFeedPosition (state: SlQzoneFeedState): string {
|
||||
const position: Record<string, string> = {};
|
||||
for (const field of Object.keys(state).sort()) {
|
||||
if (field !== 'icServerTime') position[field] = state[field as keyof SlQzoneFeedState];
|
||||
}
|
||||
return JSON.stringify(position);
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
export interface SlQzoneEmotion {
|
||||
tid: string;
|
||||
content: string;
|
||||
time: number;
|
||||
comment_num: number;
|
||||
is_private: boolean;
|
||||
images: string[];
|
||||
}
|
||||
|
||||
export interface SlQzoneMsgList {
|
||||
total: number;
|
||||
/** False means total is the legacy page-length fallback, not a measured account total. */
|
||||
total_known?: boolean;
|
||||
msglist: SlQzoneEmotion[];
|
||||
}
|
||||
|
||||
export interface SlQzoneFlatReply {
|
||||
uin: number;
|
||||
name: string;
|
||||
time: number;
|
||||
content: string;
|
||||
comment_id: string;
|
||||
parent_comment_id: string;
|
||||
parent_comment_uin: number;
|
||||
}
|
||||
|
||||
export interface SlQzoneFlatComment {
|
||||
uin: number;
|
||||
name: string;
|
||||
time: number;
|
||||
content: string;
|
||||
comment_id: string;
|
||||
replies: SlQzoneFlatReply[];
|
||||
}
|
||||
|
||||
export interface SlQzoneMsgDetail {
|
||||
tid: string;
|
||||
content: string;
|
||||
comment_num: number;
|
||||
comments: SlQzoneFlatComment[];
|
||||
}
|
||||
|
||||
export interface SlQzoneCommentResult {
|
||||
comment_id: string;
|
||||
parent_comment_id?: string;
|
||||
parent_comment_uin?: number;
|
||||
}
|
||||
|
||||
export interface SlQzoneCommentOptions {
|
||||
imageUrls?: string[];
|
||||
comment_id?: string;
|
||||
comment_uin?: string;
|
||||
reply_uin?: string;
|
||||
reply_name?: string;
|
||||
}
|
||||
|
||||
function object (value: unknown): Record<string, unknown> | undefined {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
return prototype === Object.prototype || prototype === null ? value as Record<string, unknown> : undefined;
|
||||
}
|
||||
|
||||
function requireObject (value: unknown): Record<string, unknown> {
|
||||
const result = object(value);
|
||||
if (!result) throw new Error('QQ空间兼容响应对象格式异常');
|
||||
return result;
|
||||
}
|
||||
|
||||
function responseCodes (response: Record<string, unknown>, requireAcknowledgement = false, requireCode = false): void {
|
||||
let acknowledged = false;
|
||||
for (const field of ['code', 'subcode', 'retcode', 'ret']) {
|
||||
if (!Object.prototype.hasOwnProperty.call(response, field)) continue;
|
||||
const value = response[field];
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value !== 0) {
|
||||
const code = typeof value === 'number' && Number.isSafeInteger(value) ? ` (${field}=${value})` : '';
|
||||
throw new Error(`QQ空间兼容接口拒绝请求${code}`);
|
||||
}
|
||||
acknowledged = true;
|
||||
}
|
||||
if ((requireAcknowledgement && !acknowledged) || (requireCode && response['code'] !== 0)) {
|
||||
throw new Error('QQ空间兼容响应缺少明确成功状态');
|
||||
}
|
||||
}
|
||||
|
||||
function integer (value: unknown, minimum = 0): number {
|
||||
if (typeof value !== 'number' && !(typeof value === 'string' && /^\d+$/.test(value))) throw new Error('QQ空间兼容响应数值无效');
|
||||
const parsed = Number(value);
|
||||
if (!Number.isSafeInteger(parsed) || parsed < minimum) throw new Error('QQ空间兼容响应数值无效');
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function requiredText (value: unknown): string {
|
||||
if (typeof value !== 'string') throw new Error('QQ空间兼容响应文本字段无效');
|
||||
return value;
|
||||
}
|
||||
|
||||
function hasControlCharacter (value: string): boolean {
|
||||
for (const character of value) {
|
||||
const code = character.charCodeAt(0);
|
||||
if (code < 32 || code === 127) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function id (value: unknown, allowEmpty = false): string {
|
||||
if (value === undefined || value === null) {
|
||||
if (allowEmpty) return '';
|
||||
throw new Error('QQ空间兼容响应缺少标识');
|
||||
}
|
||||
if (typeof value === 'number') return String(integer(value));
|
||||
if (typeof value !== 'string' || value.length > 8192 || hasControlCharacter(value) || (!value.trim() && (!allowEmpty || value !== ''))) {
|
||||
throw new Error('QQ空间兼容响应标识无效');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function array (value: unknown): unknown[] {
|
||||
if (value === undefined || value === null) return [];
|
||||
if (!Array.isArray(value)) throw new Error('QQ空间兼容响应列表格式异常');
|
||||
return value;
|
||||
}
|
||||
|
||||
function pictureUrls (value: unknown): string[] {
|
||||
const result: string[] = [];
|
||||
for (const picture of array(value)) {
|
||||
const fields = requireObject(picture);
|
||||
for (const key of ['url3', 'url2', 'url1', 'smallurl']) {
|
||||
const url = fields[key];
|
||||
if (url === undefined || url === null || url === '') continue;
|
||||
if (typeof url !== 'string') throw new Error('QQ空间说说图片地址格式异常');
|
||||
result.push(url);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function privateFlag (value: unknown): boolean {
|
||||
if (value === undefined || value === null) return false;
|
||||
if (typeof value !== 'number' && !(typeof value === 'string' && /^-?\d+$/.test(value))) throw new Error('QQ空间说说私密标记无效');
|
||||
const parsed = Number(value);
|
||||
if (!Number.isSafeInteger(parsed)) throw new Error('QQ空间说说私密标记无效');
|
||||
return parsed !== 0;
|
||||
}
|
||||
|
||||
/** Legacy zero/empty sentinels apply only to absent fields, never malformed supplied values. */
|
||||
export function parseSlQzoneMsgList (response: Record<string, unknown>): SlQzoneMsgList {
|
||||
const fields = requireObject(response);
|
||||
responseCodes(fields);
|
||||
if (!Array.isArray(fields['msglist'])) throw new Error('QQ空间兼容说说列表响应不完整');
|
||||
const msglist: SlQzoneEmotion[] = [];
|
||||
for (const entry of fields['msglist']) {
|
||||
const row = requireObject(entry);
|
||||
msglist.push({
|
||||
tid: id(row['tid'], true),
|
||||
content: row['content'] === undefined || row['content'] === null ? '' : requiredText(row['content']),
|
||||
time: row['created_time'] === undefined || row['created_time'] === null ? 0 : integer(row['created_time']),
|
||||
comment_num: row['cmtnum'] === undefined || row['cmtnum'] === null ? 0 : integer(row['cmtnum']),
|
||||
is_private: privateFlag(row['secret']),
|
||||
images: pictureUrls(row['pic']),
|
||||
});
|
||||
}
|
||||
const totalKnown = fields['total'] !== undefined && fields['total'] !== null;
|
||||
return {
|
||||
total: totalKnown ? integer(fields['total']) : msglist.length,
|
||||
total_known: totalKnown,
|
||||
msglist,
|
||||
};
|
||||
}
|
||||
|
||||
function flatComment (value: unknown): Omit<SlQzoneFlatComment, 'replies'> {
|
||||
const fields = requireObject(value);
|
||||
return {
|
||||
comment_id: id(fields['tid']),
|
||||
uin: integer(fields['uin'], 1),
|
||||
name: requiredText(fields['name']),
|
||||
time: integer(fields['create_time']),
|
||||
content: requiredText(fields['content']),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseSlQzoneMsgDetail (response: Record<string, unknown>, tid: string): SlQzoneMsgDetail {
|
||||
assertTid(tid);
|
||||
const fields = requireObject(response);
|
||||
responseCodes(fields);
|
||||
if (typeof fields['tid'] !== 'string' || fields['tid'] !== tid) throw new Error('QQ空间兼容详情与请求的说说不匹配');
|
||||
const comments: SlQzoneFlatComment[] = [];
|
||||
for (const value of array(fields['commentlist'])) {
|
||||
const original = requireObject(value);
|
||||
const parent = flatComment(original);
|
||||
const replies: SlQzoneFlatReply[] = [];
|
||||
for (const reply of array(original['list_3'])) {
|
||||
replies.push({ ...flatComment(reply), parent_comment_id: parent.comment_id, parent_comment_uin: parent.uin });
|
||||
}
|
||||
comments.push({ ...parent, replies });
|
||||
}
|
||||
return { tid, content: requiredText(fields['content']), comment_num: integer(fields['cmtnum']), comments };
|
||||
}
|
||||
|
||||
function assertUin (value: unknown, safeNumeric = false): asserts value is string {
|
||||
if (typeof value !== 'string' || !/^[1-9]\d{0,19}$/.test(value) || (safeNumeric && !Number.isSafeInteger(Number(value)))) {
|
||||
throw new Error('QQ空间兼容账号标识无效');
|
||||
}
|
||||
}
|
||||
|
||||
function assertTid (value: unknown): asserts value is string {
|
||||
if (typeof value !== 'string' || !value.trim() || value.length > 8192 || hasControlCharacter(value)) throw new Error('QQ空间兼容说说标识无效');
|
||||
}
|
||||
|
||||
export function buildSlQzoneLikeBody (self: string, target: string, tid: string, enable: boolean, abstime: number): string {
|
||||
assertUin(self);
|
||||
assertUin(target);
|
||||
assertTid(tid);
|
||||
if (typeof enable !== 'boolean' || typeof abstime !== 'number' || !Number.isSafeInteger(abstime) || abstime < 0) throw new Error('QQ空间兼容点赞参数无效');
|
||||
const resource = `http://user.qzone.qq.com/${target}/mood/${tid}`;
|
||||
const form = new URLSearchParams();
|
||||
form.set('opuin', self);
|
||||
form.set('fid', tid);
|
||||
form.set('abstime', String(abstime));
|
||||
form.set('unikey', resource);
|
||||
form.set('curkey', resource);
|
||||
for (const [key, value] of Object.entries({ appid: '311', typeid: '0', from: '1', active: '0', fupdate: '1', format: 'json' })) form.set(key, value);
|
||||
form.set('qzreferrer', `https://user.qzone.qq.com/${self}`);
|
||||
return form.toString();
|
||||
}
|
||||
|
||||
function commentOptions (options: SlQzoneCommentOptions | undefined): { options: SlQzoneCommentOptions; reply: boolean; } {
|
||||
if (options !== undefined && !object(options)) throw new Error('QQ空间兼容评论选项无效');
|
||||
const fields: SlQzoneCommentOptions = options ?? {};
|
||||
if (Object.keys(fields).some(key => !['imageUrls', 'comment_id', 'comment_uin', 'reply_uin', 'reply_name'].includes(key))) throw new Error('QQ空间兼容评论选项无效');
|
||||
const reply = fields.comment_id !== undefined || fields.comment_uin !== undefined;
|
||||
if (reply) {
|
||||
assertTid(fields.comment_id);
|
||||
assertUin(fields.comment_uin, true);
|
||||
}
|
||||
const addressed = fields.reply_uin !== undefined || fields.reply_name !== undefined;
|
||||
if (addressed) {
|
||||
if (!reply || typeof fields.reply_name !== 'string' || !fields.reply_name.trim() || fields.reply_name.length > 8192) throw new Error('指定回复目标需要完整父评论与昵称');
|
||||
assertUin(fields.reply_uin, true);
|
||||
}
|
||||
if (fields.imageUrls !== undefined) {
|
||||
if (!Array.isArray(fields.imageUrls)) throw new Error('QQ空间评论图片地址必须为数组');
|
||||
if (reply && fields.imageUrls.length > 0) throw new Error('QQ空间楼中楼回复不支持图片');
|
||||
for (const url of fields.imageUrls) {
|
||||
if (typeof url !== 'string' || !url || url.length > 8192 || url.trim() !== url) throw new Error('QQ空间评论图片地址无效');
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
if (!['https:', 'http:'].includes(parsed.protocol) || parsed.username || parsed.password || /[\t\r\n]/.test(url)) throw new Error('Invalid URL');
|
||||
} catch {
|
||||
throw new Error('QQ空间评论图片地址无效');
|
||||
}
|
||||
}
|
||||
}
|
||||
return { options: fields, reply };
|
||||
}
|
||||
|
||||
function addressedContent (content: string, options: SlQzoneCommentOptions): string {
|
||||
if (options.reply_uin === undefined) return content;
|
||||
const escapes: Record<string, string> = { '%': '%25', ',': '%2C', '}': '%7D' };
|
||||
const name = [...options.reply_name!.trim()].map(character => escapes[character] ?? character).join('');
|
||||
return `@{uin:${options.reply_uin},nick:${name},auto:1} ${content}`;
|
||||
}
|
||||
|
||||
export function buildSlQzoneCommentBody (self: string, target: string, tid: string, content: string, options?: SlQzoneCommentOptions): string {
|
||||
assertUin(self);
|
||||
assertUin(target);
|
||||
assertTid(tid);
|
||||
if (typeof content !== 'string' || content === '') throw new Error('QQ空间兼容评论正文不能为空');
|
||||
const branch = commentOptions(options);
|
||||
const form = new URLSearchParams({ uin: self, hostUin: target, inCharset: 'utf-8', outCharset: 'utf-8' });
|
||||
if (branch.reply) {
|
||||
if (!content.trim()) throw new Error('QQ空间兼容回复正文不能为空白');
|
||||
form.set('hostuin', self);
|
||||
form.set('topicId', `${target}_${tid}`);
|
||||
form.set('commentId', branch.options.comment_id!);
|
||||
form.set('commentUin', branch.options.comment_uin!);
|
||||
form.set('content', addressedContent(content, branch.options));
|
||||
form.set('ref', '');
|
||||
form.set('code_version', '1');
|
||||
form.set('format', 'fs');
|
||||
form.set('qzreferrer', `https://user.qzone.qq.com/${target}`);
|
||||
} else {
|
||||
form.set('topicId', `${target}_${tid}__1`);
|
||||
form.set('content', content);
|
||||
form.set('richtype', branch.options.imageUrls?.length ? '1' : '');
|
||||
form.set('richval', branch.options.imageUrls?.join('\t') ?? '');
|
||||
for (const [key, value] of Object.entries({ format: 'json', ref: 'feeds', feedsType: '100', private: '0', paramstr: '1', isSignIn: '', plat: 'qzone', source: 'ic', platformid: '52' })) form.set(key, value);
|
||||
form.set('qzreferrer', `https://user.qzone.qq.com/${self}`);
|
||||
}
|
||||
return form.toString();
|
||||
}
|
||||
|
||||
export function parseSlQzoneComment (response: Record<string, unknown>, options?: SlQzoneCommentOptions): SlQzoneCommentResult {
|
||||
const fields = requireObject(response);
|
||||
const branch = commentOptions(options);
|
||||
responseCodes(fields, true, branch.reply);
|
||||
if (branch.reply) {
|
||||
const result = object(fields['data']);
|
||||
if (!result) throw new Error('QQ空间回复响应缺少新标识,结果未知,请查询后确认,勿自动重试');
|
||||
let replyId: string;
|
||||
try {
|
||||
replyId = id(result['id']);
|
||||
} catch {
|
||||
throw new Error('QQ空间回复响应缺少有效新标识,结果未知,请查询后确认,勿自动重试');
|
||||
}
|
||||
return { comment_id: replyId, parent_comment_id: branch.options.comment_id!, parent_comment_uin: Number(branch.options.comment_uin!) };
|
||||
}
|
||||
// An empty ID is the explicit legacy sentinel after an acknowledged ordinary comment.
|
||||
return { comment_id: id(fields['commentid'] ?? fields['commentId'], true) };
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
export interface QzoneProfile {
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface QzoneProfileUpdate {
|
||||
name?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export type QzoneUgcRight = 1 | 4 | 16 | 64 | 128;
|
||||
|
||||
const SUCCESS_FIELDS = ['code', 'subcode', 'retcode', 'ret'];
|
||||
const MAX_PROFILE_LENGTH = 8192;
|
||||
const MAX_IDENTITY_LENGTH = 8192;
|
||||
|
||||
export class QzoneWebError extends Error {
|
||||
constructor (public readonly field: string, public readonly code: number) {
|
||||
super(`QQ空间接口拒绝请求 (${field}=${code})`);
|
||||
}
|
||||
}
|
||||
|
||||
function object (value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
return prototype === Object.prototype || prototype === null ? value as Record<string, unknown> : undefined;
|
||||
}
|
||||
|
||||
function assertUin (uin: unknown): asserts uin is string {
|
||||
if (typeof uin !== 'string' || !/^[1-9]\d{0,19}$/.test(uin)) throw new Error('QQ空间账号标识无效');
|
||||
}
|
||||
|
||||
function assertIdentity (value: unknown): asserts value is string {
|
||||
if (typeof value !== 'string' || !value.trim() || value.length > MAX_IDENTITY_LENGTH) {
|
||||
throw new Error('QQ空间说说标识无效');
|
||||
}
|
||||
}
|
||||
|
||||
function assertSuccess (response: Record<string, unknown>, requireCode: boolean): void {
|
||||
let acknowledged = false;
|
||||
for (const field of SUCCESS_FIELDS) {
|
||||
if (!Object.prototype.hasOwnProperty.call(response, field)) continue;
|
||||
const code = response[field];
|
||||
if (typeof code !== 'number' || !Number.isSafeInteger(code) || code !== 0) {
|
||||
// CGI messages may contain account content or tickets. Only include a numeric code.
|
||||
if (typeof code === 'number' && Number.isSafeInteger(code)) throw new QzoneWebError(field, code);
|
||||
throw new Error('QQ空间接口拒绝请求');
|
||||
}
|
||||
acknowledged = true;
|
||||
}
|
||||
if (!acknowledged || (requireCode && response['code'] !== 0)) throw new Error('QQ空间响应缺少明确成功状态');
|
||||
}
|
||||
|
||||
/** Quote only observed bare name keys with string values, never string contents. */
|
||||
function normalizeNameStringKeys (text: string): string {
|
||||
let result = '';
|
||||
let quoted = false;
|
||||
let escaped = false;
|
||||
const containers: Array<{ object: boolean; key: boolean; }> = [];
|
||||
for (let index = 0; index < text.length; index++) {
|
||||
const character = text[index]!;
|
||||
if (!quoted) {
|
||||
const container = containers[containers.length - 1];
|
||||
if (container?.object && container.key && character === 'n' && /^name(?=\s*:\s*")/.test(text.slice(index))) {
|
||||
result += '"name"';
|
||||
index += 'name'.length - 1;
|
||||
container.key = false;
|
||||
continue;
|
||||
}
|
||||
if (character === '{') containers.push({ object: true, key: true });
|
||||
else if (character === '[') containers.push({ object: false, key: false });
|
||||
else if (character === '}' || character === ']') containers.pop();
|
||||
else if (character === ',' && container?.object) container.key = true;
|
||||
else if (!/\s/.test(character) && container?.object) container.key = false;
|
||||
}
|
||||
result += character;
|
||||
if (quoted) {
|
||||
if (escaped) escaped = false;
|
||||
else if (character === '\\') escaped = true;
|
||||
else if (character === '"') quoted = false;
|
||||
} else if (character === '"') {
|
||||
quoted = true;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function rejectDuplicateSuccessFields (text: string): void {
|
||||
const seen = new Set<string>();
|
||||
let depth = 0;
|
||||
for (let index = 0; index < text.length; index++) {
|
||||
const character = text[index];
|
||||
if (character === '{' || character === '[') depth++;
|
||||
else if (character === '}' || character === ']') depth--;
|
||||
else if (character === '"') {
|
||||
const start = index;
|
||||
let escaped = false;
|
||||
for (index++; index < text.length; index++) {
|
||||
const current = text[index];
|
||||
if (escaped) escaped = false;
|
||||
else if (current === '\\') escaped = true;
|
||||
else if (current === '"') break;
|
||||
}
|
||||
let next = index + 1;
|
||||
while (/\s/.test(text[next] ?? '') && next < text.length) next++;
|
||||
if (depth !== 1 || text[next] !== ':') continue;
|
||||
const field: unknown = JSON.parse(text.slice(start, index + 1));
|
||||
if (typeof field !== 'string' || !SUCCESS_FIELDS.includes(field)) continue;
|
||||
if (seen.has(field)) throw new Error('QQ空间响应包含重复状态字段');
|
||||
seen.add(field);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// FormSender's response is a data callback inside one fixed, passive HTML shell.
|
||||
// Consume its observed domain setup as text; never run the returned JavaScript.
|
||||
const FORM_SENDER_HTML = /^(?:<!doctype\s+html>\s*)?<html>\s*<head>\s*<meta\s+http-equiv="content-type"\s+content="text\/html;\s*charset=utf-8"\s*\/?>\s*<\/head>\s*<body>\s*<script\s+type="text\/javascript">\s*([\s\S]*?)\s*<\/script>\s*<\/body>\s*<\/html>$/i;
|
||||
const DOMAIN_SETUP = 'document\\s*\\.\\s*domain\\s*=\\s*"h5\\.qzone\\.qq\\.com"\\s*;\\s*';
|
||||
const CALLBACK_SETUP = 'cb\\s*=\\s*frameElement\\s*\\.\\s*callback\\s*;\\s*';
|
||||
const DOMAIN_TRY_SETUP = new RegExp(
|
||||
'^var\\s+cb\\s*;\\s*try\\s*\\{\\s*' + DOMAIN_SETUP + CALLBACK_SETUP +
|
||||
'\\}\\s*catch\\s*\\(\\s*e\\s*\\)\\s*\\{\\s*try\\s*\\{\\s*' + DOMAIN_SETUP + CALLBACK_SETUP +
|
||||
'\\}\\s*catch\\s*\\(\\s*e\\s*\\)\\s*\\{\\s*' + DOMAIN_SETUP + CALLBACK_SETUP + '\\}\\s*\\}\\s*'
|
||||
);
|
||||
const DOMAIN_ONLY_SETUP = new RegExp('^' + DOMAIN_SETUP);
|
||||
|
||||
function unwrapFormSenderHtml (text: string): string | undefined {
|
||||
const html = FORM_SENDER_HTML.exec(text);
|
||||
if (!html) return undefined;
|
||||
const script = html[1]!.trim();
|
||||
const setup = DOMAIN_TRY_SETUP.exec(script) ?? DOMAIN_ONLY_SETUP.exec(script);
|
||||
if (!setup) throw new Error('QQ空间响应脚本包裹格式异常');
|
||||
const callback = script.slice(setup[0].length).trim();
|
||||
if (!/^frameElement\.callback\s*\(/.test(callback)) throw new Error('QQ空间响应脚本包裹格式异常');
|
||||
return callback;
|
||||
}
|
||||
|
||||
/** Parse data only: no script evaluation and no first-brace/last-brace extraction. */
|
||||
export function parseQzoneWebResponse (text: string, requireCode = false): Record<string, unknown> {
|
||||
if (typeof text !== 'string' || text.length > 8 * 1024 * 1024) throw new Error('QQ空间响应格式异常');
|
||||
let payload = text.trim();
|
||||
const formSender = unwrapFormSenderHtml(payload);
|
||||
if (formSender !== undefined) payload = formSender;
|
||||
// Preserve the original single-script and bare callback envelopes as well.
|
||||
const script = /^<script>\s*([\s\S]*?)\s*<\/script>$/i.exec(payload);
|
||||
if (script) {
|
||||
payload = script[1]!.trim();
|
||||
if (!/^(?:_Callback|callback|_preloadCallback|back|frameElement\.callback)\s*\(/.test(payload)) throw new Error('QQ空间响应脚本包裹格式异常');
|
||||
} else if (payload.endsWith('</script>') && payload.startsWith('frameElement.callback')) payload = payload.slice(0, -9).trim();
|
||||
if (!payload.startsWith('{')) {
|
||||
const callback = /^(?:_Callback|callback|_preloadCallback|back|frameElement\.callback)\s*\(\s*([\s\S]*)\s*\)\s*;?\s*$/.exec(payload);
|
||||
if (!callback) throw new Error('QQ空间响应格式异常');
|
||||
payload = callback[1]!.trim();
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
payload = normalizeNameStringKeys(payload);
|
||||
rejectDuplicateSuccessFields(payload);
|
||||
parsed = JSON.parse(payload);
|
||||
} catch {
|
||||
throw new Error('QQ空间响应JSON格式异常');
|
||||
}
|
||||
const response = object(parsed);
|
||||
if (!response) throw new Error('QQ空间响应必须是对象');
|
||||
assertSuccess(response, requireCode);
|
||||
return response;
|
||||
}
|
||||
|
||||
export function parseQzoneProfile (response: Record<string, unknown>): QzoneProfile {
|
||||
if (!object(response)) throw new Error('QQ空间资料响应格式异常');
|
||||
assertSuccess(response, true);
|
||||
const data = object(response['data']);
|
||||
if (!data || typeof data['spacename'] !== 'string' || typeof data['desc'] !== 'string') {
|
||||
throw new Error('QQ空间资料响应不完整');
|
||||
}
|
||||
return { name: data['spacename'], description: data['desc'] };
|
||||
}
|
||||
|
||||
export function buildQzoneProfileBody (selfUin: string, profile: QzoneProfileUpdate): string {
|
||||
assertUin(selfUin);
|
||||
const fields = object(profile);
|
||||
if (!fields || Object.keys(fields).some(key => key !== 'name' && key !== 'description')) throw new Error('QQ空间资料参数无效');
|
||||
const params = new URLSearchParams({ uin: selfUin, pageindex: '3', fupdate: '1' });
|
||||
let bitmap = 0;
|
||||
for (const [field, wireName, bit] of [['name', 'spacename', 2048], ['description', 'desc', 4096]] as const) {
|
||||
const value = fields[field];
|
||||
if (value === undefined) continue;
|
||||
if (typeof value !== 'string' || value.length > MAX_PROFILE_LENGTH) throw new Error('QQ空间名称或说明必须是8192字以内的文本');
|
||||
params.set(wireName, value.replaceAll('\r', ''));
|
||||
bitmap |= bit;
|
||||
}
|
||||
if (bitmap === 0) throw new Error('至少提供空间名称或说明');
|
||||
params.set('mb', String(bitmap));
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
export function normalizeQzoneRight (ugcRight: number, targetUins?: string[]): { right: QzoneUgcRight; targetUins: string[]; } {
|
||||
const rights = [1, 4, 16, 64, 128];
|
||||
if (typeof ugcRight !== 'number' || !rights.includes(ugcRight)) throw new Error('ugc_right仅支持1、4、16、64、128');
|
||||
if (targetUins !== undefined && !Array.isArray(targetUins)) throw new Error('target_uins必须为QQ号数组');
|
||||
const targets: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const uin of targetUins ?? []) {
|
||||
assertUin(uin);
|
||||
if (!seen.has(uin)) {
|
||||
targets.push(uin);
|
||||
seen.add(uin);
|
||||
}
|
||||
}
|
||||
if ((ugcRight === 16 || ugcRight === 128) && targets.length === 0) throw new Error('ugc_right为16或128时target_uins不能为空');
|
||||
return { right: ugcRight as QzoneUgcRight, targetUins: targets };
|
||||
}
|
||||
|
||||
function wireText (value: unknown, fallback: string): string {
|
||||
if (value === undefined) return fallback;
|
||||
if (typeof value !== 'string') throw new Error('QQ空间说说重建字段格式异常');
|
||||
return value;
|
||||
}
|
||||
|
||||
function wireInteger (value: unknown, fallback: string, minimum = 0, allowEmpty = false): string {
|
||||
if (value === undefined) return fallback;
|
||||
if (allowEmpty && value === '') return '';
|
||||
if ((typeof value !== 'number' || !Number.isSafeInteger(value)) && (typeof value !== 'string' || !/^\d+$/.test(value))) {
|
||||
throw new Error('QQ空间说说重建数值无效');
|
||||
}
|
||||
const number = Number(value);
|
||||
if (!Number.isSafeInteger(number) || number < minimum) throw new Error('QQ空间说说重建数值无效');
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function firstPresent (first: unknown, second: unknown): unknown {
|
||||
return first === undefined ? second : first;
|
||||
}
|
||||
|
||||
function hasMediaValue (value: unknown): boolean {
|
||||
if (value === undefined || value === null || value === false || value === 0 || value === '' || value === '0') return false;
|
||||
if (Array.isArray(value)) return value.length > 0;
|
||||
const record = object(value);
|
||||
return record ? Object.keys(record).length > 0 : true;
|
||||
}
|
||||
|
||||
function hasObservedEmptyForwardContent (detail: Record<string, unknown>): boolean {
|
||||
if (detail['rt_tid'] !== '' || detail['rt_uin'] !== 0 || detail['rt_source'] !== 0) return false;
|
||||
const content = object(detail['rt_con']);
|
||||
if (!content) return false;
|
||||
const keys = Object.keys(content);
|
||||
return keys.length === 2 && keys.includes('conlist') && keys.includes('content') &&
|
||||
content['conlist'] === null && content['content'] === '';
|
||||
}
|
||||
|
||||
function assertSupportedMedia (detail: Record<string, unknown>): void {
|
||||
for (const field of [
|
||||
'video', 'videos', 'video_info', 'video_url', 'videoid', 'video_id', 'vid',
|
||||
'music', 'music_info', 'audio', 'voice', 'voice_info',
|
||||
'rt_tid', 'rt_uin', 'rt_con', 'rt_source', 'forward', 'forward_info', 'forward_tid',
|
||||
'origin', 'origin_tid', 'origin_feed', 'cell_origin',
|
||||
]) {
|
||||
// The legacy detail CGI supplies this exact empty object for ordinary text and image posts.
|
||||
if (field === 'rt_con' && hasObservedEmptyForwardContent(detail)) continue;
|
||||
if (hasMediaValue(detail[field])) throw new Error('该说说包含暂不支持完整重建的媒体或转发内容');
|
||||
}
|
||||
for (const field of ['appid', 'app_id']) {
|
||||
if (detail[field] !== undefined && detail[field] !== 311 && detail[field] !== '311') throw new Error('该动态不是可重建的说说');
|
||||
}
|
||||
if (wireText(detail['special_url'], '') !== '') throw new Error('暂不支持修改含特殊分享内容的说说权限');
|
||||
}
|
||||
|
||||
function pictureBo (picture: Record<string, unknown>): string | undefined {
|
||||
for (const key of ['smallurl', 'url1', 'url2', 'url3']) {
|
||||
const value = picture[key];
|
||||
if (value === undefined || value === '') continue;
|
||||
if (typeof value !== 'string') throw new Error('QQ空间图片地址元数据无效');
|
||||
const matches = [...value.matchAll(/[?&]bo=([^&#]*)/g)];
|
||||
if (matches.length > 1) throw new Error('QQ空间图片包含歧义元数据');
|
||||
if (matches.length === 0) continue;
|
||||
try {
|
||||
const decoded = decodeURIComponent(matches[0]![1]!);
|
||||
if (!decoded || /[\t\r\n]/.test(decoded)) throw new Error('Invalid picture metadata');
|
||||
return decoded;
|
||||
} catch {
|
||||
throw new Error('QQ空间图片元数据无法完整重建');
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function rebuildContent (detail: Record<string, unknown>): string {
|
||||
const conlist = detail['conlist'];
|
||||
if (conlist !== undefined && conlist !== null) {
|
||||
if (!Array.isArray(conlist)) throw new Error('QQ空间说说正文分段格式异常');
|
||||
if (conlist.length > 0) {
|
||||
return conlist.map((value) => {
|
||||
const part = object(value);
|
||||
if (!part || typeof part['con'] !== 'string') throw new Error('QQ空间说说正文分段不完整');
|
||||
return part['con'];
|
||||
}).join('');
|
||||
}
|
||||
}
|
||||
if (typeof detail['content'] !== 'string') throw new Error('QQ空间说说缺少完整正文');
|
||||
return detail['content'];
|
||||
}
|
||||
|
||||
/** Permission updates resubmit a whole post, so unsupported or partial data must fail before POST. */
|
||||
export function buildQzoneRightBody (
|
||||
detail: Record<string, unknown>,
|
||||
selfUin: string,
|
||||
tid: string,
|
||||
ugcRight: number,
|
||||
targetUins?: string[]
|
||||
): string {
|
||||
assertUin(selfUin);
|
||||
assertIdentity(tid);
|
||||
const source = object(detail);
|
||||
if (!source || source['tid'] !== tid) throw new Error('QQ空间详情与请求的说说标识不匹配');
|
||||
const owner = source['uin'];
|
||||
if ((typeof owner !== 'string' && !(typeof owner === 'number' && Number.isSafeInteger(owner))) || String(owner) !== selfUin) {
|
||||
throw new Error('只能修改当前账号自己的说说权限');
|
||||
}
|
||||
if (SUCCESS_FIELDS.some(field => Object.prototype.hasOwnProperty.call(source, field))) assertSuccess(source, false);
|
||||
const permission = normalizeQzoneRight(ugcRight, targetUins);
|
||||
assertSupportedMedia(source);
|
||||
const pics = source['pic'] ?? [];
|
||||
if (!Array.isArray(pics)) throw new Error('QQ空间说说图片列表格式异常');
|
||||
const richType = wireInteger(source['richtype'], pics.length ? '1' : '', 0, true);
|
||||
if (!['', '0', '1'].includes(richType)) throw new Error('该说说的媒体类型暂不支持完整重建');
|
||||
if ((pics.length > 0 && richType !== '1') || (pics.length === 0 && richType === '1')) throw new Error('QQ空间说说图片信息不完整');
|
||||
const richValues: string[] = [];
|
||||
const boValues: Array<string | undefined> = [];
|
||||
for (const value of pics) {
|
||||
const picture = object(value);
|
||||
const pictureId = picture?.['pic_id'];
|
||||
if (!picture || typeof pictureId !== 'string' || !pictureId || /[\t\r\n]/.test(pictureId)) throw new Error('QQ空间说说图片标识不完整');
|
||||
const parts = pictureId.split(',');
|
||||
const albumId = parts[1];
|
||||
const lloc = parts[2];
|
||||
if (!albumId?.trim() || !lloc?.trim()) throw new Error('QQ空间说说图片信息无法完整重建');
|
||||
// 22 is the observed legacy image default; existing image dimensions cannot be guessed.
|
||||
const pictureType = wireInteger(firstPresent(picture['pictype'], picture['type']), '22');
|
||||
const originalHeight = firstPresent(picture['height'], picture['b_height']);
|
||||
const originalWidth = firstPresent(picture['width'], picture['b_width']);
|
||||
if (originalHeight === undefined || originalWidth === undefined) throw new Error('QQ空间说说图片尺寸不完整');
|
||||
const height = wireInteger(originalHeight, '', 1);
|
||||
const width = wireInteger(originalWidth, '', 1);
|
||||
richValues.push(`,${albumId},${lloc},${lloc},${pictureType},${height},${width},,0,0`);
|
||||
boValues.push(pictureBo(picture));
|
||||
}
|
||||
if (boValues.some(value => value !== undefined) && boValues.some(value => value === undefined)) throw new Error('QQ空间图片元数据数量不完整');
|
||||
const boGroup = boValues.every(value => value !== undefined) ? boValues.join(',') : '';
|
||||
const originalRichValue = wireText(source['richval'], '');
|
||||
if (richValues.length === 0 && originalRichValue !== '') throw new Error('QQ空间说说包含无法完整重建的媒体数据');
|
||||
const subtype = wireInteger(firstPresent(source['t1_subtype'], source['subrichtype']), richValues.length ? '1' : '', 0, true);
|
||||
// Subtype 2 was observed on plain text, without either rich-type field or pictures.
|
||||
const observedPlainTextSubtype = subtype === '2' && hasObservedEmptyForwardContent(source) &&
|
||||
pics.length === 0 && source['richtype'] === undefined && source['subrichtype'] === undefined;
|
||||
if (!['', '0', '1'].includes(subtype) && !observedPlainTextSubtype) throw new Error('该说说的媒体子类型暂不支持完整重建');
|
||||
const sign = wireInteger(source['to_sign'], '0');
|
||||
if (sign !== '0' && sign !== '1') throw new Error('QQ空间说说同步标记无效');
|
||||
const rightId = wireText(source['ugcright_id'], tid);
|
||||
assertIdentity(rightId);
|
||||
const params = new URLSearchParams({
|
||||
syn_tweet_verson: '1',
|
||||
tid,
|
||||
paramstr: '1',
|
||||
pic_template: wireText(source['pic_template'], ''),
|
||||
richtype: richType,
|
||||
richval: richValues.join('\t'),
|
||||
special_url: '',
|
||||
subrichtype: subtype,
|
||||
pic_bo: boGroup ? `${boGroup}\t${boGroup}` : '',
|
||||
con: rebuildContent(source),
|
||||
feedversion: wireInteger(source['feedversion'], '1', 1),
|
||||
ver: wireInteger(source['ver'], '1', 1),
|
||||
ugc_right: String(permission.right),
|
||||
to_sign: sign,
|
||||
ugcright_id: rightId,
|
||||
hostuin: selfUin,
|
||||
code_version: wireInteger(source['code_version'], '1', 1),
|
||||
format: 'fs',
|
||||
qzreferrer: `https://user.qzone.qq.com/${selfUin}`,
|
||||
});
|
||||
if (permission.right === 16 || permission.right === 128) params.set('allow_uins', permission.targetUins.join('|'));
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
export function buildQzoneBanBody (selfUin: string, targetUin: string, enable: boolean): string {
|
||||
assertUin(selfUin);
|
||||
assertUin(targetUin);
|
||||
if (typeof enable !== 'boolean') throw new Error('空间黑名单状态必须是布尔值');
|
||||
return new URLSearchParams({
|
||||
uin: selfUin,
|
||||
act_uin: targetUin,
|
||||
action: enable ? '1' : '2',
|
||||
fupdate: '1',
|
||||
qzreferrer: `https://user.qzone.qq.com/${selfUin}/main`,
|
||||
}).toString();
|
||||
}
|
||||
@@ -139,23 +139,36 @@ export interface QzonePublishResponse {
|
||||
code?: number;
|
||||
tid?: string;
|
||||
t1_tid?: string;
|
||||
t1_time?: string | number;
|
||||
t1_ntime?: string | number;
|
||||
now?: number;
|
||||
message?: string;
|
||||
msg?: string;
|
||||
}
|
||||
|
||||
export function parseQzonePublishTime (value: unknown): number {
|
||||
if (value === undefined || value === null) return 0;
|
||||
const time = (typeof value === 'number' || (typeof value === 'string' && /^\d+$/.test(value))) ? Number(value) : NaN;
|
||||
if (!Number.isSafeInteger(time) || time < 0) throw new Error('QQ空间发表时间无效,结果需查询确认,勿自动重试');
|
||||
return time;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析发表说说接口返回的 JSON, 提取 tid
|
||||
*/
|
||||
export function parseQzonePublishResponse (json: QzonePublishResponse): { tid: string; } {
|
||||
const subcode = json.subcode ?? json.code;
|
||||
if (subcode !== undefined && subcode !== 0) {
|
||||
throw new Error(json.message || json.msg || `QQ空间发说说失败, subcode=${subcode}`);
|
||||
export function parseQzonePublishResponse (json: QzonePublishResponse): { tid: string; time: number; } {
|
||||
for (const code of [json.subcode, json.code]) {
|
||||
if (code !== undefined && code !== 0) throw new Error('QQ空间发说说失败,服务端拒绝请求');
|
||||
}
|
||||
const tid = json.t1_tid || json.tid;
|
||||
if (!tid) {
|
||||
throw new Error('QQ空间发说说失败, 未返回tid');
|
||||
}
|
||||
return { tid };
|
||||
// t1_ntime is Unix seconds; current CGI t1_time is a display label such as "22:08".
|
||||
const displayTime = typeof json.t1_time === 'string' && /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(json.t1_time);
|
||||
const time = json.t1_ntime ?? (displayTime ? json.now : json.t1_time ?? json.now);
|
||||
// SL uses zero when no machine-readable creation time is supplied, never the local clock.
|
||||
return { tid, time: parseQzonePublishTime(time) };
|
||||
}
|
||||
|
||||
export interface QzoneDeleteParams {
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
NTQQFlashApi,
|
||||
NTQQOnlineApi,
|
||||
NTQQDatabaseApi,
|
||||
NTQQQzoneApi,
|
||||
NTQQQzonePublicApi,
|
||||
} from '@/napcat-core/apis';
|
||||
import { NTQQCollectionApi } from '@/napcat-core/apis/collection';
|
||||
@@ -172,6 +173,7 @@ export class NapCatCore {
|
||||
FlashApi: new NTQQFlashApi(this.context, this),
|
||||
OnlineApi: new NTQQOnlineApi(this.context, this),
|
||||
DatabaseApi: new NTQQDatabaseApi(this.context, this),
|
||||
QzoneApi: new NTQQQzoneApi(this.context, this),
|
||||
QzonePublicApi: new NTQQQzonePublicApi(this.context, this),
|
||||
};
|
||||
container.bind(NapCatCore).toConstantValue(this);
|
||||
@@ -384,5 +386,6 @@ export interface StableNTApiWrapper {
|
||||
FlashApi: NTQQFlashApi,
|
||||
OnlineApi: NTQQOnlineApi,
|
||||
DatabaseApi: NTQQDatabaseApi,
|
||||
QzoneApi: NTQQQzoneApi,
|
||||
QzonePublicApi: NTQQQzonePublicApi,
|
||||
}
|
||||
@@ -20,6 +20,7 @@
|
||||
"@sinclair/typebox": "^0.34.38",
|
||||
"compressing": "^1.10.1",
|
||||
"file-type": "^21.0.0",
|
||||
"htmlparser2": "10.0.0",
|
||||
"inversify": "^7.10.4",
|
||||
"json5": "^2.2.3",
|
||||
"napcat-common": "workspace:*",
|
||||
|
||||
Reference in new issue
Block a user