mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-02 19:02:50 +08:00
fix(qq): verify sidecar ports and validate batch playback results
This commit is contained in:
1 parent
5c2a9468bd
commit
e5470b6b78
11 files changed
+224
-36
No files matched your search
@@ -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` 字段就是实际监听端口。
|
||||
|
||||
@@ -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");
|
||||
|
||||
+4
-4
@@ -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<AudioQualityConfig>;
|
||||
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),
|
||||
|
||||
+1
-1
@@ -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");
|
||||
|
||||
@@ -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" });
|
||||
|
||||
@@ -34,6 +34,38 @@ export function isApiPortFree(port: number): Promise<boolean> {
|
||||
});
|
||||
}
|
||||
|
||||
/** Identify the QQ wrapper without credentials or a request to QQ upstream. */
|
||||
export async function isQqMusicApi(port: number): Promise<boolean> {
|
||||
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<void> {
|
||||
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!);
|
||||
|
||||
@@ -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("<html>WebUI</html>", { 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"];
|
||||
|
||||
+22
-1
@@ -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<void> | null = null;
|
||||
let stopping: Promise<void> = 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<void> {
|
||||
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" });
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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}播放请求失败,请检查服务与网络连接`;
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
+82
-26
@@ -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<string, { url?: unknown }>;
|
||||
};
|
||||
}
|
||||
|
||||
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<string> {
|
||||
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<SongUrlResult | null> {
|
||||
// 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<QqPlaybackReply>("/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<string>();
|
||||
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<QqPlaybackReply>("/getMusicPlay", {
|
||||
params: { songmid: remaining.join(","), quality, resType: "full", ...this.cookieParams },
|
||||
});
|
||||
const playUrlMap: Record<string, { url?: string }> | 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;
|
||||
|
||||
Reference in new issue
Block a user