From c2771ab9a7f0cdcf1be56dee1aa4208871adbb07 Mon Sep 17 00:00:00 2001 From: jiayuLian Date: Sun, 8 Nov 2026 17:20:01 +0800 Subject: [PATCH] =?UTF-8?q?fix(playback):=20retry=20and=20downgrade=20qual?= =?UTF-8?q?ity=20before=20reporting=20=E6=97=A0=E6=B3=95=E6=92=AD=E6=94=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two failure modes look identical to the user — 「无法播放(区域/版权限制)」 — but need different handling, and both were hitting the same code path: 1. **Transient.** NetEase intermittently answers `url: null` for a song that resolves fine a moment later. Repeating the SAME request fixes it, but the user had to click play repeatedly to be that retry. 2. **Quality gap.** Measured against a real library: a track can be playable at 192k ("higher") while BOTH 320k ("exhigh") and 128k ("standard") return `url: null`. So the ladder is not continuous and "just drop to the cheapest" would still fail — every level below the current one has to be tried. `resolveAndPlay` now resolves through `bot/url-retry.ts`: - Phase 1: `1 + config.playUrlRetries` attempts (default 2, clamped 0..5) at the configured quality, 250ms linear backoff between them. - Phase 2: one attempt per lower level from `provider.getFallbackQualities()` (NetEase: exhigh → higher → standard), 120ms apart — switching level is a different request, not a re-poke of the same one. - Cancel (stop / disconnect) is checked before every attempt, so the budget never retries into a dead connection. - A thrown error is retried exactly like an empty result: a sidecar timeout looks identical to the user. - Failure is logged once per track, not once per attempt. Every queue path funnels into `resolveAndPlay` (web click, chat !play, auto-advance, FM), so playlists and albums get the same budget for free — that is where "click the playlist four times before it starts" came from. `config.playUrlRetries` is exposed on GET/POST `/api/bot/settings`. A config without the field falls back to 2 — retries are ON by default because the whole point is to be invisible. Set it to 0 to restore the previous fail-fast path. --- src/bot/instance.ts | 37 ++++- src/bot/url-retry.test.ts | 311 ++++++++++++++++++++++++++++++++++++++ src/bot/url-retry.ts | 119 +++++++++++++++ src/data/config.ts | 27 ++++ src/music/netease.test.ts | 29 ++++ src/music/netease.ts | 18 +++ src/music/provider.ts | 11 ++ src/web/api/bot.ts | 19 +++ 8 files changed, 566 insertions(+), 5 deletions(-) create mode 100644 src/bot/url-retry.test.ts create mode 100644 src/bot/url-retry.ts diff --git a/src/bot/instance.ts b/src/bot/instance.ts index b2412cb..e87cddb 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -7,8 +7,9 @@ import { type TS3VoiceSendFailure, } from "../ts-protocol/client.js"; import { AudioPlayer } from "../audio/player.js"; +import { resolveUrlWithRetry } from "./url-retry.js"; import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js"; -import type { MusicProvider, Platform, Song } from "../music/provider.js"; +import type { MusicProvider, Platform, Song, SongUrlResult } from "../music/provider.js"; import { parseCommand, canRunCommand, @@ -1022,8 +1023,7 @@ export class BotInstance extends EventEmitter { } /** Resolve URL for a song and start playing it. Skips to next if URL fails. */ - async resolveAndPlay(song: QueuedSong): Promise { - if (!this.connected) { + async resolveAndPlay(song: QueuedSong): Promise { if (!this.connected) { this.logger.warn({ songId: song.id, name: song.name }, "resolveAndPlay called on disconnected bot — skipping"); return false; } @@ -1045,9 +1045,36 @@ export class BotInstance extends EventEmitter { song.id = detail.id; } } - const result = await provider.getSongUrl(song.id); + // Retries live in resolveUrlWithRetry so the whole queue path (web click, + // chat !play, auto-advance, FM) benefits from the same budget, and the + // failure is logged once there instead of once per attempt. + // 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: () => !this.connected, + onAttemptFailed: ({ attempt, total, quality, error }) => { + const fields = { songId: song.id, name: song.name, attempt, total, quality }; + 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"); + } else { + // Once per track, after the budget is spent — not once per attempt. + this.logger.warn(fields, "No URL available after retries, skipping"); + } + }, + }); 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 diff --git a/src/bot/url-retry.test.ts b/src/bot/url-retry.test.ts new file mode 100644 index 0000000..b4cfef3 --- /dev/null +++ b/src/bot/url-retry.test.ts @@ -0,0 +1,311 @@ +import { describe, expect, it, vi } from "vitest"; +import type { SongUrlResult } from "../music/provider.js"; +import { + MAX_URL_RETRIES, + DEFAULT_URL_RETRY_BACKOFF_MS, + QUALITY_SWITCH_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>() + .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>() + .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>() + .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>() + .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>() + .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 = []; + 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 = []; + 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); + }); +}); diff --git a/src/bot/url-retry.ts b/src/bot/url-retry.ts new file mode 100644 index 0000000..58ebf41 --- /dev/null +++ b/src/bot/url-retry.ts @@ -0,0 +1,119 @@ +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; + +/** + * 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; + /** + * 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; + /** Injectable for tests. */ + sleep?: (ms: number) => Promise; +} + +/** + * 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. + */ +export async function resolveUrlWithRetry( + opts: ResolveUrlWithRetryOptions, +): Promise { + const retries = normalizeRetryCount(opts.retries); + const backoffMs = opts.backoffMs ?? DEFAULT_URL_RETRY_BACKOFF_MS; + const sleep = + opts.sleep ?? ((ms: number) => new Promise((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; + + for (let i = 0; i < plan.length; i++) { + const step = plan[i]; + if (opts.isCancelled?.()) return null; + + if (i > 0) { + const wait = 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; + try { + const result = await opts.resolve(step.quality); + if (result?.url) return result; + } catch (err) { + error = err; + } + 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; + } + + return null; +} diff --git a/src/data/config.ts b/src/data/config.ts index 898a5bc..ff0623c 100755 --- a/src/data/config.ts +++ b/src/data/config.ts @@ -137,6 +137,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" @@ -192,6 +205,9 @@ export function getDefaultConfig(): BotConfig { localAudioEnabled: true, savedQueuesEnabled: 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: { @@ -395,6 +411,16 @@ export function loadConfig(path: string): BotConfig { const savedQueuesEnabled = partial.savedQueuesEnabled === true; const playKeepsQueue = partial.playKeepsQueue === 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. @@ -457,6 +483,7 @@ export function loadConfig(path: string): BotConfig { enabledProviders, savedQueuesEnabled, playKeepsQueue, + playUrlRetries, voiceDucking, defaultPlatform: defaultPlatformPref, }; diff --git a/src/music/netease.test.ts b/src/music/netease.test.ts index 4e8e961..bffd55c 100644 --- a/src/music/netease.test.ts +++ b/src/music/netease.test.ts @@ -314,3 +314,32 @@ 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"]); + }); +}); diff --git a/src/music/netease.ts b/src/music/netease.ts index 528859a..07bc429 100644 --- a/src/music/netease.ts +++ b/src/music/netease.ts @@ -206,6 +206,24 @@ export class NeteaseProvider implements MusicProvider { 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 { const res = await this.api.get("/song/detail", { params: { ids: songId, ...this.cookieParams }, diff --git a/src/music/provider.ts b/src/music/provider.ts index ba9990c..890b5ed 100644 --- a/src/music/provider.ts +++ b/src/music/provider.ts @@ -134,6 +134,17 @@ export interface MusicProvider { setCookie(cookie: string): void; getCookie(): string; getAuthStatus(): Promise; + /** + * 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[]; getPersonalFm?(): Promise; getDailyRecommendSongs?(): Promise; getUserPlaylists?(): Promise; diff --git a/src/web/api/bot.ts b/src/web/api/bot.ts index 043a578..ad0df9d 100755 --- a/src/web/api/bot.ts +++ b/src/web/api/bot.ts @@ -75,6 +75,8 @@ export function createBotRouter( localAudioEnabled: config.localAudioEnabled, savedQueuesEnabled: config.savedQueuesEnabled, 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(), @@ -94,6 +96,7 @@ export function createBotRouter( voiceDucking, guestMode, adminGroups, + playUrlRetries, } = req.body; const hasIdle = idleTimeoutMinutes !== undefined; @@ -104,10 +107,24 @@ 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; + } if (hasIdle) config.idleTimeoutMinutes = idleTimeoutMinutes; if (hasAutoPause) config.autoPauseOnEmpty = autoPauseOnEmpty; if (hasLocalAudioEnabled) config.localAudioEnabled = localAudioEnabled; + if (hasPlayUrlRetries) config.playUrlRetries = playUrlRetries; // Voice ducking is a partial settings block. Merge only known, strictly // valid fields so malformed JSON cannot replace the object or inject NaN / @@ -283,6 +300,8 @@ export function createBotRouter( localAudioEnabled: config.localAudioEnabled, savedQueuesEnabled: config.savedQueuesEnabled, 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(),