diff --git a/packages/bridge/src/qq-port-probe.ts b/packages/bridge/src/qq-port-probe.ts index 3ab83e5b..be25eefd 100644 --- a/packages/bridge/src/qq-port-probe.ts +++ b/packages/bridge/src/qq-port-probe.ts @@ -1,5 +1,6 @@ import { exec } from 'child_process'; import net from 'net'; +import http from 'http'; import https from 'https'; import { promisify } from 'util'; @@ -126,51 +127,61 @@ interface PtloginUin { nickname?: string; } -async function fetchPtlogin(port: number): Promise { +/** + * One `pt_get_uins` call. Returns the parsed account array (possibly empty — + * an EMPTY array is a real answer: "0 accounts", NOT an error) or `null` when + * the port could not be reached / the body was not a usable pt_get_uins + * response (connect refused, timeout, unparseable). Callers MUST distinguish + * the two: `[]` feeds the logged-in/out decision, `null` means "network + * problem, no answer" and should fall through to the deep-link fallback. + */ +async function fetchPtlogin(port: number, useHttps: boolean): Promise { return new Promise((resolve) => { - const url = `https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`; + const protocol = useHttps ? 'https' : 'http'; + const url = `${protocol}://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`; - const req = https.get( - url, - { - headers: { - Host: 'localhost.ptlogin2.qq.com', - Referer: 'https://xui.ptlogin2.qq.com/', - Cookie: 'pt_local_token=0', - }, - rejectUnauthorized: false, // 忽略本地自签证书报错 - timeout: CONNECTION_TIMEOUT_MS, - }, - (res) => { - let text = ''; - res.on('data', (chunk) => { text += chunk.toString(); }); - res.on('end', () => { - try { - // 100% 复刻 Python 切片逻辑:获取两个方括号中间的字符串,再包装成数组 - const inner = text.split('[')[1].split(']')[0]; - const data = JSON.parse('[' + inner + ']') as PtloginUin[]; - resolve(data); - } catch { - resolve([]); - } - }); - } - ); + const headers = { + Host: 'localhost.ptlogin2.qq.com', + Referer: 'https://xui.ptlogin2.qq.com/', + Cookie: 'pt_local_token=0', + }; - req.on('error', () => resolve([])); + const handleResponse = (res: http.IncomingMessage) => { + let text = ''; + res.on('data', (chunk) => { text += chunk.toString(); }); + res.on('end', () => { + try { + const inner = text.split('[')[1].split(']')[0]; + const data = JSON.parse('[' + inner + ']') as PtloginUin[]; + resolve(data); + } catch { + resolve(null); + } + }); + }; + + const req = useHttps + ? https.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false }, handleResponse) + : http.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS }, handleResponse); + + req.on('error', () => resolve(null)); req.on('timeout', () => { req.destroy(); - resolve([]); + resolve(null); }); }); } async function tryPtloginMethod(port: number): Promise { - // 抽象的 QQNT - const res1 = await fetchPtlogin(port); - const res2 = await fetchPtlogin(port); + const useHttps = port % 2 !== 0; - const target = res1.length < res2.length ? res1 : res2; + const res1 = await fetchPtlogin(port, useHttps); + const res2 = await fetchPtlogin(port, useHttps); + + if (res1 === null && res2 === null) return 'fallback'; + + const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null); + const target = usable.reduce((a, b) => (a.length <= b.length ? a : b)); if (target.length === 1) { const account = target[0]; @@ -182,8 +193,6 @@ async function tryPtloginMethod(port: number): Promise PT_PORTS.includes(p)); + const matchedOddPorts = ports.filter(p => ODD_PT_PORTS.includes(p)); + const matchedEvenPorts = ports.filter(p => EVEN_PT_PORTS.includes(p)); - if (matchedPtPorts.length > 0) { - for (const port of matchedPtPorts) { + let ptPortsToTry: number[] = []; + if (matchedOddPorts.length > 0) { + ptPortsToTry = matchedOddPorts; + } else if (matchedEvenPorts.length > 0) { + ptPortsToTry = matchedEvenPorts; + } + + if (ptPortsToTry.length > 0) { + for (const port of ptPortsToTry) { const ptResult = await tryPtloginMethod(port); if (ptResult !== 'fallback') { return ptResult; diff --git a/packages/protocol/src/web/qzone.ts b/packages/protocol/src/web/qzone.ts index ce014369..57c6a139 100644 --- a/packages/protocol/src/web/qzone.ts +++ b/packages/protocol/src/web/qzone.ts @@ -308,11 +308,86 @@ export function mapMsgList(data: RawMsgListResponse): QzoneMsgListResult { }; } +interface MsgListRoute { + url: string; + headers: Record; +} + +/** Legacy route (default): h5.qzone.qq.com → taotao.qzone.qq.com. */ +function legacyMsgListRoute( + cookieObject: Record, + targetUin: string, + pos: number, + num: number, + bkn: string, +): MsgListRoute { + const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_msglist_v6?${new URLSearchParams( + { + uin: targetUin, + ftype: '0', + sort: '0', + pos: String(pos), + num: String(num), + replynum: '100', + g_tk: bkn, + callback: '_preloadCallback', + code_version: '1', + format: 'jsonp', + need_private_comment: '1', + }, + ).toString()}`; + return { url, headers: { Cookie: cookieToString(cookieObject) } }; +} + +/** + * Fallback route: user.qzone.qq.com → taotao.qq.com (NOT taotao.qzone.qq.com). + * Live captures show this pair is not subject to the `-10000` rate-limit the + * legacy route can hit. + */ +function userMsgListRoute( + cookieObject: Record, + targetUin: string, + pos: number, + num: number, + bkn: string, +): MsgListRoute { + const url = `https://user.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6?${new URLSearchParams( + { + uin: targetUin, + ftype: '0', + sort: '0', + pos: String(pos), + num: String(num), + g_tk: bkn, + code_version: '1', + format: 'json', + }, + ).toString()}`; + return { + url, + headers: { + Cookie: cookieToString(cookieObject), + Referer: `https://user.qzone.qq.com/${targetUin}`, + }, + }; +} + +async function requestMsgList( + route: MsgListRoute, + targetUin: string, +): Promise<{ data: RawMsgListResponse; text: string }> { + const text = await RequestUtil.HttpGetText(route.url, 'GET', '', route.headers); + log.trace('getQzoneMsgList raw body (uin=%s): %s', targetUin, text); + return { data: parseQzoneJson(text), text }; +} + /** * Fetch a 说说 (Qzone emotion/feed) list via the taotao.qzone.qq.com web * API, proxied through h5.qzone.qq.com — the same cookie/g_tk plumbing the * group-album helper uses. Defaults to the bot's own space; `targetUin` - * can name any space the bot may view. + * can name any space the bot may view. On a `-10000` rate-limit from that + * route, retries once via the user.qzone.qq.com route (see + * {@link userMsgListRoute}). * * Errors PROPAGATE: a transport failure, a non-zero `code` (Qzone's own * error envelope, e.g. auth/permission), or a missing `msglist` (the body @@ -333,27 +408,20 @@ export async function getQzoneMsgList( } const bkn = getBknFromCookie(cookieObject); - const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_msglist_v6?${new URLSearchParams( - { - uin: targetUin, - ftype: '0', - sort: '0', - pos: String(pos), - num: String(num), - replynum: '100', - g_tk: bkn, - callback: '_preloadCallback', - code_version: '1', - format: 'jsonp', - need_private_comment: '1', - }, - ).toString()}`; + let { data, text } = await requestMsgList( + legacyMsgListRoute(cookieObject, targetUin, pos, num, bkn), + targetUin, + ); - const text = await RequestUtil.HttpGetText(url, 'GET', '', { - Cookie: cookieToString(cookieObject), - }); - log.trace('getQzoneMsgList raw body (uin=%s): %s', targetUin, text); - const data = parseQzoneJson(text); + // -10000「使用人数过多」is route-specific to the legacy gateway; retry once + // via the user.qzone.qq.com route, which live captures show is not limited. + if (data.code === -10000) { + log.warn('getQzoneMsgList: legacy route rate-limited (uin=%s), retrying via user.qzone route', targetUin); + ({ data, text } = await requestMsgList( + userMsgListRoute(cookieObject, targetUin, pos, num, bkn), + targetUin, + )); + } if (typeof data.code === 'number' && data.code !== 0) { log.warn('getQzoneMsgList: non-zero code (uin=%s) code=%d msg=%s', targetUin, data.code, data.message); diff --git a/packages/protocol/tests/web/qzone.test.ts b/packages/protocol/tests/web/qzone.test.ts index 83790511..39018654 100644 --- a/packages/protocol/tests/web/qzone.test.ts +++ b/packages/protocol/tests/web/qzone.test.ts @@ -93,6 +93,31 @@ describe('qzone / getQzoneMsgList (HTTP layer)', () => { expect(q.get('format')).toBe('jsonp'); }); + it('retries via the user.qzone.qq.com route on a -10000 rate-limit', async () => { + const spy = vi + .spyOn(RequestUtil, 'HttpGetText') + .mockResolvedValueOnce('{"code":-10000,"message":"使用人数过多,请稍后再试"}') + .mockResolvedValueOnce( + '{"code":0,"total":1,"msglist":[{"tid":"T1","content":"hi","created_time":1700000000,"cmtnum":0,"secret":0,"pic":[]}]}', + ); + + const out = await getQzoneMsgList(cookies, '10000', 0, 20); + + expect(out).toEqual({ + total: 1, + msglist: [{ tid: 'T1', content: 'hi', time: 1700000000, comment_num: 0, is_private: false, images: [] }], + }); + + expect(spy).toHaveBeenCalledTimes(2); + expect(spy.mock.calls[0]![0]).toContain('https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/'); + const [retryUrl, , , retryHeaders] = spy.mock.calls[1]!; + expect(retryUrl).toContain('https://user.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6?'); + expect((retryHeaders as Record).Referer).toBe('https://user.qzone.qq.com/10000'); + const q = new URLSearchParams((retryUrl as string).split('?')[1]); + expect(q.get('format')).toBe('json'); + expect(q.get('g_tk')).toBe(expectedGtk); + }); + it('returns an empty list (not a throw) for a genuinely empty space', async () => { // The throw-on-auth-failure contract hinges on distinguishing a missing // msglist (cookie failure → throw) from an empty msglist (no 说说 → []).