Merge pull request #185 from jiayuLian/feat/play-url-retry

fix(playback): 播放前重试 + 降音质,不再动不动「无法播放(区域/版权限制)」
This commit is contained in:
TIANYAO ZHANG authored and GitHub committed 2026-11-18 17:04:48 +08:00
commit c72cd4f233
10 files changed
+1333 -70

No files matched your search

+17
View File
@@ -475,6 +475,7 @@ function makeResolveCtx(opts: {
config: {},
id: "bot1",
voteSkipUsers: new Set<string>(),
queue: { current: vi.fn(() => null) },
autoPaused: false,
currentSourceIsSpotify: opts.currentSourceIsSpotify ?? false,
effectiveDuration: undefined,
@@ -501,6 +502,22 @@ function spotifySong() {
};
}
it("does not start a track whose URL resolved after the queue was cleared", async () => {
const player = makePlayer();
const song = { ...spotifySong(), platform: "netease" };
const ctx = makeResolveCtx({ controller: makeController(), player, url: "" });
ctx.queue.current.mockReturnValue(song);
ctx.getProviderFor.mockReturnValue({
getSongUrl: async () => {
ctx.queue.current.mockReturnValue(null);
return { url: "https://example.com/track" };
},
});
expect(await resolveAndPlay.call(ctx, song)).toBe(false);
expect(player.play).not.toHaveBeenCalled();
});
describe("BotInstance.resolveAndPlay — Spotify routing (C4)", () => {
it("routes a spotify song to controller.playTrack + player.playPcmStream, not player.play", async () => {
const controller = makeController();
+127 -38
View File
@@ -9,8 +9,10 @@ import {
} from "../ts-protocol/client.js";
import { OpenProtocolManager } from "../ts-protocol/open-protocol.js";
import { AudioPlayer } from "../audio/player.js";
import { resolveUrlWithRetry } from "./url-retry.js";
import { RISK_CONTROL_CODE, RiskControlError, toPlayFailure } from "../music/provider.js";
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
import type { MusicProvider, Platform, Song } from "../music/provider.js";
import type { MusicProvider, Platform, PlayFailure, Song, SongUrlResult } from "../music/provider.js";
import { musicRequestError } from "../music/request-error.js";
import {
parseCommand,
@@ -221,6 +223,7 @@ export class BotInstance extends EventEmitter {
private fmRequesterName: string | undefined;
/** Results of the most recent !search, for "#N" selection (issue #90). */
private lastSearchResults: Song[] = [];
private playbackRequest?: symbol;
/** 当前曲实际播放时长(试听片段秒数或完整 duration);resolveAndPlay 赋值。 */
private effectiveDuration: number | undefined;
/** Resume attempts for the current song's stream (#161); see resumeInterruptedStream. */
@@ -1066,55 +1069,118 @@ export class BotInstance extends EventEmitter {
return requestedBy ? { ...song, requestedBy } : { ...song };
}
/** Resolve URL for a song and start playing it. Skips to next if URL fails. */
async resolveAndPlay(song: QueuedSong): Promise<boolean> {
/** Resolve the URL and start playback if this request still owns the queue. */
async resolveAndPlay(song: QueuedSong, onFailure?: (failure: PlayFailure) => void): Promise<boolean> {
const request = Symbol();
this.playbackRequest = request;
const generation = this.lifecycleGeneration;
const current = this.queue.current();
const isCancelled = () => !this.connected || this.lifecycleGeneration !== generation ||
this.playbackRequest !== request || this.queue.current() !== current;
const fail = (message: string) => onFailure?.({
platform: song.platform,
songId: song.id,
code: "unknown",
message,
});
if (!this.connected) {
this.logger.warn({ songId: song.id, name: song.name }, "resolveAndPlay called on disconnected bot — skipping");
fail("机器人未连接");
return false;
}
if (song.platform === "local" && !this.isLocalAudioEnabled()) {
this.logger.warn({ songId: song.id, name: song.name }, "Local audio playback disabled — refusing track");
fail("该机器人已关闭本地音频播放");
return false;
}
// Clear any accumulated skip votes — every fresh track starts with a
// clean slate, regardless of which code path loaded it (cmdPlay,
// cmdPlaylist, cmdAlbum, cmdFm, trackEnd auto-advance, etc.).
this.voteSkipUsers.clear();
const provider = this.getProviderFor(song.platform);
try {
const provider = this.getProviderFor(song.platform);
if (song.platform === "bilibili" && (!song.id.includes("?p=") || song.duration === 0)) {
const detail = await provider.getSongDetail(song.id);
if (detail) {
song.duration = detail.duration;
song.name = detail.name;
song.id = detail.id;
// Detail is metadata only (duration / canonical id). A failure here used
// to abort the whole resolve before the retry budget even started, so a
// transient 4xx turned into an instant 「无法播放」.
try {
const detail = await provider.getSongDetail(song.id);
if (isCancelled()) return false;
if (detail) {
song.duration = detail.duration;
song.name = detail.name;
song.id = detail.id;
}
} catch (err) {
this.logger.warn({ err, songId: song.id }, "Song detail lookup failed — continuing with queued metadata");
}
}
const result = await provider.getSongUrl(song.id);
if (!result?.url) {
this.logger.warn({ songId: song.id, name: song.name }, "No URL available, skipping");
return false;
}
// Re-check connection state AFTER the network round-trip — the URL
// resolve can take multiple seconds and the user may have called stop
// during that window. Without this, we'd spawn ffmpeg on a
// disconnected bot and land back in the same "connected=false but
// playing=true" inconsistency that Bug C was about.
if (!this.connected) {
this.logger.warn(
{ songId: song.id, name: song.name },
"bot disconnected during URL resolve — aborting playback",
);
return false;
}
// Retries happen here (not in the provider) so every queue path — web
// click, chat !play, auto-advance, FM — shares the same budget. The
// policy lives in url-retry.ts so it is unit tested without a bot; a
// config without the field means 0 retries, i.e. the previous behaviour.
const result = await resolveUrlWithRetry({
retries: this.config?.playUrlRetries,
resolve: (quality) => provider.getSongUrl(song.id, quality),
// NetEase's quality ladder is not continuous: a track can play at 192k
// while both 320k and 128k return null, so every lower level is tried.
// Providers without a quality knob return [] and keep one attempt.
fallbacks: provider.getFallbackQualities?.() ?? [],
// Stop / disconnect must abort the budget: retrying into a dead
// connection only delays the queue.
isCancelled,
onAttemptFailed: ({ attempt, total, quality, error }) => {
const fields = { songId: song.id, name: song.name, attempt, total, quality };
if (error instanceof RiskControlError) {
// -460 is NetEase refusing the IP, not this track. Say so, otherwise
// the log reads like the song is unavailable and people go hunting
// for a copyright problem that does not exist.
this.logger.warn(
{ ...fields, code: RISK_CONTROL_CODE, reason: error.message },
"URL resolve hit NetEase risk control (-460) — backing off",
);
} else if (error) {
this.logger.warn({ ...fields, err: error }, "URL resolve threw — retrying");
} else if (attempt < total) {
this.logger.debug(fields, "URL resolve returned no URL — retrying");
}
},
// Once per track, and with the reason named. The old log line was
// `No URL available` with no cause, which is what sent three separate
// investigations after a copyright problem that was never there.
onExhausted: ({ quality, error }) => {
const failure = error
? toPlayFailure(provider.platform, song.id, error)
: {
platform: provider.platform,
songId: song.id,
code: "unknown" as const,
message: `没有拿到播放地址(${quality ?? "默认音质"})`,
};
onFailure?.(failure);
this.logger.warn(
{
songId: song.id,
name: song.name,
platform: provider.platform,
code: failure.code,
quality: quality ?? "default",
upstream: failure.upstream,
reason: failure.message,
},
"No URL available, skipping",
);
},
});
if (!result?.url || isCancelled()) return false;
// Stage 2: a `spotify:` sentinel URI means the go-librespot sidecar
// serves the audio, NOT ffmpeg. Start the per-bot sidecar on demand; if
// it can't run (disabled / non-Linux / binary missing) keep the Stage-1
// fallback message + skip so the queue keeps moving.
if (isSpotifyUri(result.url)) {
const ready = await this.spotifyController.ensureStarted();
if (isCancelled()) return false;
if (!ready) {
this.logger.info({ songId: song.id, name: song.name }, "Spotify backend unavailable — skipping");
fail(SPOTIFY_UNAVAILABLE_MESSAGE);
await this.tsClient.sendTextMessage(SPOTIFY_UNAVAILABLE_MESSAGE);
return false;
}
@@ -1124,8 +1190,10 @@ export class BotInstance extends EventEmitter {
// sidecar failed the play (dead/errored backend): never attach the
// player to a dead stream — send the same fallback and skip.
const played = await this.spotifyController.playTrack(result.url);
if (isCancelled()) return false;
if (!played) {
this.logger.info({ songId: song.id, name: song.name }, "Spotify playTrack failed — skipping");
fail(SPOTIFY_UNAVAILABLE_MESSAGE);
await this.tsClient.sendTextMessage(SPOTIFY_UNAVAILABLE_MESSAGE);
return false;
}
@@ -1225,7 +1293,9 @@ export class BotInstance extends EventEmitter {
this.emit("stateChange");
return true;
} catch (err) {
if (isCancelled()) return false;
this.logger.error({ err, songId: song.id }, "Failed to resolve URL");
onFailure?.(toPlayFailure(song.platform, song.id, err));
return false;
}
}
@@ -1409,8 +1479,9 @@ export class BotInstance extends EventEmitter {
const { song, error } = await this.resolvePlayQuery(cmd);
if (error) return error;
const song0 = song!;
const ok = await this.playSingleSong(song0, requesterName);
if (!ok) return `Cannot play: ${song0.name}`;
let why: string | undefined;
const ok = await this.playSingleSong(song0, requesterName, failure => { why = failure.message; });
if (!ok) return why ? `Cannot play: ${song0.name} — ${why}` : `Cannot play: ${song0.name}`;
return `Now playing: ${song0.name} - ${song0.artist}`;
}
@@ -1426,7 +1497,7 @@ export class BotInstance extends EventEmitter {
* Shared by chat !play and the web /play-song route so the toggle decision
* lives in exactly one place (#119). Returns true if a track started playing.
*/
async playSingleSong(song: QueuedSong, requesterName?: string): Promise<boolean> {
async playSingleSong(song: QueuedSong, requesterName?: string, onFailure?: (failure: PlayFailure) => void): Promise<boolean> {
const s = this.withRequester(song, requesterName);
if (this.config.playKeepsQueue && !this.queue.isEmpty()) {
const insertedAt =
@@ -1439,7 +1510,7 @@ export class BotInstance extends EventEmitter {
this.queue.playAt(insertedAt);
this.player.resetFailures();
// No sweep here: the queue is kept, so no local uploads were released.
return this.resolveAndPlay(this.queue.current()!);
return this.resolveAndPlay(this.queue.current()!, onFailure);
}
// Legacy replace behavior (default).
const previous = this.queue.current();
@@ -1453,7 +1524,7 @@ export class BotInstance extends EventEmitter {
// Reset failure counter on user-initiated play
this.player.resetFailures();
const ok = await this.resolveAndPlay(this.queue.current()!);
const ok = await this.resolveAndPlay(this.queue.current()!, onFailure);
// Sweep AFTER the new song is queued+resolved: the replaced songs are no
// longer referenced (and get deleted), but the song — if it is the same
// local upload that was already playing — stays referenced and is preserved.
@@ -2157,24 +2228,39 @@ export class BotInstance extends EventEmitter {
*
* Returns true if a song actually started playing, false otherwise.
*/
async playNext(maxRetries = 3): Promise<boolean> {
async playNext(maxRetries = 3, onFailure?: (failure: PlayFailure) => void): Promise<boolean> {
if (this.isAdvancing || !this.connected) return false;
this.isAdvancing = true;
let started = false;
let riskControlled = false;
const captureFailure = (failure: PlayFailure) => {
riskControlled = failure.code === "risk_control";
onFailure?.(failure);
};
const generation = this.lifecycleGeneration;
const unchanged = (song: QueuedSong, request: symbol | undefined) =>
this.connected && this.lifecycleGeneration === generation &&
this.queue.current() === song && this.playbackRequest === request;
try {
if (this.player.getState() !== "idle") this.player.stop(true);
this.voteSkipUsers.clear();
const next = this.queue.next();
if (next) {
started = await this.resolveAndPlay(next);
const playback = this.resolveAndPlay(next, captureFailure);
const request = this.playbackRequest;
started = await playback;
if (!started && !unchanged(next, request)) return false;
if (!started) {
for (let i = 0; i < maxRetries && this.connected; i++) {
for (let i = 0; i < maxRetries && this.connected && !riskControlled; i++) {
const retry = this.queue.next();
if (!retry) break;
if (await this.resolveAndPlay(retry)) {
const retryPlayback = this.resolveAndPlay(retry, captureFailure);
const retryRequest = this.playbackRequest;
if (await retryPlayback) {
started = true;
break;
}
if (!unchanged(retry, retryRequest)) return false;
}
}
if (!started) {
@@ -2190,7 +2276,10 @@ export class BotInstance extends EventEmitter {
await this.refillFm();
const refillNext = this.queue.next();
if (refillNext) {
started = await this.resolveAndPlay(refillNext);
const refillPlayback = this.resolveAndPlay(refillNext, captureFailure);
const refillRequest = this.playbackRequest;
started = await refillPlayback;
if (!started && !unchanged(refillNext, refillRequest)) return false;
}
if (!started) {
this.player.stop();
+540
View File
@@ -0,0 +1,540 @@
import { describe, expect, it, vi } from "vitest";
import { RiskControlError, SongUrlUnavailable, toPlayFailure } from "../music/provider.js";
import type { SongUrlResult } from "../music/provider.js";
import {
MAX_URL_RETRIES,
DEFAULT_URL_RETRY_BACKOFF_MS,
QUALITY_SWITCH_BACKOFF_MS,
RISK_CONTROL_BACKOFF_MS,
normalizeRetryCount,
resolveUrlWithRetry,
} from "./url-retry.js";
const ok = (url = "https://cdn.example/track.mp3"): SongUrlResult => ({ url });
/** Sleep stand-in that records the delays instead of waiting. */
function recordingSleep() {
const delays: number[] = [];
return { delays, sleep: async (ms: number) => void delays.push(ms) };
}
describe("normalizeRetryCount", () => {
it("accepts 0..MAX and truncates fractions", () => {
expect(normalizeRetryCount(0)).toBe(0);
expect(normalizeRetryCount(2)).toBe(2);
expect(normalizeRetryCount(2.9)).toBe(2);
});
it("clamps out-of-range numbers", () => {
expect(normalizeRetryCount(-3)).toBe(0);
expect(normalizeRetryCount(99)).toBe(MAX_URL_RETRIES);
});
// Garbage means "old behaviour" (fail fast), not "retry forever".
it("treats non-numeric values as zero", () => {
expect(normalizeRetryCount(undefined)).toBe(0);
expect(normalizeRetryCount(null)).toBe(0);
expect(normalizeRetryCount("3")).toBe(0);
expect(normalizeRetryCount(Number.NaN)).toBe(0);
expect(normalizeRetryCount(Number.POSITIVE_INFINITY)).toBe(0);
});
});
describe("resolveUrlWithRetry", () => {
it("makes exactly one attempt when retries is 0", async () => {
const resolve = vi.fn(async () => null);
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({ retries: 0, resolve, sleep });
expect(result).toBeNull();
expect(resolve).toHaveBeenCalledTimes(1);
});
// The reported bug: first click fails, third works. A retry inside one
// request turns that into a normal play.
it("succeeds on a later attempt and stops retrying", async () => {
const resolve = vi
.fn<() => Promise<SongUrlResult | null>>()
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(ok());
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({ retries: 2, resolve, sleep });
expect(result).toEqual(ok());
expect(resolve).toHaveBeenCalledTimes(3);
});
it("gives up after 1 + retries attempts", async () => {
const resolve = vi.fn(async () => null);
const { sleep, delays } = recordingSleep();
const result = await resolveUrlWithRetry({ retries: 2, resolve, sleep });
expect(result).toBeNull();
expect(resolve).toHaveBeenCalledTimes(3);
// Linear backoff: one wait before attempt 2, two units before attempt 3.
expect(delays).toEqual([DEFAULT_URL_RETRY_BACKOFF_MS, DEFAULT_URL_RETRY_BACKOFF_MS * 2]);
});
// A timeout from the local API sidecar looks identical to the user, so a
// throw is retried exactly like an empty result.
it("retries after a thrown error", async () => {
const resolve = vi
.fn<() => Promise<SongUrlResult | null>>()
.mockRejectedValueOnce(new Error("ECONNRESET"))
.mockResolvedValueOnce(ok("https://cdn.example/retry.mp3"));
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({ retries: 1, resolve, sleep });
expect(result?.url).toBe("https://cdn.example/retry.mp3");
expect(resolve).toHaveBeenCalledTimes(2);
});
it("returns null when every attempt throws", async () => {
const resolve = vi.fn(async () => {
throw new Error("boom");
});
const { sleep } = recordingSleep();
expect(await resolveUrlWithRetry({ retries: 2, resolve, sleep })).toBeNull();
expect(resolve).toHaveBeenCalledTimes(3);
});
it("does not start when already cancelled", async () => {
const resolve = vi.fn(async () => ok());
const result = await resolveUrlWithRetry({
retries: 3,
resolve,
isCancelled: () => true,
sleep: async () => {},
});
expect(result).toBeNull();
expect(resolve).not.toHaveBeenCalled();
});
// Stopping mid-budget must not keep hammering the API for a track nobody
// wants any more.
it("aborts after cancellation during the backoff", async () => {
const resolve = vi.fn(async () => null);
let cancelled = false;
const sleep = async () => {
cancelled = true; // user hit stop while we waited
};
const result = await resolveUrlWithRetry({
retries: 3,
resolve,
isCancelled: () => cancelled,
sleep,
});
expect(result).toBeNull();
expect(resolve).toHaveBeenCalledTimes(1);
});
it("reports every failed attempt once, with the error when there was one", async () => {
const failures: Array<{ attempt: number; total: number; error?: unknown }> = [];
const boom = new Error("boom");
const resolve = vi
.fn<() => Promise<SongUrlResult | null>>()
.mockResolvedValueOnce(null)
.mockRejectedValueOnce(boom)
.mockResolvedValueOnce(null);
const { sleep } = recordingSleep();
await resolveUrlWithRetry({
retries: 2,
resolve,
sleep,
onAttemptFailed: (info) => failures.push(info),
});
expect(failures).toHaveLength(3);
expect(failures[0]).toEqual({ attempt: 1, total: 3, error: undefined });
expect(failures[1]).toEqual({ attempt: 2, total: 3, error: boom });
expect(failures[2]).toEqual({ attempt: 3, total: 3, error: undefined });
});
it("does not report a failure for the attempt that succeeded", async () => {
const onAttemptFailed = vi.fn();
const resolve = vi
.fn<() => Promise<SongUrlResult | null>>()
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(ok());
const { sleep } = recordingSleep();
await resolveUrlWithRetry({ retries: 1, resolve, sleep, onAttemptFailed });
expect(onAttemptFailed).toHaveBeenCalledTimes(1);
});
it("honours a custom backoff", async () => {
const { sleep, delays } = recordingSleep();
await resolveUrlWithRetry({
retries: 2,
backoffMs: 10,
resolve: async () => null,
sleep,
});
expect(delays).toEqual([10, 20]);
});
// An empty-string URL is as useless as null: the player would fail later.
it("treats a result without a url as a failure", async () => {
const resolve = vi
.fn<() => Promise<SongUrlResult | null>>()
.mockResolvedValueOnce({ url: "" })
.mockResolvedValueOnce(ok());
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({ retries: 1, resolve, sleep });
expect(result?.url).toBe(ok().url);
expect(resolve).toHaveBeenCalledTimes(2);
});
});
// ---------------------------------------------------------------------------
// Quality fallback
//
// Regression for «点四五次才能播»: NetEase's ladder is discontinuous, so a
// track that plays at 192k can return null at BOTH 320k (the default) and 128k.
// Retrying the same level can never fix that — the level has to change.
// ---------------------------------------------------------------------------
describe("resolveUrlWithRetry — quality fallback", () => {
it("sweeps the fallback levels after the primary budget is spent", async () => {
const seen: Array<string | undefined> = [];
const resolve = vi.fn(async (quality?: string) => {
seen.push(quality);
// Only "higher" ever works; the configured level never does.
return quality === "higher" ? ok("https://cdn.example/192.mp3") : null;
});
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({
retries: 1,
resolve,
fallbacks: ["higher", "standard"],
sleep,
});
expect(result?.url).toBe("https://cdn.example/192.mp3");
// primary, primary retry, then higher — and stops there.
expect(seen).toEqual([undefined, undefined, "higher"]);
});
it("tries every fallback in order when none of them work", async () => {
const seen: Array<string | undefined> = [];
const resolve = vi.fn(async (quality?: string) => {
seen.push(quality);
return null;
});
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({
retries: 1,
resolve,
fallbacks: ["higher", "standard"],
sleep,
});
expect(result).toBeNull();
expect(seen).toEqual([undefined, undefined, "higher", "standard"]);
});
it("does not touch fallbacks when the configured level succeeds", async () => {
const resolve = vi.fn(async () => ok());
const { sleep } = recordingSleep();
await resolveUrlWithRetry({ retries: 3, resolve, fallbacks: ["higher"], sleep });
expect(resolve).toHaveBeenCalledTimes(1);
});
// A level switch is a different request, so it must not wait out a full
// same-quality backoff — otherwise a broken 320k track stalls for seconds.
it("uses the short switch delay between levels", async () => {
const { sleep, delays } = recordingSleep();
await resolveUrlWithRetry({
retries: 1,
resolve: async () => null,
fallbacks: ["higher", "standard"],
sleep,
});
expect(delays).toEqual([
DEFAULT_URL_RETRY_BACKOFF_MS, // primary → primary retry
QUALITY_SWITCH_BACKOFF_MS, // retry → higher
QUALITY_SWITCH_BACKOFF_MS, // higher → standard
]);
});
it("reports which quality each failed attempt used", async () => {
const failures: Array<{ quality?: string }> = [];
const { sleep } = recordingSleep();
await resolveUrlWithRetry({
retries: 0,
resolve: async () => null,
fallbacks: ["higher", "standard"],
sleep,
onAttemptFailed: (info) => failures.push(info),
});
expect(failures.map((f) => f.quality)).toEqual([undefined, "higher", "standard"]);
});
it("still works when no fallbacks are supplied", async () => {
const resolve = vi.fn(async () => null);
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({ retries: 2, resolve, sleep });
expect(result).toBeNull();
expect(resolve).toHaveBeenCalledTimes(3);
});
it("aborts mid-sweep when the caller is cancelled", async () => {
const resolve = vi.fn(async () => null);
let cancelled = false;
const sleep = async () => {
cancelled = true;
};
const result = await resolveUrlWithRetry({
retries: 0,
resolve,
fallbacks: ["higher", "standard"],
isCancelled: () => cancelled,
sleep,
});
expect(result).toBeNull();
expect(resolve).toHaveBeenCalledTimes(1);
});
});
// ---------------------------------------------------------------------------
// NetEase risk control (-460)
//
// Measured against a live host: `GET /song/url/v1?id=…&level=exhigh` without
// the account cookie answers 400 `{"code":-460,"message":"检测到您的网络环境存在
// 风险,请稍后再试"}` every single time, while the same call WITH the cookie
// answers 200. Intermittently it also rejects the cookie call — that is the
// "click play five times until it works" report.
//
// Because -460 is a 400, the normal 250ms re-poke lands inside the same risk
// window and the whole budget is wasted. These tests pin the longer wait.
// ---------------------------------------------------------------------------
describe("resolveUrlWithRetry — risk control backoff", () => {
it("retries once after RISK_CONTROL_BACKOFF_MS, then stops", async () => {
const { sleep, delays } = recordingSleep();
const resolve = vi.fn(async () => {
throw new RiskControlError("网络环境风险 (-460)");
});
const result = await resolveUrlWithRetry({ retries: 2, resolve, sleep });
expect(result).toBeNull();
// One request plus exactly one retry. The old shape waited 2.5s and then
// 7.5s, spending three requests to reach the same "still blocked".
expect(resolve).toHaveBeenCalledTimes(2);
expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS]);
// Still far longer than a plain transient retry would have waited.
expect(delays[0]).toBeGreaterThan(DEFAULT_URL_RETRY_BACKOFF_MS);
});
it("caps the budget at two requests regardless of retries, and skips the ladder", async () => {
let attempts = 0;
const { sleep, delays } = recordingSleep();
const result = await resolveUrlWithRetry({
retries: 5,
resolve: async () => {
attempts += 1;
throw new RiskControlError("网络环境风险 (-460)");
},
fallbacks: ["higher", "standard"],
sleep,
});
expect(result).toBeNull();
// -460 ignores which level we ask for, so neither the extra configured
// retries nor the two ladder steps are worth sending: each one only adds
// silence before the same failure surfaces.
expect(attempts).toBe(2);
expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS]);
});
it("still walks the ladder when the risk control clears on a retry", async () => {
// First attempt blocked by the IP, second one just has no URL — the cause
// changed, so a lower level is worth trying again.
let attempts = 0;
const result = await resolveUrlWithRetry({
retries: 1,
resolve: async (quality) => {
attempts += 1;
if (attempts === 1) throw new RiskControlError("网络环境风险 (-460)");
if (quality === "standard") return ok("https://cdn.example/128k.mp3");
return null;
},
fallbacks: ["higher", "standard"],
sleep: async () => {},
});
expect(result?.url).toBe("https://cdn.example/128k.mp3");
// 2 same-quality attempts, then both ladder steps — the second attempt was a
// plain miss, not -460, so the cap no longer applies and the ladder keeps
// its normal cost.
expect(attempts).toBe(4);
});
it("recovers on the single retry and stops spending", async () => {
let attempts = 0;
const { sleep, delays } = recordingSleep();
const result = await resolveUrlWithRetry({
retries: 3,
resolve: async () => {
attempts += 1;
if (attempts < 2) throw new RiskControlError("网络环境风险 (-460)");
return ok("https://cdn.example/after-window.mp3");
},
sleep,
});
expect(result?.url).toBe("https://cdn.example/after-window.mp3");
expect(attempts).toBe(2);
expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS]);
});
it("still uses the short delay for a plain error", async () => {
const { sleep, delays } = recordingSleep();
await resolveUrlWithRetry({
retries: 1,
resolve: async () => {
throw new Error("boom");
},
sleep,
});
expect(delays).toEqual([DEFAULT_URL_RETRY_BACKOFF_MS]);
});
it("cancels during a risk-control wait", async () => {
let cancelled = false;
const result = await resolveUrlWithRetry({
retries: 3,
resolve: async () => {
throw new RiskControlError("网络环境风险 (-460)");
},
isCancelled: () => cancelled,
sleep: async () => {
cancelled = true;
},
});
expect(result).toBeNull();
});
});
// ---------------------------------------------------------------------------
// Reporting why the budget ran out
//
// The caller needs a cause, not just `null`: the web layer used to print
// 「无法播放(区域/版权限制)」 for every outcome, including a lapsed membership and
// a quality the account cannot stream. `onExhausted` is how the cause survives
// the retry loop.
// ---------------------------------------------------------------------------
describe("resolveUrlWithRetry — reporting the cause", () => {
function unavailable(code: any, message = "某原因") {
return new SongUrlUnavailable({ platform: "netease", songId: "1", code, message });
}
it("hands back the last error once the budget is spent", async () => {
const seen: Array<{ quality?: string; error: unknown }> = [];
const err = unavailable("vip_required");
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({
retries: 2,
resolve: async () => {
throw err;
},
sleep,
onExhausted: (info) => seen.push(info),
});
expect(result).toBeNull();
expect(seen).toHaveLength(1);
expect(seen[0].error).toBe(err);
expect(toPlayFailure("netease", "1", seen[0].error).code).toBe("vip_required");
});
it("reports the level it gave up on, not the first one", async () => {
const seen: Array<{ quality?: string; error: unknown }> = [];
const { sleep } = recordingSleep();
await resolveUrlWithRetry({
retries: 0,
resolve: async (quality) => {
if (quality === "standard") throw unavailable("quality_denied");
return null;
},
fallbacks: ["higher", "standard"],
sleep,
onExhausted: (info) => seen.push(info),
});
expect(seen[0].quality).toBe("standard");
});
it("stays silent when a level finally works", async () => {
const seen: unknown[] = [];
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({
retries: 1,
resolve: async (quality) => {
if (quality === "higher") return ok();
throw unavailable("quality_denied");
},
fallbacks: ["higher"],
sleep,
onExhausted: (info) => seen.push(info),
});
expect(result?.url).toBeTruthy();
expect(seen).toHaveLength(0);
});
// Pressing stop is not a failure. Reporting one would flash an error toast at
// a user who just changed their mind.
it("stays silent when the caller cancels", async () => {
const seen: unknown[] = [];
let cancelled = false;
await resolveUrlWithRetry({
retries: 3,
resolve: async () => {
throw unavailable("risk_control");
},
isCancelled: () => cancelled,
sleep: async () => {
cancelled = true;
},
onExhausted: (info) => seen.push(info),
});
expect(seen).toHaveLength(0);
});
// Providers that have not adopted SongUrlUnavailable still return null.
it("still reports for a provider that returns null without throwing", async () => {
const seen: Array<{ quality?: string; error: unknown }> = [];
const { sleep } = recordingSleep();
await resolveUrlWithRetry({
retries: 0,
resolve: async () => null,
sleep,
onExhausted: (info) => seen.push(info),
});
expect(seen).toHaveLength(1);
expect(seen[0].error).toBeUndefined();
});
});
+188
View File
@@ -0,0 +1,188 @@
import { RiskControlError } from "../music/provider.js";
import type { SongUrlResult } from "../music/provider.js";
/**
* Silent re-resolve of a playable URL.
*
* Two different failure modes look identical to the user but need different
* treatment, so this handles both inside one request:
*
* 1. **Transient** — NetEase intermittently answers `url: null` for a song that
* resolves fine a moment later. Repeating the SAME request fixes it.
* 2. **Quality gap** — some tracks have no URL at the configured level while a
* different level works. Measured against a real library: a track can be
* playable at "higher" (192k) while BOTH "exhigh" (320k) and "standard"
* (128k) return null, so a single "drop to the cheapest" step is not enough
* — every level below the current one has to be tried.
*
* Without either, the user saw 「无法播放(区域/版权限制)」 and had to click play
* repeatedly until it happened to work.
*
* Kept as a standalone function (not a BotInstance method) so the behaviour is
* testable without booting a bot, and so every caller — web click, chat !play,
* auto-advance, FM — gets the same budget by construction.
*/
/** Upper bound on retries per quality level, whatever the config says. */
export const MAX_URL_RETRIES = 5;
/** Default delay before retrying the SAME quality; grows linearly (250, 500 …). */
export const DEFAULT_URL_RETRY_BACKOFF_MS = 250;
/**
* Delay before the first attempt at the next quality level. Much shorter than a
* same-quality retry: switching level is a different request, not a re-poke of
* the same one, so it does not need to wait out the same jitter window.
*/
export const QUALITY_SWITCH_BACKOFF_MS = 120;
/**
* Delay before the single retry that follows a -460 (NetEase IP risk control).
*
* This is the one failure mode where the delay is NOT cosmetic: the upstream
* has decided the caller's address looks risky and will keep answering 400 for
* a few seconds no matter what we ask. Re-poking after 250ms just burns the
* budget inside the same window.
*
* Sized against what the window actually looks like: a live host answered
* `-460, -460, -460, -460, 200` on six consecutive 128k requests with no
* waiting at all, i.e. it is "let a few of these through, then stop caring"
* rather than a hard timer. So 2.5s is a good bet for one retry, and waiting
* longer is not: it buys nothing the user cannot do themselves.
*/
export const RISK_CONTROL_BACKOFF_MS = 2500;
/**
* Hard ceiling on requests sent while the IP is risk controlled (1 + 1 retry).
*
* The previous shape grew the delay per attempt (2.5s, then 7.5s), which meant
* up to 10s of a spinner doing nothing before the same error appeared. Measured
* behaviour says a blocked address either clears within a couple of seconds or
* stays blocked; the third and later attempts only add silence. Spending two
* requests and then telling the user to wait ~5s is both faster and honest.
*/
export const MAX_RISK_CONTROL_REQUESTS = 2;
/**
* Normalise a config value into a usable retry count.
* Anything non-numeric (legacy config, `"3"`, `null`) means "no retries", which
* keeps the pre-existing fail-fast behaviour for callers that pass garbage.
*/
export function normalizeRetryCount(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) return 0;
return Math.min(MAX_URL_RETRIES, Math.max(0, Math.trunc(value)));
}
export interface ResolveUrlWithRetryOptions {
/** Extra attempts per quality level after the first. 0 = one attempt each. */
retries: unknown;
/** Resolve one URL. `undefined` means "the provider's configured quality". */
resolve: (quality?: string) => Promise<SongUrlResult | null>;
/**
* Lower quality levels to sweep after the primary budget is spent, best→worst.
* Typically `provider.getFallbackQualities?.()`.
*/
fallbacks?: string[];
/** Checked before every attempt — stop / disconnect aborts the budget. */
isCancelled?: () => boolean;
backoffMs?: number;
/** Called once per failed attempt (logging hook). */
onAttemptFailed?: (info: {
attempt: number;
total: number;
quality?: string;
error?: unknown;
}) => void;
/**
* Called once when the budget is spent — never on cancellation, because
* "the user pressed stop" is not a failure worth reporting.
*
* Carries the last attempt's error so the caller can turn it into a message
* that names the cause (missing membership, delisted, blocked quality) rather
* than the old catch-all 「区域/版权限制」.
*/
onExhausted?: (info: { quality?: string; error: unknown }) => void;
/** Injectable for tests. */
sleep?: (ms: number) => Promise<void>;
}
/**
* Returns the first successful result, or null once every level is exhausted.
*
* Request count: `(1 + retries)` at the configured quality, then one per
* fallback level. With the defaults (2 retries, exhigh, NetEase's two lower
* levels) that is at most 5 requests and ~1.1s of waiting — or 2 requests and
* 2.5s when the IP is risk controlled, which is the one case where waiting
* more cannot help.
*/
export async function resolveUrlWithRetry(
opts: ResolveUrlWithRetryOptions,
): Promise<SongUrlResult | null> {
const retries = normalizeRetryCount(opts.retries);
const backoffMs = opts.backoffMs ?? DEFAULT_URL_RETRY_BACKOFF_MS;
const sleep =
opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
// Phase 1: the configured quality (1 + retries attempts).
// Phase 2: every lower level, once each, so a discontinuous ladder is covered.
const plan: Array<{ quality?: string; fallback: boolean }> = [];
for (let i = 0; i <= retries; i++) plan.push({ quality: undefined, fallback: false });
for (const quality of opts.fallbacks ?? []) plan.push({ quality, fallback: true });
let sameQualityAttempt = 0;
// Set when the previous attempt failed with -460. Risk control ignores the
// quality we ask for, so a level switch does not get to use its short delay.
let riskControlled = false;
// Requests actually sent. Only consulted while risk controlled, where the
// budget is capped at MAX_RISK_CONTROL_REQUESTS instead of the configured
// retry count.
let requestsMade = 0;
// The last failure, kept so the caller can explain the outcome. A `null`
// result (no throw) counts too — it is the providers that have not adopted
// SongUrlUnavailable yet.
let lastError: unknown;
let lastQuality: string | undefined;
for (let i = 0; i < plan.length; i++) {
const step = plan[i];
if (opts.isCancelled?.()) return null;
// -460 is an IP-level refusal, not a property of this track: the quality we
// ask for is irrelevant to it, so stepping down the ladder cannot succeed
// and each extra step only adds silence. Stop after one retry instead of
// when the plan runs out — the caller reports "try again in a few seconds",
// which is something the user can act on, unlike a longer spinner.
if (riskControlled && (step.fallback || requestsMade >= MAX_RISK_CONTROL_REQUESTS)) break;
if (i > 0) {
const wait = riskControlled
? RISK_CONTROL_BACKOFF_MS
: step.fallback
? QUALITY_SWITCH_BACKOFF_MS
: backoffMs * sameQualityAttempt;
if (wait > 0) await sleep(wait);
// The user may have stopped or switched tracks while we waited.
if (opts.isCancelled?.()) return null;
}
let error: unknown;
requestsMade += 1;
let result: SongUrlResult | null = null;
try {
result = await opts.resolve(step.quality);
} catch (err) {
error = err;
}
if (opts.isCancelled?.()) return null;
if (result?.url) return result;
riskControlled = error instanceof RiskControlError;
lastError = error;
lastQuality = step.quality;
opts.onAttemptFailed?.({ attempt: i + 1, total: plan.length, quality: step.quality, error });
// Only same-quality attempts grow the backoff; a level switch resets it.
sameQualityAttempt = step.fallback ? 0 : sameQualityAttempt + 1;
}
opts.onExhausted?.({ quality: lastQuality, error: lastError });
return null;
}
+27
View File
@@ -144,6 +144,19 @@ export interface BotConfig {
* keeps today's clear-and-play behavior.
*/
playKeepsQueue: boolean;
/**
* Extra attempts to re-resolve a playable URL before a track is reported as
* unplayable.
*
* NetEase intermittently answers `url: null` for a song that resolves fine a
* second later (upstream risk-control / edge jitter), which users experienced
* as "click once → 无法播放(区域/版权限制), click again → works". Retrying
* silently inside one request turns that into a normal play.
*
* 0 disables retries (fail fast, pre-existing behaviour). Clamped to 0..5 so
* a hand-edited config cannot turn every failed track into a long stall.
*/
playUrlRetries: number;
// Public base URL used when generating share links (e.g. the bot专属链接).
// Leave empty to use the browser's current origin. Example:
// "https://music.example.com" or "http://1.2.3.4:3000"
@@ -200,6 +213,9 @@ export function getDefaultConfig(): BotConfig {
savedQueuesEnabled: false,
perUserMusicAccounts: false,
playKeepsQueue: false,
// Two extra attempts: enough to ride out a transient NetEase hiccup without
// making a genuinely unlicensed track feel stuck (~1s of backoff total).
playUrlRetries: 2,
publicUrl: "",
trustProxy: false,
guestMode: {
@@ -406,6 +422,16 @@ export function loadConfig(path: string): BotConfig {
// hand-edited `"yes"`/`1`, must never turn account isolation on by accident.
const perUserMusicAccounts = partial.perUserMusicAccounts === true;
// Play-URL retry budget. Anything non-numeric (legacy config, `"3"`,
// `null`) falls back to the default instead of disabling the retry, because
// "no retries" is the surprising outcome here — the feature exists to hide
// upstream flakiness from users.
const rawRetries = partial.playUrlRetries;
const playUrlRetries =
typeof rawRetries === "number" && Number.isFinite(rawRetries)
? Math.min(5, Math.max(0, Math.trunc(rawRetries)))
: defaults.playUrlRetries;
// Voice ducking is opt-in and the retained-volume percentage is consumed
// directly by the audio path. Only a plain-object block with correctly
// typed, finite and in-range fields may override the safe defaults.
@@ -469,6 +495,7 @@ export function loadConfig(path: string): BotConfig {
savedQueuesEnabled,
perUserMusicAccounts,
playKeepsQueue,
playUrlRetries,
voiceDucking,
defaultPlatform: defaultPlatformPref,
};
+175 -2
View File
@@ -2,6 +2,8 @@ import { once } from "node:events";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { describe, it, expect, vi } from "vitest";
import { normalizeCookie } from "./cookie-normalize.js";
import { RiskControlError, SongUrlUnavailable } from "./provider.js";
import {
parseLyrics,
mapNeteaseAlbums,
@@ -43,8 +45,9 @@ describe("NeteaseProvider playback user agent", () => {
const params = requests.at(-1)!.searchParams;
expect(params.get("ua")).toContain(uaFamily);
expect(params.get("level")).toBe("standard");
expect(params.get("cookie")).toBe(cookie || null);
expect(provider.getCookie()).toBe(cookie);
const normalized = normalizeCookie(cookie);
expect(params.get("cookie")).toBe(normalized || null);
expect(provider.getCookie()).toBe(normalized);
}
provider.setCookie("MUSIC_U=shared; os=pc");
@@ -374,3 +377,173 @@ describe("NeteaseProvider.getArtistAllSongs (全部歌曲 paging)", () => {
expect(page.hasMore).toBe(false);
});
});
describe("NetEase quality fallback ladder", () => {
it("offers every lower level, best-first, for the default 320k setting", () => {
const p = new NeteaseProvider("http://x");
// Default quality is exhigh (320k) → 192k then 128k.
expect(p.getFallbackQualities()).toEqual(["higher", "standard"]);
});
// The real-world case that produced «点四五次才能播»: a track playable at
// 192k while BOTH 320k and 128k return null. Dropping only to the cheapest
// level would still fail, so 192k has to be in the list.
it("includes intermediate levels, not just the cheapest", () => {
const p = new NeteaseProvider("http://x");
p.setQuality("lossless");
expect(p.getFallbackQualities()).toEqual(["exhigh", "higher", "standard"]);
});
it("has nothing to offer once already at the lowest level", () => {
const p = new NeteaseProvider("http://x");
p.setQuality("standard");
expect(p.getFallbackQualities()).toEqual([]);
});
it("never proposes a level above the configured one", () => {
const p = new NeteaseProvider("http://x");
p.setQuality("higher");
expect(p.getFallbackQualities()).toEqual(["standard"]);
});
});
// ---------------------------------------------------------------------------
// Risk control (-460)
//
// Live measurement on a cloud host, same song, same second:
// GET /song/url/v1?id=1827600686&level=exhigh → 400 {"code":-460}
// GET …&cookie=<account cookie> → 200, 320k url
// axios reports both 400s and 200s alike as ERR_BAD_REQUEST when it fails, so
// the body has to be inspected to know whether retrying is worthwhile.
// ---------------------------------------------------------------------------
describe("NetEase risk control (-460)", () => {
/** Swap the axios instance for a stub — no module mocking needed. */
function providerWithApi(get: (url: string, cfg: unknown) => Promise<unknown>) {
const p = new NeteaseProvider("http://127.0.0.1:3001");
(p as unknown as { api: { get: typeof get } }).api = { get };
return p;
}
function httpError(status: number, data: unknown) {
const err = new Error(`Request failed with status code ${status}`) as Error & {
response: unknown;
};
err.response = { status, data };
return err;
}
it("turns 400 + code -460 into a RiskControlError", async () => {
const p = providerWithApi(async () => {
throw httpError(400, {
code: -460,
message: "检测到您的网络环境存在风险,请稍后再试",
});
});
await expect(p.getSongUrl("1827600686")).rejects.toBeInstanceOf(RiskControlError);
});
it("returns a fixed risk-control error without exposing the upstream message", async () => {
const p = providerWithApi(async () => {
throw httpError(400, { code: -460, message: "upstream sample detail" });
});
await expect(p.getSongUrl("1827600686")).rejects.toThrow("网易云请求被风控拦截 (-460)");
});
it("does not disguise a genuine bad request", async () => {
const p = providerWithApi(async () => {
throw httpError(400, { code: 400, msg: "参数错误" });
});
await expect(p.getSongUrl("1")).rejects.not.toBeInstanceOf(RiskControlError);
});
it("does not disguise an unrelated 400 without a body code", async () => {
const p = providerWithApi(async () => {
throw httpError(400, "<html>Bad Request</html>");
});
await expect(p.getSongUrl("1")).rejects.not.toBeInstanceOf(RiskControlError);
});
// A 200 with no url is not "the track does not exist" — it is one of five
// different things, and this used to collapse all of them into a bare null.
it("names the cause for a 200 that carries no url", async () => {
const p = providerWithApi(async () => ({ data: { data: [{ url: null, code: 404 }] } }));
await expect(p.getSongUrl("1")).rejects.toMatchObject({
failure: { code: "no_copyright" },
});
});
it("returns the url and the trial window on success", async () => {
const p = providerWithApi(async () => ({
data: { data: [{ url: "http://cdn.example/x.mp3", freeTrialInfo: { start: 0, end: 60 } }] },
}));
const r = await p.getSongUrl("1");
expect(r?.url).toBe("http://cdn.example/x.mp3");
expect(r?.trialDuration).toBe(60);
});
});
// ---------------------------------------------------------------------------
// Naming the cause of a 200-with-no-URL
//
// `/song/url/v1` says "no URL here" for at least four unrelated reasons and the
// fix differs for each: open a membership, pick another track, drop the quality,
// or wait. Collapsing them into `null` is what produced the catch-all
// 「无法播放(区域/版权限制)」 for a problem that was usually not about copyright.
// ---------------------------------------------------------------------------
describe("NetEase — why a track has no URL", () => {
/** Resolve and return the thrown error; fails loudly if it does not throw. */
async function miss(item: Record<string, unknown> | undefined): Promise<any> {
const p = new NeteaseProvider("http://127.0.0.1:3001");
(p as unknown as { api: { get: () => Promise<unknown> } }).api = {
get: async () => ({ data: { data: item ? [item] : [] } }),
};
try {
await p.getSongUrl("1");
} catch (err) {
return err;
}
throw new Error("expected getSongUrl to throw for a URL-less response");
}
it("fee=1 未购买 → 需要会员", async () => {
const err = await miss({ url: null, code: 200, fee: 1, payed: 0, level: "exhigh" });
expect(err.failure.code).toBe("vip_required");
expect(err.failure.message).toMatch(/需要会员/);
});
it("fee=4 未购买 → 需要购买专辑(不是「会员」)", async () => {
const err = await miss({ url: null, code: 200, fee: 4, payed: 0, level: "exhigh" });
expect(err.failure.code).toBe("vip_required");
expect(err.failure.message).toMatch(/专辑/);
});
it("已付款的曲目不算会员问题", async () => {
const err = await miss({ url: null, code: 200, fee: 1, payed: 1, level: "exhigh" });
expect(err.failure.code).toBe("quality_denied");
});
it("upstream code 404 → 无版权", async () => {
const err = await miss({ url: null, code: 404, level: "exhigh" });
expect(err.failure.code).toBe("no_copyright");
expect(err.failure.message).toMatch(/无版权|下架/);
});
// The measured case that broke the old single-message assumption: a free
// track (fee=8) with no URL at exhigh that plays fine at higher.
it("fee=8 且无 URL → 音质受限,而不是版权", async () => {
const err = await miss({ url: null, code: 200, fee: 8, level: "exhigh" });
expect(err.failure.code).toBe("quality_denied");
expect(err.failure.message).toMatch(/音质/);
});
it("空 data 数组 → 未知,但仍带得出上游字段", async () => {
const err = await miss(undefined);
expect(err.failure.code).toBe("unknown");
expect(err.failure.upstream).toBeDefined();
});
it("把 fee / payed / level 留在 upstream 里供日志使用", async () => {
const err = await miss({ url: null, code: 200, fee: 8, payed: 0, level: "higher", br: 192000 });
expect(err.failure.upstream).toMatchObject({ fee: 8, payed: 0, level: "higher", br: 192000 });
});
});
+117 -4
View File
@@ -1,5 +1,7 @@
import { normalizeCookie } from "./cookie-normalize.js";
import axios, { type AxiosInstance } from "axios";
import { RISK_CONTROL_CODE, RiskControlError, SongUrlUnavailable } from "./provider.js";
import type { PlayFailure } from "./provider.js";
import type {
MusicProvider,
Song,
@@ -115,6 +117,84 @@ export function parseNeteaseTrial(item: any): number | undefined {
return Math.round(secs);
}
/**
* Recognise NetEase's IP risk control inside an axios error. The status alone
* is not enough — axios reports every 4xx as ERR_BAD_REQUEST — so the body has
* to be read. See RiskControlError for the measured behaviour.
*/
function riskControlFrom(err: unknown): RiskControlError | null {
const e = err as {
response?: { status?: number; data?: { code?: number } };
};
if (e?.response?.status === 400 && e.response.data?.code === RISK_CONTROL_CODE) {
return new RiskControlError("网易云请求被风控拦截 (-460)");
}
return null;
}
/**
* Classify a 200-with-no-URL answer.
*
* `/song/url/v1` reports "no URL here" for at least four unrelated reasons, and
* they need different fixes: open a membership, pick another track, drop the
* quality, or just wait. The response does carry enough to tell them apart
* (`code`, `fee`, `payed`, `level`), and not reading those fields is exactly
* why every one of them reached the user as 「区域/版权限制」.
*
* Field meanings (NetEase):
* fee 0 = free, 1 = VIP, 4 = album-only purchase, 8 = free / low quality
* payed 1 = this account already paid for it
* code 404 on the item = the id does not resolve to a playable track
*/
export function diagnoseNeteaseMiss(
songId: string,
level: string,
item: Record<string, any> | undefined,
body: Record<string, any> | undefined,
): PlayFailure {
const upstream = {
code: item?.code ?? body?.code,
fee: item?.fee,
payed: item?.payed,
level: item?.level ?? level,
br: item?.br,
freeTrial: Boolean(item?.freeTrialInfo),
};
const suffix = `(${String(upstream.level)})`;
const base = { platform: "netease" as const, songId, upstream };
if (!item) {
return {
...base,
code: "unknown",
message: `音源没有返回该曲目${suffix}`,
};
}
if (upstream.code === 404) {
return {
...base,
code: "no_copyright",
message: `无版权或已下架${suffix}`,
};
}
const fee = typeof upstream.fee === "number" ? upstream.fee : -1;
if ((fee === 1 || fee === 4) && !upstream.payed) {
return {
...base,
code: "vip_required",
message: fee === 4 ? `需要购买该专辑${suffix}` : `需要会员${suffix}`,
};
}
// Everything else that has the track but no URL is a per-level restriction:
// the same id often plays at another level (measured: 192k OK while both
// 320k and 128k returned null).
return {
...base,
code: "quality_denied",
message: `当前音质无播放权限${suffix}`,
};
}
// NetEase quality levels: standard(128k) higher(192k) exhigh(320k) lossless(flac) hires(hi-res) jyeffect jymaster
export const NETEASE_QUALITY_LEVELS = [
{ value: "standard", label: "标准 (128kbps)", bitrate: 128 },
@@ -221,15 +301,48 @@ export class NeteaseProvider implements MusicProvider {
async getSongUrl(songId: string, quality?: string): Promise<SongUrlResult | null> {
const level = quality ?? this.quality;
const res = await this.api.get("/song/url/v1", {
params: { id: songId, level, ua: getPlaybackUserAgent(this.cookie), ...this.cookieParams },
});
let res;
try {
res = await this.api.get("/song/url/v1", {
params: { id: songId, level, ua: getPlaybackUserAgent(this.cookie), ...this.cookieParams },
});
} catch (err) {
// -460 arrives as HTTP 400, and left as-is it looks like "this track is
// unavailable" to every caller. Surface it as its own error type so the
// retry layer can wait out the risk-control window instead of giving up.
const risk = riskControlFrom(err);
if (risk) throw risk;
throw err;
}
const item = res.data?.data?.[0];
const url = item?.url;
if (!url) return null;
// A bare `null` here forced every caller to invent an explanation, and the
// one they invented was 「区域/版权限制」 — wrong for a lapsed membership, for
// a delisted track, and for a quality the account cannot stream. Throw the
// reason instead; the retry layer still spends its budget, it just stops
// lying about why nothing worked.
if (!url) throw new SongUrlUnavailable(diagnoseNeteaseMiss(songId, level, item, res.data));
return { url, trialDuration: parseNeteaseTrial(item) };
}
/**
* Levels to fall back to when the configured one returns no URL.
*
* NetEase does not offer a continuous quality ladder per track: measured on a
* real library, a track can be available at "higher" (192k) while BOTH
* "exhigh" (320k) and "standard" (128k) answer `url: null`. So the caller must
* sweep every level BELOW the current one instead of assuming "just drop to
* the cheapest".
*/
getFallbackQualities(): string[] {
const order = NETEASE_QUALITY_LEVELS.map((l) => l.value as string);
const index = order.indexOf(this.quality);
if (index <= 0) return [];
// order is low→high, so everything before the current level reversed gives
// best→worst below it (exhigh → ["higher", "standard"]).
return order.slice(0, index).reverse();
}
async getSongDetail(songId: string): Promise<Song | null> {
const res = await this.api.get("/song/detail", {
params: { ids: songId, ...this.cookieParams },
+83
View File
@@ -34,6 +34,77 @@ export interface SongUrlResult {
trialDuration?: number;
}
/** NetEase upstream risk-control response code. */
export const RISK_CONTROL_CODE = -460;
export class RiskControlError extends Error {
readonly code: number = RISK_CONTROL_CODE;
constructor(message: string) {
super(message);
this.name = "RiskControlError";
}
}
/**
* Why a track could not be turned into a playable URL.
*
* Every one of these used to reach the user as the same string —
* 「无法播放(区域/版权限制)」 — which is why a genuine -460, a lapsed membership
* and a delisted track were indistinguishable for weeks of debugging. Naming
* the cause is the whole point of this type.
*/
export type PlayFailureCode =
/** Upstream refused the caller's IP (-460). Transient by nature. */
| "risk_control"
/** Paid track with no entitlement on the account (NetEase fee=1 VIP / fee=4). */
| "vip_required"
/** Delisted, region-blocked, or the id no longer resolves (upstream 404). */
| "no_copyright"
/** The track exists, but this quality level is not ours to serve. */
| "quality_denied"
/** 200 with no URL and nothing that explains why. */
| "unknown";
export interface PlayFailure {
platform: string;
songId: string;
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. */
upstream?: Record<string, unknown>;
}
/**
* Thrown when a provider knows *why* no URL came back.
*
* `resolveUrlWithRetry` still runs the full budget on it — a lower level can
* genuinely help, and "deterministic" judgements about this API have been wrong
* before — but it remembers the last one so the eventual message can name the
* cause instead of falling back to a guess.
*/
export class SongUrlUnavailable extends Error {
readonly failure: PlayFailure;
constructor(failure: PlayFailure) {
super(failure.message);
this.name = "SongUrlUnavailable";
this.failure = failure;
}
}
export function toPlayFailure(platform: string, songId: string, error: unknown): PlayFailure {
if (error instanceof SongUrlUnavailable) return error.failure;
if (error instanceof RiskControlError) {
return {
platform,
songId,
code: "risk_control",
message: "网易云暂时拒绝播放请求(-460),请稍后重试",
};
}
return { platform, songId, code: "unknown", message: "解析播放地址失败" };
}
export interface Playlist {
id: string;
name: string;
@@ -42,6 +113,7 @@ export interface Playlist {
platform: Platform;
}
export interface PlaylistDetail {
id: string;
name: string;
@@ -134,6 +206,17 @@ export interface MusicProvider {
setCookie(cookie: string): void;
getCookie(): string;
getAuthStatus(): Promise<AuthStatus>;
/**
* Lower quality levels to try when the configured one has no URL, ordered
* best→worst.
*
* NetEase does not publish a uniform ladder: a track can be playable at 192k
* ("higher") while BOTH 320k ("exhigh") and 128k ("standard") return null —
* so the list has to contain every level below the current one, not just the
* cheapest. Sources whose quality is not a user-selectable knob (Bilibili,
* local files, Jellyfin) omit this and the caller keeps its single attempt.
*/
getFallbackQualities?(): string[];
/**
* A view of this same provider logged in as another account, without
* disturbing the shared instance. Implemented by the sources that support
+20
View File
@@ -76,6 +76,8 @@ export function createBotRouter(
savedQueuesEnabled: config.savedQueuesEnabled,
perUserMusicAccounts: config.perUserMusicAccounts === true,
playKeepsQueue: config.playKeepsQueue,
// Silent re-resolve budget for a track whose URL came back empty.
playUrlRetries: config.playUrlRetries ?? 0,
adminGroups: config.adminGroups ?? [],
guestMode: config.guestMode,
spotify: maskedSpotify(),
@@ -95,6 +97,7 @@ export function createBotRouter(
voiceDucking,
guestMode,
adminGroups,
playUrlRetries,
perUserMusicAccounts,
} = req.body;
@@ -106,6 +109,20 @@ export function createBotRouter(
const hasAutoPause = typeof autoPauseOnEmpty === "boolean";
const hasLocalAudioEnabled = typeof localAudioEnabled === "boolean";
// Retry budget is an integer 0..5; out-of-range is a client bug, not
// something to silently clamp, so it 400s like the other numeric fields.
const hasPlayUrlRetries = playUrlRetries !== undefined;
if (
hasPlayUrlRetries &&
(typeof playUrlRetries !== "number" ||
!Number.isInteger(playUrlRetries) ||
playUrlRetries < 0 ||
playUrlRetries > 5)
) {
res.status(400).json({ error: "playUrlRetries must be an integer 0-5" });
return;
}
const hasPerUserMusicAccounts = typeof perUserMusicAccounts === "boolean";
if (hasPerUserMusicAccounts && req.user?.role !== "admin") {
res.status(403).json({ error: "forbidden" });
@@ -115,6 +132,7 @@ export function createBotRouter(
if (hasIdle) config.idleTimeoutMinutes = idleTimeoutMinutes;
if (hasAutoPause) config.autoPauseOnEmpty = autoPauseOnEmpty;
if (hasLocalAudioEnabled) config.localAudioEnabled = localAudioEnabled;
if (hasPlayUrlRetries) config.playUrlRetries = playUrlRetries;
if (hasPerUserMusicAccounts) config.perUserMusicAccounts = perUserMusicAccounts;
// Voice ducking is a partial settings block. Merge only known, strictly
@@ -292,6 +310,8 @@ export function createBotRouter(
savedQueuesEnabled: config.savedQueuesEnabled,
perUserMusicAccounts: config.perUserMusicAccounts === true,
playKeepsQueue: config.playKeepsQueue,
// Silent re-resolve budget for a track whose URL came back empty.
playUrlRetries: config.playUrlRetries ?? 0,
adminGroups: config.adminGroups ?? [],
guestMode: config.guestMode,
spotify: maskedSpotify(),
+39 -26
View File
@@ -1,7 +1,9 @@
import { Router, type Request } from "express";
import type { BotInstance } from "../../bot/instance.js";
import type { QueuedSong } from "../../audio/queue.js";
import type { BotManager } from "../../bot/manager.js";
import type { BotDatabase } from "../../data/database.js";
import type { MusicProvider, Song, ArtistSongPage } from "../../music/provider.js";
import type { MusicProvider, Song, ArtistSongPage, PlayFailure } from "../../music/provider.js";
import { musicRequestError } from "../../music/request-error.js";
import type { Logger } from "../../logger.js";
import { parseCommand } from "../../bot/commands.js";
@@ -97,6 +99,21 @@ export function createPlayerRouter(
next();
});
const whyUnplayable = (song: { name?: string; id?: string }, reason?: string): string => {
const label = song.name || song.id || "这首歌";
return reason ? `无法播放「${label}」:${reason}` : `无法播放「${label}」`;
};
async function startCollection(bot: BotInstance, first: QueuedSong | null) {
let failure: PlayFailure | undefined;
const capture = (reason: PlayFailure) => { failure = reason; };
let started = first ? await bot.resolveAndPlay(first, capture) : false;
if (first && !started && failure?.code !== "risk_control" && bot.getQueueManager().current() === first) {
started = await bot.playNext(20, capture);
}
return { started, reason: failure?.message };
}
/** Map API platform string to the corresponding command flag. */
const platformFlag = (platform: unknown): string => {
if (platform === "bilibili") return "-b";
@@ -393,7 +410,7 @@ export function createPlayerRouter(
// the sequential retry path, which still has a chance.
}
if (queueable.length === 0) {
res.json({ ok: false, message: `歌单 ${totalCount} 首歌曲均无版权可播放(区域/版权限制)` });
res.json({ ok: false, message: `歌单 ${totalCount} 首歌曲均无法播放` });
return;
}
@@ -422,19 +439,16 @@ export function createPlayerRouter(
// retry-skip behavior. Use a higher retry budget than the default
// trackEnd auto-advance because user-initiated playlist plays
// commonly have long contiguous runs of unplayable songs.
let started = first ? await bot.resolveAndPlay(first) : false;
if (first && !started) {
started = await bot.playNext(20);
}
const { started, reason } = await startCollection(bot, first);
const playing = queue.current();
const loadedMsg = queueable.length < totalCount
? `已加载 ${queueable.length}/${totalCount} 首(其余区域/版权限制)`
? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)`
: `已加载 ${queueable.length} 首`;
if (started && playing) {
res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` });
} else {
res.json({ ok: false, message: `${loadedMsg},但无法开始播放。` });
res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` });
}
} catch (err) {
const error = musicRequestError(err);
@@ -476,7 +490,7 @@ export function createPlayerRouter(
}
}
if (queueable.length === 0) {
res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无版权可播放(区域/版权限制)` });
res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无法播放` });
return;
}
@@ -497,19 +511,16 @@ export function createPlayerRouter(
first = queue.play();
}
let started = first ? await bot.resolveAndPlay(first) : false;
if (first && !started) {
started = await bot.playNext(20);
}
const { started, reason } = await startCollection(bot, first);
const playing = queue.current();
const loadedMsg = queueable.length < totalCount
? `已加载 ${queueable.length}/${totalCount} 首(其余区域/版权限制)`
? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)`
: `已加载 ${queueable.length} 首`;
if (started && playing) {
res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` });
} else {
res.json({ ok: false, message: `${loadedMsg},但无法开始播放。` });
res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` });
}
} catch (err) {
const error = musicRequestError(err);
@@ -563,7 +574,7 @@ export function createPlayerRouter(
}
}
if (queueable.length === 0) {
res.json({ ok: false, message: `歌手 ${totalCount} 首歌曲均无版权可播放(区域/版权限制)` });
res.json({ ok: false, message: `歌手 ${totalCount} 首歌曲均无法播放` });
return;
}
@@ -589,16 +600,15 @@ export function createPlayerRouter(
first = queue.play();
}
let started = first ? await bot.resolveAndPlay(first) : false;
if (first && !started) started = await bot.playNext(20);
const { started, reason } = await startCollection(bot, first);
const playing = queue.current();
const loadedMsg = queueable.length < totalCount
? `已加载 ${queueable.length}/${totalCount} 首(其余区域/版权限制)`
? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)`
: `已加载 ${queueable.length} 首`;
return started && playing
? { ok: true, message: `${loadedMsg},正在播放:${playing.name}` }
: { ok: false, message: `${loadedMsg},但无法开始播放。` };
: { ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` };
});
res.json(body);
} catch (err) {
@@ -629,10 +639,11 @@ export function createPlayerRouter(
// clear branch — do NOT also call it here, or it would delete retained
// local uploads in keep-queue mode.
const body = await bot.runExclusive(async () => {
const ok = await bot.playSingleSong({ ...song }, requesterName(req));
let reason: string | undefined;
const ok = await bot.playSingleSong({ ...song }, requesterName(req), (failure: PlayFailure) => { reason = failure.message; });
return ok
? { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` }
: { ok: false, message: `无法播放「${song.name || song.id}」(区域/版权限制)` };
: { ok: false, message: whyUnplayable(song, reason) };
});
res.json(body);
} catch (err) {
@@ -672,9 +683,10 @@ export function createPlayerRouter(
// Promote the just-added song to current and start it.
queue.playAt(insertedAt);
bot.getPlayer().resetFailures();
const ok = await bot.resolveAndPlay(queue.current()!);
let reason: string | undefined;
const ok = await bot.resolveAndPlay(queue.current()!, (failure: PlayFailure) => { reason = failure.message; });
if (!ok) {
return { ok: false, message: `无法播放「${song.name || song.id}」(区域/版权限制)` };
return { ok: false, message: whyUnplayable(song, reason) };
}
return { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` };
}
@@ -711,9 +723,10 @@ export function createPlayerRouter(
queue.addNext({ ...song, requestedBy: requesterName(req) });
queue.playAt(insertedAt);
bot.getPlayer().resetFailures();
const ok = await bot.resolveAndPlay(queue.current()!);
let reason: string | undefined;
const ok = await bot.resolveAndPlay(queue.current()!, (failure: PlayFailure) => { reason = failure.message; });
if (!ok) {
return { ok: false, message: `无法播放「${song.name || song.id}」(区域/版权限制)` };
return { ok: false, message: whyUnplayable(song, reason) };
}
return { ok: true, message: `正在播放:${song.name || "Unknown"} - ${song.artist || "Unknown"}` };
});