fix(music): align QQ stream requests and surface provider failures

This commit is contained in:
TIANYAO ZHANG committed 2026-11-18 18:16:47 +08:00
1 parent 8ec3dcc405
commit fbc12aa11b
5 files changed
+204 -54

No files matched your search

+25
View File
@@ -2,6 +2,31 @@ import { describe, it, expect, vi } from "vitest";
import { mapKugouSong, mapKugouSongs, mapKugouAlbums, mapKugouPlaylist, mapKugouPlaylists, krcToLrc, KugouProvider } from "./kugou.js";
import { parseLyrics } from "./netease.js";
describe("KugouProvider.getSongUrl failure diagnostics", () => {
const id = "b3a52a7a958bf0aed0efbba2e9a818b7|32100650|966846";
const provider = () => {
const p = new KugouProvider();
p.setCookie("dfid=test-device");
return { bot: p, http: p as unknown as { request: (...args: unknown[]) => Promise<unknown> } };
};
it("distinguishes a provider verification response from a missing stream", async () => {
const { bot, http } = provider();
vi.spyOn(http, "request").mockResolvedValue({ status: 0, errcode: 20028 });
await expect(bot.getSongUrl(id)).rejects.toMatchObject({
failure: { code: "provider_verification_required", upstream: { code: 20028 } },
});
});
it("carries only safe status fields on a failed HTTP request", async () => {
const { bot, http } = provider();
vi.spyOn(http, "request").mockRejectedValue({ response: { status: 503, data: { hidden: "test-cookie" } } });
await expect(bot.getSongUrl(id)).rejects.toMatchObject({
failure: { code: "upstream_request_failed", upstream: { httpStatus: 503 } },
});
});
});
describe("mapKugouSongs", () => {
it("maps the mobile-search song shape to a Song with platform 'kugou'", () => {
// Shape captured live from mobilecdn.kugou.com/api/v3/search/song.
+31 -11
View File
@@ -11,15 +11,14 @@
* VERIFICATION NOTE: search and lyrics were verified live during development.
* The play-URL endpoint (`/v5/url`) is gated by Kugou's risk-control and may
* return `errcode 20028 "本次请求需要验证"` from flagged (datacenter) IPs even
* for free songs; on such hosts a logged-in session (QR login below) and/or a
* residential IP is required. QR login and VIP audio could not be verified in
* the build environment.
* for free songs. Surface explicit verification requests to the operator.
*/
import { normalizeCookie } from "./cookie-normalize.js";
import axios, { type AxiosInstance } from "axios";
import crypto from "node:crypto";
import zlib from "node:zlib";
import { parseLyrics } from "./netease.js";
import { playbackRequestFailure, SongUrlUnavailable } from "./provider.js";
import type {
Album,
AuthStatus,
@@ -663,8 +662,9 @@ export class KugouProvider implements MusicProvider {
if (!hash) return null;
await this.ensureDfid();
const q = quality ? (QUALITY_MAP[quality] ?? this.quality) : this.quality;
let data;
try {
const data = await this.request({
data = await this.request({
method: "GET",
url: "/v5/url",
xRouter: "trackercdn.kugou.com",
@@ -692,14 +692,34 @@ export class KugouProvider implements MusicProvider {
clientver: 11430,
},
});
const urls: string[] = Array.isArray(data?.url) ? data.url : [];
const backup: string[] = Array.isArray(data?.backupUrl) ? data.backupUrl : [];
const url = urls.find(Boolean) || backup.find(Boolean);
if (!url) return null;
return { url };
} catch {
return null;
} catch (error) {
const responseData = (error as { response?: { data?: unknown } } | null)?.response?.data;
throw this.kugouVerificationFailure(songId, responseData) ?? playbackRequestFailure(this.platform, songId, error);
}
const verification = this.kugouVerificationFailure(songId, data);
if (verification) throw verification;
const urls: unknown[] = Array.isArray(data?.url) ? data.url : [];
const backup: unknown[] = Array.isArray(data?.backupUrl) ? data.backupUrl : [];
const url = [...urls, ...backup].find((value): value is string => typeof value === "string" && value.length > 0);
if (url) return { url };
throw new SongUrlUnavailable({
platform: this.platform,
songId,
code: "unknown",
message: "酷狗未返回播放地址",
});
}
private kugouVerificationFailure(songId: string, data: unknown): SongUrlUnavailable | undefined {
const code = (data as { errcode?: unknown } | null)?.errcode;
if (code !== 20028 && code !== "20028") return;
return new SongUrlUnavailable({
platform: this.platform,
songId,
code: "provider_verification_required",
message: "酷狗要求完成验证(20028),请在酷狗检查账号状态",
upstream: { code: 20028 },
});
}
async getSongDetail(songId: string): Promise<Song | null> {
+29 -1
View File
@@ -62,6 +62,10 @@ export type PlayFailureCode =
| "no_copyright"
/** The track exists, but this quality level is not ours to serve. */
| "quality_denied"
/** The upstream HTTP request failed or the expected API was unreachable. */
| "upstream_request_failed"
/** The music service explicitly asked the user to complete verification. */
| "provider_verification_required"
/** 200 with no URL and nothing that explains why. */
| "unknown";
@@ -71,7 +75,7 @@ export interface PlayFailure {
code: PlayFailureCode;
/** One short line in the UI's language — safe to render as-is. */
message: string;
/** Raw upstream fields (fee / payed / code / level). Logs only, never shown. */
/** Selected non-secret diagnostic fields. Logs only, never shown directly. */
upstream?: Record<string, unknown>;
}
@@ -92,6 +96,30 @@ export class SongUrlUnavailable extends Error {
}
}
/** Preserve typed status for troubleshooting without forwarding request or response data. */
export function playbackRequestFailure(
platform: "qq" | "kugou",
songId: string,
error: unknown,
): SongUrlUnavailable {
const raw = error as { code?: unknown; response?: { status?: unknown } } | null;
const status = raw?.response?.status;
const httpStatus = typeof status === "number" && Number.isInteger(status) && status >= 100 && status < 600
? status : undefined;
const name = platform === "qq" ? "QQ 音乐 API" : "酷狗";
const message = httpStatus ? `${name}播放请求失败(HTTP ${httpStatus})`
: raw?.code === "ECONNREFUSED" && platform === "qq" ? "无法连接 QQ 音乐 API,请检查服务启动与端口"
: raw?.code === "ECONNABORTED" || raw?.code === "ETIMEDOUT" ? `${name}播放请求超时`
: `${name}播放请求失败,请检查服务与网络连接`;
return new SongUrlUnavailable({
platform,
songId,
code: "upstream_request_failed",
message,
upstream: httpStatus ? { httpStatus } : undefined,
});
}
export function toPlayFailure(platform: string, songId: string, error: unknown): PlayFailure {
if (error instanceof SongUrlUnavailable) return error.failure;
if (error instanceof RiskControlError) {
+41
View File
@@ -10,6 +10,47 @@ vi.mock("axios", () => ({
import { mapQqAlbums, mapQqArtists, mapQqSongs, parseQqTrial, QQMusicProvider } from "./qq.js";
describe("QQ playback sidecar contract", () => {
beforeEach(() => {
mockGet.mockReset();
});
it("maps app playback quality to the installed sidecar format", async () => {
const provider = new QQMusicProvider("http://127.0.0.1:3200");
provider.setQuality("lossless");
mockGet.mockResolvedValue({ data: { data: { playUrl: { abc: { url: "https://example.com/audio" } } } } });
await expect(provider.getSongUrl("abc")).resolves.toMatchObject({ url: "https://example.com/audio" });
expect(mockGet).toHaveBeenLastCalledWith("/getMusicPlay", { params: expect.objectContaining({ songmid: "abc", quality: "flac" }) });
});
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" } } } } } });
mockGet.mockResolvedValueOnce({ data: { data: { playUrl: { abc: { url: "https://example.com/audio" } } } } });
await expect(provider.getSongUrl("12345")).resolves.toMatchObject({ url: "https://example.com/audio" });
expect(mockGet).toHaveBeenNthCalledWith(1, "/getSongInfo", { params: expect.objectContaining({ songid: "12345" }) });
expect(mockGet).toHaveBeenNthCalledWith(2, "/getMusicPlay", { params: expect.objectContaining({ songmid: "abc" }) });
});
it("separates a broken sidecar from a track without a URL", async () => {
const provider = new QQMusicProvider("http://127.0.0.1:3200");
mockGet.mockRejectedValue({ response: { status: 502, data: { hidden: "test-cookie" } } });
await expect(provider.getSongUrl("abc")).rejects.toMatchObject({
failure: { code: "upstream_request_failed", upstream: { httpStatus: 502 } },
});
expect(mockGet).toHaveBeenCalledOnce();
});
it("keeps tracks playable at a supported fallback quality during batch preflight", async () => {
const provider = new QQMusicProvider("http://127.0.0.1:3200");
provider.setQuality("exhigh");
mockGet.mockResolvedValueOnce({ data: { data: { playUrl: { abc: { url: "https://example.com/audio1" }, def: { url: "" } } } } });
mockGet.mockResolvedValueOnce({ data: { data: { playUrl: { def: { url: "https://example.com/audio2" } } } } });
await expect(provider.getPlayableSongIds(["abc", "def"])).resolves.toEqual(new Set(["abc", "def"]));
expect(mockGet).toHaveBeenNthCalledWith(2, "/getMusicPlay", { params: expect.objectContaining({ songmid: "def", quality: "128" }) });
});
});
describe("QQ adapter", () => {
it("mapQqSongs maps QQMusicApi-style song entries", () => {
const out = mapQqSongs([
+78 -42
View File
@@ -1,5 +1,6 @@
import { normalizeCookie } from "./cookie-normalize.js";
import axios, { type AxiosInstance } from "axios";
import { playbackRequestFailure, SongUrlUnavailable } from "./provider.js";
import type {
MusicProvider,
Song,
@@ -45,6 +46,25 @@ const qqFavApi = axios.create({
headers: { referer: "https://y.qq.com/" },
});
/** Formats supported by @sansenjian/qq-music-api 2.4's /getMusicPlay route. */
function qqPlaybackQuality(quality: string): string {
switch (quality) {
case "exhigh": return "320";
case "lossless":
case "hires":
case "jymaster": return "flac";
case "320":
case "flac":
case "ape":
case "m4a": return quality;
default: return "128";
}
}
function isQqNumericId(value: string): boolean {
return /^\d+$/.test(value);
}
/** 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 {
@@ -196,6 +216,13 @@ export class QQMusicProvider implements MusicProvider {
return this.quality;
}
getFallbackQualities(): string[] {
const primary = qqPlaybackQuality(this.quality);
if (primary === "flac" || primary === "ape") return ["320", "128"];
if (primary === "320") return ["128"];
return [];
}
private get cookieParams(): Record<string, string> {
return this.cookie ? { cookie: this.cookie } : {};
}
@@ -358,25 +385,29 @@ export class QQMusicProvider implements MusicProvider {
}
async getSongUrl(songId: string, quality?: string): Promise<SongUrlResult | null> {
try {
const res = await this.api.get("/getMusicPlay", {
params: { songmid: songId, quality: quality ?? this.quality, ...this.cookieParams },
});
const playUrl = res.data?.data?.playUrl?.[songId];
if (playUrl?.url) return { url: playUrl.url, trialDuration: parseQqTrial(playUrl) };
} catch {
// try with songid
try {
const res = await this.api.get("/getMusicPlay", {
params: { songid: songId, quality: quality ?? this.quality, ...this.cookieParams },
});
const playUrl = res.data?.data?.playUrl?.[songId];
if (playUrl?.url) return { url: playUrl.url, trialDuration: parseQqTrial(playUrl) };
} catch {
// ignore
}
// 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" });
}
return null;
const format = qqPlaybackQuality(quality ?? this.quality);
let response;
try {
response = await this.api.get("/getMusicPlay", {
params: { songmid, quality: format, ...this.cookieParams },
});
} catch (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})`,
});
}
/**
@@ -390,37 +421,39 @@ export class QQMusicProvider implements MusicProvider {
* the URL well under typical 8KB query-string limits and to keep per-
* request latency bounded (~2-3s per 100 mids).
*
* Returns:
* - non-null Set: authoritative result. Empty Set means all songs are
* unplayable; non-empty means filter to those mids.
* - null: every chunk failed. Caller should fall back to sequential
* retry rather than treating as "all unplayable".
* Check lower configured formats for MIDs missing from the first result.
* Return null on an incomplete response so the caller can resolve tracks
* normally instead of discarding unverified entries.
*/
async getPlayableSongIds(songIds: string[]): Promise<Set<string> | null> {
if (songIds.length === 0) return new Set();
if (songIds.some(isQqNumericId)) return null;
const CHUNK = 100; // ~14 chars/mid * 100 + commas ≈ 1.5KB
const playable = new Set<string>();
let allChunksFailed = true;
const formats = [qqPlaybackQuality(this.quality), ...this.getFallbackQualities()];
for (let i = 0; i < songIds.length; i += CHUNK) {
const slice = songIds.slice(i, i + CHUNK);
try {
const res = await this.api.get("/getMusicPlay", {
params: { songmid: slice.join(","), quality: this.quality, ...this.cookieParams },
});
const playUrlMap: Record<string, { url?: string }> | undefined =
res.data?.data?.playUrl;
if (!playUrlMap) continue; // chunk-level failure, try next
allChunksFailed = false;
for (const [mid, info] of Object.entries(playUrlMap)) {
if (info?.url) playable.add(mid);
let remaining = songIds.slice(i, i + CHUNK);
for (const quality of formats) {
try {
const res = await this.api.get("/getMusicPlay", {
params: { songmid: remaining.join(","), quality, ...this.cookieParams },
});
const playUrlMap: Record<string, { url?: string }> | undefined = res.data?.data?.playUrl;
if (!playUrlMap || remaining.some(mid => !Object.hasOwn(playUrlMap, mid))) return null;
remaining = remaining.filter(mid => {
const url = playUrlMap[mid]?.url;
if (typeof url !== "string" || !url) return true;
playable.add(mid);
return false;
});
if (remaining.length === 0) break;
} catch {
return null;
}
} catch {
// chunk-level failure — keep going so a transient error on one
// chunk doesn't poison the whole batch.
}
}
return allChunksFailed ? null : playable;
return playable;
}
async getSongDetail(songId: string): Promise<Song | null> {
@@ -432,9 +465,9 @@ export class QQMusicProvider implements MusicProvider {
// stub is sufficient to let /play-by-id and /add-by-id flows succeed.
try {
const res = await this.api.get("/getSongInfo", {
params: { songmid: songId, ...this.cookieParams },
params: { ...(isQqNumericId(songId) ? { songid: songId } : { songmid: songId }), ...this.cookieParams },
});
const s = res.data?.response?.data;
const s = res.data?.response?.songinfo?.data ?? res.data?.response?.data;
if (s && s.track_info) {
const t = s.track_info;
return {
@@ -483,11 +516,14 @@ export class QQMusicProvider implements MusicProvider {
* caller can fall back to the minimal stub. */
private async fetchSongDetailViaMusicu(songId: string): Promise<Song | null> {
try {
const numeric = isQqNumericId(songId);
const song_id = Number(songId);
if (numeric && (!Number.isSafeInteger(song_id) || song_id < 1)) return null;
const reqData = JSON.stringify({
req_0: {
module: "music.pf_song_detail_svr",
method: "get_song_detail_yqq",
param: { song_mid: songId, song_type: 0 },
param: { ...(numeric ? { song_id } : { song_mid: songId }), song_type: 0 },
},
});
const res = await qqMusicuApi.get("/cgi-bin/musicu.fcg", {