From e5470b6b78f23502f0d2e8751ec6ae631595dc6f Mon Sep 17 00:00:00 2001 From: TIANYAO ZHANG <88520881+ZHANGTIANYAO1@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:24:17 +0800 Subject: [PATCH] fix(qq): verify sidecar ports and validate batch playback results --- README.md | 2 +- src/data/config.test.ts | 7 ++ src/data/config.ts | 8 +- src/index.ts | 2 +- src/music/api-server-runtime.test.ts | 11 ++- src/music/api-server-runtime.ts | 37 ++++++++- src/music/api-server.test.ts | 14 +++- src/music/api-server.ts | 23 +++++- src/music/provider.ts | 1 + src/music/qq.test.ts | 47 ++++++++++++ src/music/qq.ts | 108 ++++++++++++++++++++------- 11 files changed, 224 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 137c0c7..f4b528d 100644 --- a/README.md +++ b/README.md @@ -927,7 +927,7 @@ A:使用 `!move <频道名>` 命令,或在设置页面创建机器人时指 A:可以。在设置页面创建多个实例,分别连接不同的 TS 服务器或频道。 **Q:端口 3200 被占用?** -A:QQ 音乐 API 启动时会监听 `config.json` 里的 `qqMusicApiPort`(默认 **3200**),客户端也用同一个端口发请求,二者始终一致。如果之前的进程还在运行,程序会自动复用。如需改端口,改 `qqMusicApiPort` 后重启即可;如需重启可手动结束 `node` 进程。 +A:QQ 音乐 API 使用 `config.json` 的 `qqMusicApiPort`(默认 **3200**)。程序会验证已在该端口监听的 QQ 音乐 API,再复用它。如果端口被 WebUI、端口转发或其他服务占用,请将 `qqMusicApiPort` 改为另一个空闲端口并重启。 **Q:日志里 `baseURL` 是 3200,但 QQ API 实际监听在 3300?(二维码不弹)** A:这是**旧版本**(或过期的 `latest` Docker 镜像)才有的问题:早期实现用的上游包默认端口是 3300,而客户端 `baseURL` 已经是 3200,两边对不上,取二维码时就 `ECONNREFUSED 127.0.0.1:3200`。当前版本已把内嵌 QQ 音乐 API **强制绑定到 `qqMusicApiPort`(默认 3200)**,并在启动前把上游包读取的 `PORT` 环境变量对齐到该端口,二者不可能再错位。修复方法:**拉取最新镜像并重启**(`docker compose pull && docker compose up -d`),或用 `npm ci && npm run build` 更新到最新代码。启动后可在日志里确认那行 `QQ Music API started`,其 `port` 字段就是实际监听端口。 diff --git a/src/data/config.test.ts b/src/data/config.test.ts index 62deb52..d7c1cb6 100644 --- a/src/data/config.test.ts +++ b/src/data/config.test.ts @@ -274,6 +274,13 @@ describe("config", () => { }); }); + it("retains a numeric QQ bitrate saved by an older settings API", () => { + const dir = makeTmpDir(); + const path = join(dir, "config.json"); + writeFileSync(path, JSON.stringify({ audioQuality: { qq: 128 } })); + expect(loadConfig(path).audioQuality.qq).toBe("128"); + }); + it("creates config file on save", () => { const dir = makeTmpDir(); const path = join(dir, "sub", "config.json"); diff --git a/src/data/config.ts b/src/data/config.ts index 4cc7507..724fe2b 100755 --- a/src/data/config.ts +++ b/src/data/config.ts @@ -469,15 +469,15 @@ export function loadConfig(path: string): BotConfig { ? (rawDefault as GateableProvider) : null; - // audioQuality → per-provider strings; each field falls back to its default - // when missing/blank/non-string (a hand-edited/legacy config must never smuggle - // a non-string past the gate — the value is fed straight to provider.setQuality). + // Normalize the two numeric QQ bitrates accepted by older settings APIs. + // Other missing, blank or non-string qualities use provider defaults. const partialAq = (partial.audioQuality ?? {}) as Partial; const coerceQuality = (v: unknown, fallback: string): string => typeof v === "string" && v.trim() ? v : fallback; + const qqQuality: unknown = partialAq.qq; const audioQuality: AudioQualityConfig = { netease: coerceQuality(partialAq.netease, defaults.audioQuality.netease), - qq: coerceQuality(partialAq.qq, defaults.audioQuality.qq), + qq: qqQuality === 128 || qqQuality === 320 ? String(qqQuality) : coerceQuality(qqQuality, defaults.audioQuality.qq), bilibili: coerceQuality(partialAq.bilibili, defaults.audioQuality.bilibili), kugou: coerceQuality(partialAq.kugou, defaults.audioQuality.kugou), jellyfin: coerceQuality(partialAq.jellyfin, defaults.audioQuality.jellyfin), diff --git a/src/index.ts b/src/index.ts index 03bd050..796831f 100755 --- a/src/index.ts +++ b/src/index.ts @@ -88,7 +88,7 @@ async function main() { const qqSession = (process.env.QQ_MUSIC_MANAGED_SESSION ?? "1") === "1" && isProviderEnabled(config, "qq") ? new QQManagedSession(createQqLoginClient(), qqStore, logger) : undefined; - const qqProvider = new QQMusicProvider(apiServer.getQQMusicBaseUrl(), qqSession); + const qqProvider = new QQMusicProvider(apiServer.getQQMusicBaseUrl(), qqSession, apiServer.assertQqMusicApiPort); if (!qqSession) { try { const cookie = cookieStore.load("qq"); diff --git a/src/music/api-server-runtime.test.ts b/src/music/api-server-runtime.test.ts index 5d90f92..d60d7a5 100644 --- a/src/music/api-server-runtime.test.ts +++ b/src/music/api-server-runtime.test.ts @@ -34,7 +34,7 @@ describe("embedded API runtime", () => { listen = vi.fn(() => { queueMicrotask(() => { server.listening = true; server.emit("listening"); }); return server; }); state.qqExport = { listen }; }); - afterEach(() => { if (previousPort === undefined) delete process.env.PORT; else process.env.PORT = previousPort; }); + afterEach(() => { if (previousPort === undefined) delete process.env.PORT; else process.env.PORT = previousPort; vi.restoreAllMocks(); }); it("binds NetEase to loopback/configured port without version checks and waits for listening", async () => { let ready = false; @@ -74,9 +74,18 @@ describe("embedded API runtime", () => { }); it("reuses a legacy module that auto-started on import without a duplicate listen", async () => { state.portFree = false; + vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify({ data: { message: "no songmid" } }), { + status: 400, headers: { "Content-Type": "application/json" }, + })); expect(await startEmbeddedApi("qq", 39217)).toEqual({ server: null }); expect(listen).not.toHaveBeenCalled(); }); + it("reports an occupied port if another service bound it during import", async () => { + state.portFree = false; + vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("not QQ", { status: 200 })); + await expect(startEmbeddedApi("qq", 39217)).rejects.toMatchObject({ code: "EADDRINUSE" }); + expect(listen).not.toHaveBeenCalled(); + }); it("never reflects arbitrary startup message, stack or code values", () => { expect(getSafeApiStartupError({ message: "synthetic-credential", stack: "synthetic-credential", code: "synthetic-credential" })).toEqual({ category: "startup" }); expect(getSafeApiStartupError({ code: "ERR_REQUIRE_ESM", message: "synthetic-credential" })).toEqual({ category: "esm", code: "ERR_REQUIRE_ESM" }); diff --git a/src/music/api-server-runtime.ts b/src/music/api-server-runtime.ts index 351cb78..ca4cf7e 100644 --- a/src/music/api-server-runtime.ts +++ b/src/music/api-server-runtime.ts @@ -34,6 +34,38 @@ export function isApiPortFree(port: number): Promise { }); } +/** Identify the QQ wrapper without credentials or a request to QQ upstream. */ +export async function isQqMusicApi(port: number): Promise { + try { + const response = await fetch(`http://127.0.0.1:${port}/getMusicPlay`, { + redirect: "manual", + signal: AbortSignal.timeout(2_000), + }); + if (response.status !== 400 || !response.headers.get("content-type")?.includes("application/json")) { + await response.body?.cancel(); + return false; + } + const reader = response.body?.getReader(); + if (!reader) return false; + const buffer = Buffer.alloc(1024); + let length = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + if (length + value.length > buffer.length) return false; + buffer.set(value, length); + length += value.length; + } + } finally { + await reader.cancel(); + } + return JSON.parse(buffer.toString("utf8", 0, length))?.data?.message === "no songmid"; + } catch { + return false; + } +} + function waitForListening(server: Server): Promise { if (server.listening) return Promise.resolve(); return new Promise((resolve, reject) => { @@ -80,7 +112,10 @@ export async function startEmbeddedApi(provider: ApiProvider, port: number): Pro if (!app || typeof app.listen !== "function") throw new Error("QQ API did not expose a Koa app"); // Historical packages listened during import. Their listener remains // owned by this child and closes when the child exits. - if (!(await isApiPortFree(port))) return { server: null }; + if (!(await isApiPortFree(port))) { + if (await isQqMusicApi(port)) return { server: null }; + throw Object.assign(new Error("QQ Music API port is occupied"), { code: "EADDRINUSE" }); + } server = app.listen(port, "127.0.0.1"); } await waitForListening(server!); diff --git a/src/music/api-server.test.ts b/src/music/api-server.test.ts index 3f7b038..ae89cac 100644 --- a/src/music/api-server.test.ts +++ b/src/music/api-server.test.ts @@ -67,7 +67,7 @@ describe("embedded API child lifecycle", () => { logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() } as unknown as Logger; manager = createApiServerManager(options, logger); }); - afterEach(async () => { manager.stop(); await flush(); vi.useRealTimers(); }); + afterEach(async () => { manager.stop(); await flush(); vi.useRealTimers(); vi.restoreAllMocks(); }); it("isolates both APIs with ignored stdio, configured ports and IPC", async () => { await manager.start(); @@ -87,10 +87,22 @@ describe("embedded API child lifecycle", () => { manager = createApiServerManager({ ...options, neteaseEnabled: false, qqEnabled: false }, logger); await manager.start(); expect(state.probes).toHaveLength(0); expect(state.fork).not.toHaveBeenCalled(); state.portFree = false; + vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify({ data: { message: "no songmid" } }), { + status: 400, headers: { "Content-Type": "application/json" }, + })); manager = createApiServerManager({ ...options, neteaseEnabled: false }, logger); await manager.start(); expect(state.fork).not.toHaveBeenCalled(); expect(logger.info).toHaveBeenCalledWith({ port: 39217 }, expect.stringContaining("reusing")); }); + it("detects the wrong service on the QQ music port without assuming every occupied port is reusable", async () => { + state.portFree = false; + vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("WebUI", { status: 200 })); + manager = createApiServerManager({ ...options, neteaseEnabled: false }, logger); + await manager.start(); + expect(state.fork).not.toHaveBeenCalled(); + expect(logger.error).toHaveBeenCalledWith({ provider: "qq", port: 39217, category: "port-in-use" }, expect.stringContaining("qqMusicApiPort")); + expect(() => manager.assertQqMusicApiPort()).toThrow(expect.objectContaining({ code: "QQ_API_PORT_CONFLICT" })); + }); it("inherits tsx loader arguments without unrelated parent runner flags", async () => { const previous = process.execArgv; process.execArgv = ["--require", "C:\\app\\node_modules\\tsx\\dist\\preflight.cjs", "--import", "file:///app/node_modules/tsx/dist/loader.mjs", "--eval", "synthetic-evaluation", "--conditions", "vitest", "--input-type=module", "--inspect"]; diff --git a/src/music/api-server.ts b/src/music/api-server.ts index c8a6cc8..90accc3 100644 --- a/src/music/api-server.ts +++ b/src/music/api-server.ts @@ -1,6 +1,6 @@ import { fork, type ChildProcess } from "node:child_process"; import type { Logger } from "../logger.js"; -import { getSafeApiStartupError, isApiPortFree, safeApiErrorCode, type ApiProvider, type SafeApiStartupError } from "./api-server-runtime.js"; +import { getSafeApiStartupError, isApiPortFree, isQqMusicApi, safeApiErrorCode, type ApiProvider, type SafeApiStartupError } from "./api-server-runtime.js"; export interface ApiServerOptions { neteasePort: number; @@ -13,6 +13,7 @@ export interface ApiServerManager { stop(): void; getNeteaseBaseUrl(): string; getQQMusicBaseUrl(): string; + assertQqMusicApiPort(): void; } export function describeQqApiStartupError(err: unknown): string | null { @@ -52,6 +53,13 @@ export function createApiServerManager(options: ApiServerOptions, logger: Logger let generation = 0; let starting: Promise | null = null; let stopping: Promise = Promise.resolve(); + let qqPortConflict = false; + + function reportQqPortConflict(port: number): void { + qqPortConflict = true; + logger.error({ provider: "qq", port, category: "port-in-use" }, + "QQ Music API port is occupied by another service. Free the port or set qqMusicApiPort to an unused port and restart."); + } function launch(provider: ApiProvider, port: number, launchGeneration: number): Promise { const source = import.meta.url.endsWith(".ts"); @@ -158,16 +166,24 @@ export function createApiServerManager(options: ApiServerOptions, logger: Logger const free = await isApiPortFree(port); if (startGeneration !== generation) return; if (!free) { + if (provider === "qq") { + const compatible = await isQqMusicApi(port); + if (startGeneration !== generation) return; + if (!compatible) { reportQqPortConflict(port); continue; } + qqPortConflict = false; + } logger.info({ port }, `${provider === "netease" ? "NetEase" : "QQ Music"} API port already in use — reusing existing instance`); continue; } await launch(provider, port, startGeneration); if (startGeneration !== generation) return; + if (provider === "qq") qqPortConflict = false; logger.info({ port }, `${name} API started`); } catch (error) { if (startGeneration !== generation) return; const details = error instanceof StartupFailure ? error.details : getSafeApiStartupError(error); if (details.category === "cancelled") return; + if (provider === "qq" && details.category === "port-in-use") { reportQqPortConflict(port); continue; } const hint = provider === "qq" ? describeQqApiStartupError(details.category === "esm" ? { code: "ERR_REQUIRE_ESM" } : details.category === "node-engine" ? { code: "EBADENGINE" } : {}) : null; logger.error({ provider, port, ...details }, hint ? `QQ Music API failed to start — ${hint}. QQ features (search/play/login) will be unavailable until fixed; port ${port} is down.` : `Failed to start ${name} API`); } @@ -191,5 +207,10 @@ export function createApiServerManager(options: ApiServerOptions, logger: Logger }, getNeteaseBaseUrl: () => `http://127.0.0.1:${options.neteasePort}`, getQQMusicBaseUrl: () => `http://127.0.0.1:${options.qqMusicPort}`, + assertQqMusicApiPort(): void { + if (qqPortConflict) { + throw Object.assign(new Error("QQ Music API port conflict; check qqMusicApiPort"), { code: "QQ_API_PORT_CONFLICT" }); + } + }, }; } diff --git a/src/music/provider.ts b/src/music/provider.ts index ab92f72..6278b7e 100644 --- a/src/music/provider.ts +++ b/src/music/provider.ts @@ -108,6 +108,7 @@ export function playbackRequestFailure( ? status : undefined; const name = platform === "qq" ? "QQ 音乐 API" : "酷狗"; const message = httpStatus ? `${name}播放请求失败(HTTP ${httpStatus})` + : raw?.code === "QQ_API_PORT_CONFLICT" && platform === "qq" ? "QQ 音乐 API 端口被其他服务占用,请检查 qqMusicApiPort" : raw?.code === "ECONNREFUSED" && platform === "qq" ? "无法连接 QQ 音乐 API,请检查服务启动与端口" : raw?.code === "ECONNABORTED" || raw?.code === "ETIMEDOUT" ? `${name}播放请求超时` : `${name}播放请求失败,请检查服务与网络连接`; diff --git a/src/music/qq.test.ts b/src/music/qq.test.ts index 04913ca..b9006e5 100644 --- a/src/music/qq.test.ts +++ b/src/music/qq.test.ts @@ -23,6 +23,15 @@ describe("QQ playback sidecar contract", () => { expect(mockGet).toHaveBeenLastCalledWith("/getMusicPlay", { params: expect.objectContaining({ songmid: "abc", quality: "flac" }) }); }); + it.each([320, "320"])("accepts QQ quality %j from the settings API", async (quality) => { + const provider = new QQMusicProvider("http://127.0.0.1:3200"); + provider.setQuality(quality); + expect(provider.getQuality()).toBe("320"); + mockGet.mockResolvedValue({ data: { data: { playUrl: { abc: { url: "https://example.com/audio" } } } } }); + await provider.getSongUrl("abc"); + expect(mockGet).toHaveBeenLastCalledWith("/getMusicPlay", { params: expect.objectContaining({ quality: "320" }) }); + }); + it("resolves a numeric ID to a MID before asking the sidecar for playback", async () => { const provider = new QQMusicProvider("http://127.0.0.1:3200"); mockGet.mockResolvedValueOnce({ data: { response: { songinfo: { data: { track_info: { mid: "abc" } } } } } }); @@ -49,6 +58,44 @@ describe("QQ playback sidecar contract", () => { await expect(provider.getPlayableSongIds(["abc", "def"])).resolves.toEqual(new Set(["abc", "def"])); expect(mockGet).toHaveBeenNthCalledWith(2, "/getMusicPlay", { params: expect.objectContaining({ songmid: "def", quality: "128" }) }); }); + + it.each([{}, { abc: { url: "" } }, { abc: { url: "" }, def: { url: 17 } }])( + "does not interpret incomplete or unconfirmed HTTP 200 play maps as unavailable", + async (playUrl) => { + const provider = new QQMusicProvider("http://127.0.0.1:3200"); + provider.setQuality("128"); + mockGet.mockResolvedValue({ status: 200, data: { data: { playUrl } } }); + await expect(provider.getPlayableSongIds(["abc", "def"])).resolves.toBeNull(); + }, + ); + + it("does not treat an upstream error inside HTTP 200 as a final no-URL result", async () => { + const provider = new QQMusicProvider("http://127.0.0.1:3200"); + provider.setQuality("128"); + mockGet.mockResolvedValue({ status: 200, data: { data: { code: 0, req_0: { code: 502 }, playUrl: { abc: { url: "" } } } } }); + await expect(provider.getPlayableSongIds(["abc"])).resolves.toBeNull(); + await expect(provider.getSongUrl("abc")).rejects.toMatchObject({ + failure: { code: "upstream_request_failed", upstream: { code: 502 } }, + }); + }); + + it("accepts a fully confirmed no-play result and a numeric HTTP envelope success code", async () => { + const provider = new QQMusicProvider("http://127.0.0.1:3200"); + provider.setQuality("128"); + mockGet.mockResolvedValue({ status: 200, data: { code: 200, data: { + code: "0", req_0: { code: 0, data: { midurlinfo: [{ songmid: "abc", purl: "" }] } }, playUrl: { abc: { url: "" } }, + } } }); + await expect(provider.getPlayableSongIds(["abc"])).resolves.toEqual(new Set()); + }); + + it("stops playback before sending a request when the sidecar port is occupied by another service", async () => { + const guard = () => { throw Object.assign(new Error("QQ sidecar port conflict"), { code: "QQ_API_PORT_CONFLICT" }); }; + const provider = new QQMusicProvider("http://127.0.0.1:3200", undefined, guard); + await expect(provider.getSongUrl("abc")).rejects.toMatchObject({ + failure: { code: "upstream_request_failed", message: expect.stringContaining("端口") }, + }); + expect(mockGet).not.toHaveBeenCalled(); + }); }); describe("QQ adapter", () => { diff --git a/src/music/qq.ts b/src/music/qq.ts index a6609ad..77eb6d9 100644 --- a/src/music/qq.ts +++ b/src/music/qq.ts @@ -65,6 +65,34 @@ function isQqNumericId(value: string): boolean { return /^\d+$/.test(value); } +interface QqPlaybackReply { + code?: unknown; + data?: { + code?: unknown; + req_0?: { code?: unknown; data?: { midurlinfo?: unknown } }; + playUrl?: Record; + }; +} + +function readQqCode(raw: unknown): number | undefined { + const code = typeof raw === "string" && /^-?\d+$/.test(raw) ? Number(raw) : raw; + return typeof code === "number" && Number.isSafeInteger(code) ? code : undefined; +} + +function qqPlaybackErrorCode(reply?: QqPlaybackReply): number | undefined { + const wrapper = readQqCode(reply?.code); + if (wrapper !== undefined && wrapper !== 0 && wrapper !== 200) return wrapper; + return [readQqCode(reply?.data?.code), readQqCode(reply?.data?.req_0?.code)] + .find(code => code !== undefined && code !== 0); +} + +function confirmedQqMisses(reply: QqPlaybackReply): Set { + const request = reply.data?.req_0; + const rows = request?.data?.midurlinfo; + if (readQqCode(request?.code) !== 0 || !Array.isArray(rows)) return new Set(); + return new Set(rows.flatMap(row => typeof row?.songmid === "string" && row.purl === "" && !row.vkey ? [row.songmid] : [])); +} + /** True when a search_type=2 album search entry really belongs to this singer. * QQ fills singerMID for most albums; older entries only carry singer_list. */ function isArtistAlbum(a: any, artistId: string): boolean { @@ -192,24 +220,34 @@ function computeGtk(pSkey: string): number { export class QQMusicProvider implements MusicProvider { readonly platform = "qq" as const; - private api: AxiosInstance; + private readonly sidecar: AxiosInstance; private legacyCookie = ""; private quality = "exhigh"; private radarPage = 1; - constructor(baseUrl: string, readonly managedSession?: QQManagedSession) { - this.api = axios.create({ + constructor( + baseUrl: string, + readonly managedSession?: QQManagedSession, + private readonly assertSidecarPort?: () => void, + ) { + this.sidecar = axios.create({ baseURL: baseUrl, timeout: 10000, }); } + private get api(): AxiosInstance { + this.assertSidecarPort?.(); + return this.sidecar; + } + private get cookie(): string { return this.managedSession?.getCookie() ?? this.legacyCookie; } - setQuality(quality: string): void { - this.quality = quality; + setQuality(quality: string | number): void { + if (quality === 128 || quality === 320) this.quality = String(quality); + else if (typeof quality === "string" && quality.trim()) this.quality = quality.trim(); } getQuality(): string { @@ -385,25 +423,33 @@ export class QQMusicProvider implements MusicProvider { } async getSongUrl(songId: string, quality?: string): Promise { - // The sidecar's play endpoint only reads songmid. Old queues and explicit - // ID requests can carry numeric IDs, which the metadata endpoint resolves. - const songmid = isQqNumericId(songId) ? (await this.getSongDetail(songId))?.id : songId; - if (!songmid || isQqNumericId(songmid)) { - throw new SongUrlUnavailable({ platform: this.platform, songId, code: "unknown", message: "QQ 音乐未返回该曲目的 MID" }); - } const format = qqPlaybackQuality(quality ?? this.quality); - let response; try { - response = await this.api.get("/getMusicPlay", { - params: { songmid, quality: format, ...this.cookieParams }, + const api = this.api; + // The play endpoint only accepts MIDs. Old queues and explicit ID + // requests can carry a numeric ID, which the metadata endpoint resolves. + const songmid = isQqNumericId(songId) ? (await this.getSongDetail(songId))?.id : songId; + if (!songmid || isQqNumericId(songmid)) { + throw new SongUrlUnavailable({ platform: this.platform, songId, code: "unknown", message: "QQ 音乐未返回该曲目的 MID" }); + } + const response = await api.get("/getMusicPlay", { + params: { songmid, quality: format, resType: "full", ...this.cookieParams }, }); + const code = qqPlaybackErrorCode(response.data); + if (code !== undefined) { + throw new SongUrlUnavailable({ + platform: this.platform, songId, code: "upstream_request_failed", message: `QQ 音乐播放请求返回错误(${code})`, + upstream: { code }, + }); + } + const playUrl = response.data?.data?.playUrl?.[songmid]; + if (typeof playUrl?.url === "string" && playUrl.url) { + return { url: playUrl.url, trialDuration: parseQqTrial(playUrl) }; + } } catch (error) { + if (error instanceof SongUrlUnavailable) throw error; throw playbackRequestFailure(this.platform, songId, error); } - const playUrl = response.data?.data?.playUrl?.[songmid]; - if (typeof playUrl?.url === "string" && playUrl.url) { - return { url: playUrl.url, trialDuration: parseQqTrial(playUrl) }; - } throw new SongUrlUnavailable({ platform: this.platform, songId, code: "unknown", message: `QQ 音乐未返回播放地址(${format})`, @@ -434,16 +480,25 @@ export class QQMusicProvider implements MusicProvider { const formats = [qqPlaybackQuality(this.quality), ...this.getFallbackQualities()]; for (let i = 0; i < songIds.length; i += CHUNK) { let remaining = songIds.slice(i, i + CHUNK); + const unconfirmed = new Set(); for (const quality of formats) { try { - const res = await this.api.get("/getMusicPlay", { - params: { songmid: remaining.join(","), quality, ...this.cookieParams }, + const res = await this.api.get("/getMusicPlay", { + params: { songmid: remaining.join(","), quality, resType: "full", ...this.cookieParams }, }); - const playUrlMap: Record | undefined = res.data?.data?.playUrl; - if (!playUrlMap || remaining.some(mid => !Object.hasOwn(playUrlMap, mid))) return null; + const playUrlMap = res.data?.data?.playUrl; + if (qqPlaybackErrorCode(res.data) !== undefined || !playUrlMap || + remaining.some(mid => !Object.hasOwn(playUrlMap, mid) || typeof playUrlMap[mid]?.url !== "string")) return null; + // The wrapper synthesizes empty URLs even if Tencent omitted a MID + // or returned a transient error. Require an upstream row before + // interpreting a blank URL as negative evidence for that quality. + const confirmed = confirmedQqMisses(res.data); remaining = remaining.filter(mid => { - const url = playUrlMap[mid]?.url; - if (typeof url !== "string" || !url) return true; + if (!playUrlMap[mid].url) { + if (!confirmed.has(mid)) unconfirmed.add(mid); + return true; + } + unconfirmed.delete(mid); playable.add(mid); return false; }); @@ -452,6 +507,7 @@ export class QQMusicProvider implements MusicProvider { return null; } } + if (unconfirmed.size > 0) return null; } return playable; } @@ -878,11 +934,11 @@ export class QQMusicProvider implements MusicProvider { * A view of the same provider logged in as another account (#164 follow-up): * a web user's own QQ 音乐 login instead of the bot's shared one. * - * The per-user view points at the SAME API server (`this.api.defaults.baseURL`) + * The per-user view points at the same guarded API server * — only the cookie differs, so the shared login keeps its own instance. */ withCookie(cookie: string): QQMusicProvider { - const view = new QQMusicProvider(this.api.defaults.baseURL ?? ""); + const view = new QQMusicProvider(this.sidecar.defaults.baseURL ?? "", undefined, this.assertSidecarPort); view.quality = this.quality; view.setCookie(cookie); return view;