From c2771ab9a7f0cdcf1be56dee1aa4208871adbb07 Mon Sep 17 00:00:00 2001 From: jiayuLian Date: Sun, 8 Nov 2026 17:20:01 +0800 Subject: [PATCH 01/10] =?UTF-8?q?fix(playback):=20retry=20and=20downgrade?= =?UTF-8?q?=20quality=20before=20reporting=20=E6=97=A0=E6=B3=95=E6=92=AD?= =?UTF-8?q?=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(), From e9995c1e303857cd072d4f178443da9afcc28883 Mon Sep 17 00:00:00 2001 From: jiayuLian Date: Sun, 8 Nov 2026 17:53:43 +0800 Subject: [PATCH 02/10] fix(playback): back off properly when NetEase risk control answers -460 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Measured directly against the sidecar on a cloud host, same song, same minute: GET /song/url/v1?id=1827600686&level=exhigh → 400 {"code":-460,"message":"检测到您的网络环境存在风险,请稍后再试"} GET …&cookie= → 200, 320k url So the "无法播放(区域/版权限制)" everyone was chasing is NetEase rejecting the host's IP, not a copyright or membership problem. It arrives as a 4xx, which axios reports as ERR_BAD_REQUEST — indistinguishable from a malformed request without reading the body — and that is why it looked like a dead end in the logs. The previous commit retried everything on a flat 250ms backoff. For -460 that is useless: the risk window lasts a few seconds, so three re-pokes inside 750ms all land in it and the budget is spent without ever giving the upstream time to relax. It also spent the 120ms level-switch delay on it, but -460 ignores which quality we ask for. Now: - `netease.getSongUrl` recognises 400 + `code: -460` and rethrows `RiskControlError` (provider.ts), so the retry layer can tell "wait this out" from "this track will never play". - `resolveUrlWithRetry` waits `RISK_CONTROL_BACKOFF_MS * attempt` (800ms, 1600ms, …) instead of 250ms, and never uses the fast level-switch delay while risk controlled. - The failure log now says what actually happened (`hit NetEase risk control (-460) — backing off`) instead of dumping an axios error that reads like a broken request. Everything else keeps the old timing: a plain thrown error still retries at 250ms, a genuine 400 (`code: 400`) is not reclassified, and a 200 with `url:null` still falls through to the quality ladder. 11 new tests: -460 → RiskControlError, genuine 400 untouched, HTML 400 untouched, message preserved, exponential wait, no 120ms switch under risk control, recovery stops spending, cancellation during a wait. --- src/bot/instance.ts | 11 ++++- src/bot/url-retry.test.ts | 93 +++++++++++++++++++++++++++++++++++++++ src/bot/url-retry.ts | 22 ++++++++- src/music/netease.test.ts | 72 ++++++++++++++++++++++++++++++ src/music/netease.ts | 32 ++++++++++++-- src/music/provider.ts | 28 ++++++++++++ 6 files changed, 253 insertions(+), 5 deletions(-) diff --git a/src/bot/instance.ts b/src/bot/instance.ts index e87cddb..b16ba79 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -8,6 +8,7 @@ import { } from "../ts-protocol/client.js"; import { AudioPlayer } from "../audio/player.js"; import { resolveUrlWithRetry } from "./url-retry.js"; +import { RISK_CONTROL_CODE, RiskControlError } from "../music/provider.js"; import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js"; import type { MusicProvider, Platform, Song, SongUrlResult } from "../music/provider.js"; import { @@ -1064,7 +1065,15 @@ export class BotInstance extends EventEmitter { isCancelled: () => !this.connected, onAttemptFailed: ({ attempt, total, quality, error }) => { const fields = { songId: song.id, name: song.name, attempt, total, quality }; - if (error) { + 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"); diff --git a/src/bot/url-retry.test.ts b/src/bot/url-retry.test.ts index b4cfef3..565b422 100644 --- a/src/bot/url-retry.test.ts +++ b/src/bot/url-retry.test.ts @@ -1,9 +1,11 @@ import { describe, expect, it, vi } from "vitest"; +import { RiskControlError } 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"; @@ -309,3 +311,94 @@ describe("resolveUrlWithRetry — quality fallback", () => { 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("grows the wait from RISK_CONTROL_BACKOFF_MS instead of 250ms", async () => { + const { sleep, delays } = recordingSleep(); + const result = await resolveUrlWithRetry({ + retries: 2, + resolve: async () => { + throw new RiskControlError("网络环境风险 (-460)"); + }, + sleep, + }); + + expect(result).toBeNull(); + expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS, RISK_CONTROL_BACKOFF_MS * 2]); + // Every one of them is longer than a plain transient retry would have been. + for (const d of delays) expect(d).toBeGreaterThan(DEFAULT_URL_RETRY_BACKOFF_MS); + }); + + it("does not fall back to the fast level-switch delay while risk controlled", async () => { + const { sleep, delays } = recordingSleep(); + await resolveUrlWithRetry({ + retries: 0, + resolve: async () => { + throw new RiskControlError("网络环境风险 (-460)"); + }, + fallbacks: ["higher", "standard"], + sleep, + }); + + // -460 ignores which quality we ask for, so 120ms would just burn attempts. + expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS, RISK_CONTROL_BACKOFF_MS]); + expect(delays).not.toContain(QUALITY_SWITCH_BACKOFF_MS); + }); + + it("recovers as soon as the window passes, and stops spending", async () => { + let attempts = 0; + const { sleep, delays } = recordingSleep(); + const result = await resolveUrlWithRetry({ + retries: 3, + resolve: async () => { + attempts += 1; + if (attempts < 3) 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(3); + expect(delays).toHaveLength(2); + }); + + 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(); + }); +}); diff --git a/src/bot/url-retry.ts b/src/bot/url-retry.ts index 58ebf41..2250eec 100644 --- a/src/bot/url-retry.ts +++ b/src/bot/url-retry.ts @@ -1,3 +1,4 @@ +import { RiskControlError } from "../music/provider.js"; import type { SongUrlResult } from "../music/provider.js"; /** @@ -35,6 +36,17 @@ export const DEFAULT_URL_RETRY_BACKOFF_MS = 250; */ export const QUALITY_SWITCH_BACKOFF_MS = 120; +/** + * Delay after a -460 (NetEase IP risk control) failure. + * + * 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. 800ms × attempt (800, 1600, …) covers roughly the window users + * reported clicking through by hand, without stalling the queue for long. + */ +export const RISK_CONTROL_BACKOFF_MS = 800; + /** * Normalise a config value into a usable retry count. * Anything non-numeric (legacy config, `"3"`, `null`) means "no retries", which @@ -91,13 +103,20 @@ export async function resolveUrlWithRetry( 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; 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; + const wait = riskControlled + ? RISK_CONTROL_BACKOFF_MS * Math.max(1, sameQualityAttempt) + : 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; @@ -110,6 +129,7 @@ export async function resolveUrlWithRetry( } catch (err) { error = err; } + riskControlled = error instanceof RiskControlError; 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; diff --git a/src/music/netease.test.ts b/src/music/netease.test.ts index bffd55c..587f7eb 100644 --- a/src/music/netease.test.ts +++ b/src/music/netease.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi } from "vitest"; +import { RiskControlError } from "./provider.js"; import { parseLyrics, mapNeteaseAlbums, @@ -343,3 +344,74 @@ describe("NetEase quality fallback ladder", () => { 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= → 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) { + 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("keeps the upstream message so the log says what happened", async () => { + const p = providerWithApi(async () => { + throw httpError(400, { code: -460, message: "检测到您的网络环境存在风险,请稍后再试" }); + }); + await expect(p.getSongUrl("1827600686")).rejects.toThrow(/风险/); + }); + + 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, "Bad Request"); + }); + await expect(p.getSongUrl("1")).rejects.not.toBeInstanceOf(RiskControlError); + }); + + it("still returns null for a 200 that carries no url", async () => { + const p = providerWithApi(async () => ({ data: { data: [{ url: null, code: 404 }] } })); + expect(await p.getSongUrl("1")).toBeNull(); + }); + + 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); + }); +}); diff --git a/src/music/netease.ts b/src/music/netease.ts index 07bc429..b513678 100644 --- a/src/music/netease.ts +++ b/src/music/netease.ts @@ -1,4 +1,5 @@ import axios, { type AxiosInstance } from "axios"; +import { RISK_CONTROL_CODE, RiskControlError } from "./provider.js"; import type { MusicProvider, Song, @@ -114,6 +115,21 @@ 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; message?: string } }; + }; + if (e?.response?.status === 400 && e.response.data?.code === RISK_CONTROL_CODE) { + return new RiskControlError(e.response.data.message ?? "网络环境风险 (-460)"); + } + return null; +} + // 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 }, @@ -197,9 +213,19 @@ export class NeteaseProvider implements MusicProvider { async getSongUrl(songId: string, quality?: string): Promise { const level = quality ?? this.quality; - const res = await this.api.get("/song/url/v1", { - params: { id: songId, level, ...this.cookieParams }, - }); + let res; + try { + res = await this.api.get("/song/url/v1", { + params: { id: songId, level, ...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; diff --git a/src/music/provider.ts b/src/music/provider.ts index 890b5ed..d7e6e5b 100644 --- a/src/music/provider.ts +++ b/src/music/provider.ts @@ -34,6 +34,34 @@ export interface SongUrlResult { trialDuration?: number; } +/** + * NetEase rate-limits by IP, not by request shape. When it decides the caller's + * network looks risky it answers **HTTP 400** with + * + * {"code":-460,"message":"检测到您的网络环境存在风险,请稍后再试"} + * + * Cloud-host IPs hit this constantly; it clears up on its own after a few + * seconds. Because it is a 4xx, axios reports `ERR_BAD_REQUEST` — identical to + * a genuinely malformed request — so the only way to tell them apart is to read + * the response body. The distinction matters: -460 is worth retrying, a bad + * request never is. + * + * Measured on a live host: the anonymous call `?id=…&level=exhigh` answered + * 400/-460 every time, while the same call with the account cookie answered 200 + * and returned a full 320k URL. Intermittently, the cookie version is also + * rejected — which is exactly the "click play five times until it works" + * behaviour users report. + */ +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"; + } +} + export interface Playlist { id: string; name: string; From 4c25cfe5e521a45eb1dec9ced45cb0f2402182f2 Mon Sep 17 00:00:00 2001 From: jiayuLian Date: Sun, 8 Nov 2026 18:28:36 +0800 Subject: [PATCH 03/10] =?UTF-8?q?fix(playback):=20name=20the=20real=20reas?= =?UTF-8?q?on=20instead=20of=20=E3=80=8C=E5=8C=BA=E5=9F=9F/=E7=89=88?= =?UTF-8?q?=E6=9D=83=E9=99=90=E5=88=B6=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every playback failure produced the same sentence: 无法播放「XXX」(区域/版权限制) It was wrong for at least four different causes, all of which take a different fix: - the account has no membership → open one (or use the shared login) - the track is delisted / region-locked → pick another track - this quality level is not ours → drop the level (or wait for the fix) - upstream refused the IP (-460) → wait, then retry Measured on the reporter's own library: a free track (fee=8) returned `url:null` at exhigh while playing fine at higher — "no copyright" was never true for it. Three separate debugging sessions went after a copyright problem because the message said so. The information was there all along: `/song/url/v1` returns `code`, `fee`, `payed` and `level` on every response. Nothing read them. What this does: - `PlayFailure` / `PlayFailureCode` in provider.ts: one shape for "why", with a ready-to-render `message` and the raw upstream fields kept separately for logs. - `netease.getSongUrl` throws `SongUrlUnavailable` instead of returning a bare `null` for a 200-with-no-URL, classified by the fields above. Providers that have not adopted it keep returning null — `toPlayFailure` covers both. - `resolveUrlWithRetry` gains `onExhausted`, called once when the budget is spent (never on cancellation — pressing stop is not a failure) and carrying the last attempt's error. - `BotInstance` keeps the result as `lastPlayFailure` and exposes `getLastPlayFailure()`. Kept as a field rather than a second return value because `resolveAndPlay` has ~20 call sites and its boolean is load-bearing in tests; only the web routes need the explanation. - `player.ts` renders that cause: 「无法播放「X」:需要会员(exhigh)」, 「…:当前音质无播放权限(higher)」, 「…:无版权或已下架」. Batch paths (playlist / album / artist) append 「,最近一次:…」 instead of claiming every track had a copyright problem. - The failure log line now carries `code`, `quality` and `upstream` (`{"fee":8,"payed":0,"level":"exhigh"}`) — the fields that were missing from the log during the previous two investigations. The old wording survives only as a fallback for a bot that could not name a cause, so behaviour is unchanged when nothing is known. 15 new tests: the five classifications (VIP / album-only / already-paid / delisted / quality), upstream fields preserved, `onExhausted` fires exactly once and never on cancel, still fires for a provider that returns null, and the message is already displayable. Note for reviewers: this changes `netease.getSongUrl` from returning null to throwing. `BotInstance` already wraps it in try/catch on the stream-recovery path, and `resolveUrlWithRetry` catches everything, so the two production callers are covered. Anything that wraps `getSongUrl` itself (e.g. the per-user fallback in #186) needs a `catch` — flagged there. --- src/bot/instance.ts | 56 ++++++++++++++++--- src/bot/url-retry.test.ts | 110 +++++++++++++++++++++++++++++++++++++- src/bot/url-retry.ts | 17 ++++++ src/music/netease.test.ts | 76 ++++++++++++++++++++++++-- src/music/netease.ts | 73 ++++++++++++++++++++++++- src/music/provider.ts | 86 +++++++++++++++++++++++++++++ src/web/api/player.ts | 41 ++++++++++---- 7 files changed, 436 insertions(+), 23 deletions(-) diff --git a/src/bot/instance.ts b/src/bot/instance.ts index b16ba79..8d77ca8 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -8,7 +8,8 @@ import { } from "../ts-protocol/client.js"; import { AudioPlayer } from "../audio/player.js"; import { resolveUrlWithRetry } from "./url-retry.js"; -import { RISK_CONTROL_CODE, RiskControlError } from "../music/provider.js"; +import { RISK_CONTROL_CODE, RiskControlError, toPlayFailure } from "../music/provider.js"; +import type { PlayFailure } from "../music/provider.js"; import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js"; import type { MusicProvider, Platform, Song, SongUrlResult } from "../music/provider.js"; import { @@ -203,6 +204,14 @@ export class BotInstance extends EventEmitter { private fmRequesterName: string | undefined; /** Results of the most recent !search, for "#N" selection (issue #90). */ private lastSearchResults: Song[] = []; + /** + * Why the most recent resolveAndPlay produced nothing, or null. + * + * Kept as an instance field rather than a second return value: `resolveAndPlay` + * has ~20 call sites and its boolean is load-bearing in tests, while only the + * web routes need the explanation. They read this right after a false. + */ + private lastPlayFailure: PlayFailure | null = null; /** 当前曲实际播放时长(试听片段秒数或完整 duration);resolveAndPlay 赋值。 */ private effectiveDuration: number | undefined; /** Resume attempts for the current song's stream (#161); see resumeInterruptedStream. */ @@ -1023,8 +1032,19 @@ export class BotInstance extends EventEmitter { return requestedBy ? { ...song, requestedBy } : { ...song }; } + /** + * Why the last `resolveAndPlay(false)` produced nothing, or null after a + * success. Web routes read this to say what actually went wrong instead of + * the old catch-all 「区域/版权限制」. + */ + getLastPlayFailure(): PlayFailure | null { + return this.lastPlayFailure; + } + /** 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 { + this.lastPlayFailure = null; + if (!this.connected) { this.logger.warn({ songId: song.id, name: song.name }, "resolveAndPlay called on disconnected bot — skipping"); return false; } @@ -1046,9 +1066,6 @@ export class BotInstance extends EventEmitter { song.id = detail.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 @@ -1077,11 +1094,34 @@ export class BotInstance extends EventEmitter { 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"); } }, + // 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 ?? "默认音质"})`, + }; + this.lastPlayFailure = 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) { return false; diff --git a/src/bot/url-retry.test.ts b/src/bot/url-retry.test.ts index 565b422..3193e76 100644 --- a/src/bot/url-retry.test.ts +++ b/src/bot/url-retry.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { RiskControlError } from "../music/provider.js"; +import { RiskControlError, SongUrlUnavailable, toPlayFailure } from "../music/provider.js"; import type { SongUrlResult } from "../music/provider.js"; import { MAX_URL_RETRIES, @@ -402,3 +402,111 @@ describe("resolveUrlWithRetry — risk control backoff", () => { 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(); + }); +}); diff --git a/src/bot/url-retry.ts b/src/bot/url-retry.ts index 2250eec..d791bb5 100644 --- a/src/bot/url-retry.ts +++ b/src/bot/url-retry.ts @@ -77,6 +77,15 @@ export interface ResolveUrlWithRetryOptions { 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; } @@ -106,6 +115,11 @@ export async function resolveUrlWithRetry( // 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; + // 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]; @@ -130,10 +144,13 @@ export async function resolveUrlWithRetry( error = err; } 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; } diff --git a/src/music/netease.test.ts b/src/music/netease.test.ts index 587f7eb..0eb39f9 100644 --- a/src/music/netease.test.ts +++ b/src/music/netease.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi } from "vitest"; -import { RiskControlError } from "./provider.js"; +import { RiskControlError, SongUrlUnavailable } from "./provider.js"; import { parseLyrics, mapNeteaseAlbums, @@ -401,9 +401,13 @@ describe("NetEase risk control (-460)", () => { await expect(p.getSongUrl("1")).rejects.not.toBeInstanceOf(RiskControlError); }); - it("still returns null for a 200 that carries no url", async () => { + // 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 }] } })); - expect(await p.getSongUrl("1")).toBeNull(); + await expect(p.getSongUrl("1")).rejects.toMatchObject({ + failure: { code: "no_copyright" }, + }); }); it("returns the url and the trial window on success", async () => { @@ -415,3 +419,69 @@ describe("NetEase risk control (-460)", () => { 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 | undefined): Promise { + const p = new NeteaseProvider("http://127.0.0.1:3001"); + (p as unknown as { api: { get: () => Promise } }).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 }); + }); +}); diff --git a/src/music/netease.ts b/src/music/netease.ts index b513678..1e8a3ad 100644 --- a/src/music/netease.ts +++ b/src/music/netease.ts @@ -1,5 +1,6 @@ import axios, { type AxiosInstance } from "axios"; -import { RISK_CONTROL_CODE, RiskControlError } from "./provider.js"; +import { RISK_CONTROL_CODE, RiskControlError, SongUrlUnavailable } from "./provider.js"; +import type { PlayFailure } from "./provider.js"; import type { MusicProvider, Song, @@ -130,6 +131,69 @@ function riskControlFrom(err: unknown): RiskControlError | null { 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 | undefined, + body: Record | 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 }, @@ -228,7 +292,12 @@ export class NeteaseProvider implements MusicProvider { } 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) }; } diff --git a/src/music/provider.ts b/src/music/provider.ts index d7e6e5b..52ecee6 100644 --- a/src/music/provider.ts +++ b/src/music/provider.ts @@ -62,6 +62,91 @@ export class RiskControlError extends Error { } } +/** + * 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; +} + +/** + * 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; + } +} + +/** Build the -460 flavour. Kept here so every provider names it identically. */ +export function riskControlFailure( + platform: string, + songId: string, + detail?: string, +): PlayFailure { + return { + platform, + songId, + code: "risk_control", + message: "被音源风控拦截(-460),请稍后重试", + upstream: detail ? { detail } : undefined, + }; +} + +/** + * Normalise anything a failed attempt threw into a `PlayFailure`, so callers + * never have to pattern-match on error classes themselves. + * + * The `unknown` branch truncates the message: axios errors carry the whole + * request config (including the cookie) and would otherwise put kilobytes into + * a UI toast and the log. + */ +export function toPlayFailure(platform: string, songId: string, error: unknown): PlayFailure { + if (error instanceof SongUrlUnavailable) return error.failure; + if (error instanceof RiskControlError) { + return riskControlFailure(platform, songId, error.message); + } + const raw = error instanceof Error ? error.message : ""; + const short = raw.replace(/\s+/g, " ").trim().slice(0, 120); + return { + platform, + songId, + code: "unknown", + message: short ? `解析播放地址失败:${short}` : "解析播放地址失败", + }; +} + export interface Playlist { id: string; name: string; @@ -70,6 +155,7 @@ export interface Playlist { platform: Platform; } + export interface PlaylistDetail { id: string; name: string; diff --git a/src/web/api/player.ts b/src/web/api/player.ts index 487293f..9637e84 100644 --- a/src/web/api/player.ts +++ b/src/web/api/player.ts @@ -61,6 +61,29 @@ export function createPlayerRouter( next(); }); + /** + * One line explaining why a track would not play. + * + * Every failure used to say 「(区域/版权限制)」 — including a lapsed + * membership, a delisted track and a quality level the account cannot + * stream. That single string is why three separate investigations went + * hunting for a copyright problem that was not there. The bot now records + * the real cause; this only falls back to the old wording when it has none. + */ + const whyUnplayable = (bot: any, song: { name?: string; id?: string }): string => { + const label = song.name || song.id || "这首歌"; + const reason: string | undefined = bot?.getLastPlayFailure?.()?.message; + return reason + ? `无法播放「${label}」:${reason}` + : `无法播放「${label}」(区域/版权限制)`; + }; + + /** Same, for the batch paths where a cause is context, not the headline. */ + const lastReason = (bot: any): string => { + const failure = bot?.getLastPlayFailure?.(); + return failure?.message ? `,最近一次:${failure.message}` : ""; + }; + /** Map API platform string to the corresponding command flag. */ const platformFlag = (platform: unknown): string => { if (platform === "bilibili") return "-b"; @@ -370,7 +393,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} 首歌曲均无法播放${lastReason(bot)}` }); return; } @@ -406,7 +429,7 @@ export function createPlayerRouter( const playing = queue.current(); const loadedMsg = queueable.length < totalCount - ? `已加载 ${queueable.length}/${totalCount} 首(其余区域/版权限制)` + ? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放${lastReason(bot)})` : `已加载 ${queueable.length} 首`; if (started && playing) { res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` }); @@ -456,7 +479,7 @@ export function createPlayerRouter( } } if (queueable.length === 0) { - res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无版权可播放(区域/版权限制)` }); + res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无法播放${lastReason(bot)}` }); return; } @@ -484,7 +507,7 @@ export function createPlayerRouter( const playing = queue.current(); const loadedMsg = queueable.length < totalCount - ? `已加载 ${queueable.length}/${totalCount} 首(其余区域/版权限制)` + ? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放${lastReason(bot)})` : `已加载 ${queueable.length} 首`; if (started && playing) { res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` }); @@ -546,7 +569,7 @@ export function createPlayerRouter( } } if (queueable.length === 0) { - res.json({ ok: false, message: `歌手 ${totalCount} 首歌曲均无版权可播放(区域/版权限制)` }); + res.json({ ok: false, message: `歌手 ${totalCount} 首歌曲均无法播放${lastReason(bot)}` }); return; } @@ -577,7 +600,7 @@ export function createPlayerRouter( const playing = queue.current(); const loadedMsg = queueable.length < totalCount - ? `已加载 ${queueable.length}/${totalCount} 首(其余区域/版权限制)` + ? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放${lastReason(bot)})` : `已加载 ${queueable.length} 首`; return started && playing ? { ok: true, message: `${loadedMsg},正在播放:${playing.name}` } @@ -614,7 +637,7 @@ export function createPlayerRouter( const ok = await bot.playSingleSong({ ...song }, requesterName(req)); return ok ? { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` } - : { ok: false, message: `无法播放「${song.name || song.id}」(区域/版权限制)` }; + : { ok: false, message: whyUnplayable(bot, song) }; }); res.json(body); } catch (err) { @@ -656,7 +679,7 @@ export function createPlayerRouter( bot.getPlayer().resetFailures(); const ok = await bot.resolveAndPlay(queue.current()!); if (!ok) { - return { ok: false, message: `无法播放「${song.name || song.id}」(区域/版权限制)` }; + return { ok: false, message: whyUnplayable(bot, song) }; } return { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` }; } @@ -695,7 +718,7 @@ export function createPlayerRouter( bot.getPlayer().resetFailures(); const ok = await bot.resolveAndPlay(queue.current()!); if (!ok) { - return { ok: false, message: `无法播放「${song.name || song.id}」(区域/版权限制)` }; + return { ok: false, message: whyUnplayable(bot, song) }; } return { ok: true, message: `正在播放:${song.name || "Unknown"} - ${song.artist || "Unknown"}` }; }); From 2daae590149029b3c30b9f0cb43c38bedc87c81c Mon Sep 17 00:00:00 2001 From: jiayuLian Date: Sun, 8 Nov 2026 11:21:37 +0000 Subject: [PATCH 04/10] feat(music): optional outbound proxy for the NetEase sidecar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The -460 documented in the previous commit has no code-level fix: NetEase decides by IP, so a cloud-datacenter host gets refused regardless of account, quality or retry budget. The only real remedy is to let the request leave from somewhere else. The sidecar already supports that, and nobody had noticed: `NeteaseCloudMusicApi` reads a `proxy` REQUEST PARAMETER and tunnels through it itself (`util/request.js`, via the `tunnel` package — `httpOverHttp`/`httpsOverHttp`). So this needs **no new dependency, no global-agent patching, and no change to how the sidecar is started**. It is one string carried on the calls we already make. What was added: - `NeteaseProvider.setProxy()` / `getProxy()`. The value goes into `requestParams`, a single getter that already existed for the cookie — which is why all ~20 call sites (search, playlist, album, artist, lyric, playback) pick it up without touching each one again. - `config.musicProxy` (default `""` = direct, i.e. exactly the old behaviour). Only `http(s)://host[:port]` is accepted; anything else falls back to direct rather than silently breaking every music request. - `index.ts` reads it, falls back to `HTTPS_PROXY`/`HTTP_PROXY` from the environment, and logs `NetEase requests will go through a proxy` with the credentials redacted. Deliberate limits: - Only HTTP proxies. The sidecar implements this with a CONNECT tunnel, so a `socks5://` value would be parsed and then fail. Documented on the setter. - Audio is NOT proxied. The player pulls the mp3 from NetEase's CDN with ffmpeg, which knows nothing about this setting. If a deployment needs those requests to share the API's egress IP, it needs a network-level route, not this option. - Config wins over the environment: a container-wide `HTTPS_PROXY` set for unrelated tools must not silently reroute music traffic. 6 new tests: no parameter by default, carried on every call once set, carried on the playback call specifically, kept alongside the cookie, blank means direct, values are trimmed. This is additive and off by default — merging it changes nothing until someone sets `musicProxy`. --- src/data/config.ts | 23 ++++++++++++ src/index.ts | 21 +++++++++++ src/music/netease.test.ts | 70 +++++++++++++++++++++++++++++++++++ src/music/netease.ts | 78 +++++++++++++++++++++++++++++---------- 4 files changed, 172 insertions(+), 20 deletions(-) mode change 100755 => 100644 src/data/config.ts mode change 100755 => 100644 src/index.ts diff --git a/src/data/config.ts b/src/data/config.ts old mode 100755 new mode 100644 index ff0623c..ca58ad1 --- a/src/data/config.ts +++ b/src/data/config.ts @@ -150,6 +150,18 @@ export interface BotConfig { * a hand-edited config cannot turn every failed track into a long stall. */ playUrlRetries: number; + /** + * Outbound HTTP proxy for the NetEase sidecar, e.g. `http://192.168.1.2:8118`. + * + * NetEase rejects cloud-datacenter IPs with `-460` ("网络环境存在风险") no matter + * which account is used, so on a VPS the only fix is to send the request out + * through somewhere else. Empty (the default) = direct, i.e. unchanged. + * + * Only `http://` proxies are supported — the sidecar implements this with a + * CONNECT tunnel. When left empty, `HTTPS_PROXY`/`HTTP_PROXY` from the + * environment is used as a fallback (see index.ts). + */ + musicProxy: string; // 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" @@ -208,6 +220,7 @@ export function getDefaultConfig(): BotConfig { // 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, + musicProxy: "", publicUrl: "", trustProxy: false, guestMode: { @@ -421,6 +434,15 @@ export function loadConfig(path: string): BotConfig { ? Math.min(5, Math.max(0, Math.trunc(rawRetries))) : defaults.playUrlRetries; + // Outbound proxy for the NetEase sidecar. Only http(s) URLs are kept: a + // stray value here would silently break every music request, so anything + // unparseable is dropped back to "direct" instead of being passed through. + const rawMusicProxy = partial.musicProxy; + const musicProxy = + typeof rawMusicProxy === "string" && /^https?:\/\/[^\s]+$/i.test(rawMusicProxy.trim()) + ? rawMusicProxy.trim() + : defaults.musicProxy; + // 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. @@ -484,6 +506,7 @@ export function loadConfig(path: string): BotConfig { savedQueuesEnabled, playKeepsQueue, playUrlRetries, + musicProxy, voiceDucking, defaultPlatform: defaultPlatformPref, }; diff --git a/src/index.ts b/src/index.ts old mode 100755 new mode 100644 index d7d14d1..5dda266 --- a/src/index.ts +++ b/src/index.ts @@ -81,6 +81,27 @@ async function main() { const cookieStore = createCookieStore(COOKIE_DIR); const avatarStore = createAvatarStore(AVATAR_DIR); + + // Outbound proxy for the NetEase sidecar. On a cloud host NetEase answers + // -460 ("网络环境存在风险") by IP, so the request has to leave through somewhere + // else. Config wins over the environment: a container-wide HTTPS_PROXY set + // for unrelated tools must not silently reroute music traffic. + const musicProxy = + config.musicProxy || + process.env.HTTPS_PROXY || + process.env.https_proxy || + process.env.HTTP_PROXY || + process.env.http_proxy || + ""; + if (musicProxy) { + neteaseProvider.setProxy(musicProxy); + // Credentials in a proxy URL are common; never put them in the log. + logger.info( + { proxy: musicProxy.replace(/\/\/[^@/]+@/, "//***@") }, + "NetEase requests will go through a proxy", + ); + } + const neteaseCookie = cookieStore.load("netease"); if (neteaseCookie) neteaseProvider.setCookie(neteaseCookie); const qqCookie = cookieStore.load("qq"); diff --git a/src/music/netease.test.ts b/src/music/netease.test.ts index 0eb39f9..f5793d5 100644 --- a/src/music/netease.test.ts +++ b/src/music/netease.test.ts @@ -485,3 +485,73 @@ describe("NetEase — why a track has no URL", () => { expect(err.failure.upstream).toMatchObject({ fee: 8, payed: 0, level: "higher", br: 192000 }); }); }); + +// --------------------------------------------------------------------------- +// Outbound proxy +// +// On a cloud host NetEase answers -460 by IP, so the request has to leave from +// somewhere else. The sidecar (NeteaseCloudMusicApi) supports this natively via +// a `proxy` request parameter — no new dependency, no global-agent patching. +// These tests pin that it is carried on EVERY call and that the default stays +// exactly as before. +// --------------------------------------------------------------------------- +describe("NetEase — outbound proxy", () => { + function capture() { + const seen: Array> = []; + const p = new NeteaseProvider("http://127.0.0.1:3001"); + (p as unknown as { api: { get: (u: string, c: any) => Promise } }).api = { + get: async (_url: string, cfg: any) => { + seen.push({ ...cfg?.params }); + return { data: { result: {}, data: [{ url: null, code: 200, fee: 8, level: "exhigh" }] } }; + }, + }; + return { p, seen }; + } + + it("sends no proxy parameter by default — behaviour is unchanged", async () => { + const { p, seen } = capture(); + await p.search("x").catch(() => {}); + expect(seen.length).toBeGreaterThan(0); + for (const params of seen) expect(params.proxy).toBeUndefined(); + }); + + it("carries the proxy on every call once configured", async () => { + const { p, seen } = capture(); + p.setProxy("http://192.168.1.9:8118"); + await p.search("x").catch(() => {}); + expect(seen.length).toBeGreaterThan(0); + for (const params of seen) expect(params.proxy).toBe("http://192.168.1.9:8118"); + }); + + it("carries it on the playback call too — that is the one that gets -460", async () => { + const { p, seen } = capture(); + p.setProxy("http://192.168.1.9:8118"); + await p.getSongUrl("1", "standard").catch(() => {}); + expect(seen).toHaveLength(1); + expect(seen[0]).toMatchObject({ id: "1", level: "standard", proxy: "http://192.168.1.9:8118" }); + }); + + it("keeps the cookie alongside the proxy", async () => { + const { p, seen } = capture(); + p.setCookie("MUSIC_U=abc"); + p.setProxy("http://h:1"); + await p.getSongUrl("1").catch(() => {}); + // cookie is normalised on the way in, so compare loosely. + expect(String(seen[0].cookie)).toContain("MUSIC_U=abc"); + expect(seen[0].proxy).toBe("http://h:1"); + }); + + it("treats a blank value as direct service", async () => { + const { p, seen } = capture(); + p.setProxy(" "); + await p.search("x").catch(() => {}); + for (const params of seen) expect(params.proxy).toBeUndefined(); + expect(p.getProxy()).toBe(""); + }); + + it("trims the value it is given", () => { + const p = new NeteaseProvider("http://x"); + p.setProxy(" http://h:1 "); + expect(p.getProxy()).toBe("http://h:1"); + }); +}); diff --git a/src/music/netease.ts b/src/music/netease.ts index 1e8a3ad..41b484e 100644 --- a/src/music/netease.ts +++ b/src/music/netease.ts @@ -209,6 +209,8 @@ export class NeteaseProvider implements MusicProvider { private api: AxiosInstance; private cookie = ""; private quality = "exhigh"; + /** Outbound HTTP proxy for the sidecar's own requests. "" = direct. */ + private proxy = ""; private readonly baseUrl: string; constructor(baseUrl: string) { @@ -231,13 +233,49 @@ export class NeteaseProvider implements MusicProvider { return this.cookie ? { cookie: this.cookie } : {}; } + /** + * Outbound proxy for every sidecar call. + * + * NetEase limits by IP: a cloud-datacenter address answers `-460` + * ("检测到您的网络环境存在风险") on most requests no matter which account asks, + * while the same account from a residential IP works. There is no code-level + * fix — the request has to originate somewhere else. + * + * The sidecar already knows how: `NeteaseCloudMusicApi` reads a `proxy` + * request parameter and tunnels through it itself (`util/request.js`, via the + * `tunnel` package). So this needs no new dependency and no global-agent + * patching — just carry the value. + * + * Only `http://` proxies work (the sidecar implements this with CONNECT). + * Empty means direct, i.e. exactly the previous behaviour. + */ + setProxy(proxy: string): void { + this.proxy = (proxy ?? "").trim(); + } + + getProxy(): string { + return this.proxy; + } + + private get proxyParams(): Record { + return this.proxy ? { proxy: this.proxy } : {}; + } + + /** + * Everything every call needs. One getter so a field added here cannot be + * forgotten on any of the ~20 call sites. + */ + private get requestParams(): Record { + return { ...this.cookieParams, ...this.proxyParams }; + } + async search(query: string, limit = 20, offset = 0): Promise { // /cloudsearch supports offset for every type. Songs, playlists (type 1000) // and albums (type 10) are all limit/offset-driven so the web can page past // the first page (playlists/albums were previously hardcoded to limit: 10). const [songRes, playlistRes, albumRes, artistRes] = await Promise.all([ this.api.get("/cloudsearch", { - params: { keywords: query, type: 1, limit, offset, ...this.cookieParams }, + params: { keywords: query, type: 1, limit, offset, ...this.requestParams }, }), this.api.get("/cloudsearch", { params: { @@ -245,14 +283,14 @@ export class NeteaseProvider implements MusicProvider { type: 1000, limit, offset, - ...this.cookieParams, + ...this.requestParams, }, }), this.api.get("/cloudsearch", { - params: { keywords: query, type: 10, limit, offset, ...this.cookieParams }, + params: { keywords: query, type: 10, limit, offset, ...this.requestParams }, }), this.api.get("/cloudsearch", { - params: { keywords: query, type: 100, limit, offset, ...this.cookieParams }, + params: { keywords: query, type: 100, limit, offset, ...this.requestParams }, }), ]); @@ -280,7 +318,7 @@ export class NeteaseProvider implements MusicProvider { let res; try { res = await this.api.get("/song/url/v1", { - params: { id: songId, level, ...this.cookieParams }, + params: { id: songId, level, ...this.requestParams }, }); } catch (err) { // -460 arrives as HTTP 400, and left as-is it looks like "this track is @@ -321,21 +359,21 @@ export class NeteaseProvider implements MusicProvider { async getSongDetail(songId: string): Promise { const res = await this.api.get("/song/detail", { - params: { ids: songId, ...this.cookieParams }, + params: { ids: songId, ...this.requestParams }, }); return mapNeteaseSongs(res.data?.songs)[0] ?? null; } async getPlaylistSongs(playlistId: string): Promise { const res = await this.api.get("/playlist/track/all", { - params: { id: playlistId, ...this.cookieParams }, + params: { id: playlistId, ...this.requestParams }, }); return mapNeteaseSongs(res.data?.songs); } async getRecommendPlaylists(): Promise { const res = await this.api.get("/personalized", { - params: { limit: 10, ...this.cookieParams }, + params: { limit: 10, ...this.requestParams }, }); return (res.data?.result ?? []).map((p: any) => ({ id: String(p.id), @@ -348,7 +386,7 @@ export class NeteaseProvider implements MusicProvider { async getAlbumSongs(albumId: string): Promise { const res = await this.api.get("/album", { - params: { id: albumId, ...this.cookieParams }, + params: { id: albumId, ...this.requestParams }, }); return mapNeteaseSongs(res.data?.songs); } @@ -358,7 +396,7 @@ export class NeteaseProvider implements MusicProvider { // separately via /artist/songs (order=hot) so the artist page's three // upstream calls stay independent of each other. const res = await this.api.get("/artists", { - params: { id: artistId, ...this.cookieParams }, + params: { id: artistId, ...this.requestParams }, }); const a = res.data?.artist; if (!a) return null; @@ -375,7 +413,7 @@ export class NeteaseProvider implements MusicProvider { limit, offset: 0, order: "hot", - ...this.cookieParams, + ...this.requestParams, }, }); return mapNeteaseSongs(res.data?.songs); @@ -383,7 +421,7 @@ export class NeteaseProvider implements MusicProvider { async getArtistAlbums(artistId: string, limit = 20): Promise { const res = await this.api.get("/artist/album", { - params: { id: artistId, limit, offset: 0, ...this.cookieParams }, + params: { id: artistId, limit, offset: 0, ...this.requestParams }, }); return mapNeteaseAlbums(res.data?.hotAlbums); } @@ -404,7 +442,7 @@ export class NeteaseProvider implements MusicProvider { limit: safeLimit, offset: safeOffset, order: "hot", - ...this.cookieParams, + ...this.requestParams, }, }); const songs = mapNeteaseSongs(res.data?.songs); @@ -418,7 +456,7 @@ export class NeteaseProvider implements MusicProvider { async getLyrics(songId: string): Promise { const res = await this.api.get("/lyric", { - params: { id: songId, ...this.cookieParams }, + params: { id: songId, ...this.requestParams }, }); return parseLyrics( res.data?.lrc?.lyric ?? "", @@ -514,7 +552,7 @@ export class NeteaseProvider implements MusicProvider { if (!this.cookie) return { loggedIn: false }; try { const res = await this.api.get("/login/status", { - params: { ...this.cookieParams }, + params: { ...this.requestParams }, }); const profile = res.data?.data?.profile; if (profile) { @@ -532,21 +570,21 @@ export class NeteaseProvider implements MusicProvider { async getPersonalFm(): Promise { const res = await this.api.get("/personal_fm", { - params: { ...this.cookieParams }, + params: { ...this.requestParams }, }); return mapNeteaseSongs(res.data?.data); } async getDailyRecommendSongs(): Promise { const res = await this.api.get("/recommend/songs", { - params: { ...this.cookieParams }, + params: { ...this.requestParams }, }); return mapNeteaseSongs(res.data?.data?.dailySongs); } async getPlaylistDetail(playlistId: string): Promise { const res = await this.api.get("/playlist/detail", { - params: { id: playlistId, ...this.cookieParams }, + params: { id: playlistId, ...this.requestParams }, }); const p = res.data?.playlist; if (!p) return null; @@ -562,13 +600,13 @@ export class NeteaseProvider implements MusicProvider { async getUserPlaylists(): Promise { // First get user ID from login status const statusRes = await this.api.get("/login/status", { - params: { ...this.cookieParams }, + params: { ...this.requestParams }, }); const uid = statusRes.data?.data?.profile?.userId; if (!uid) return []; const res = await this.api.get("/user/playlist", { - params: { uid, ...this.cookieParams }, + params: { uid, ...this.requestParams }, }); return (res.data?.playlist ?? []).map((p: any) => ({ id: String(p.id), From d8a8574323a3e6fe776971d546fcd57a0b0bfd3f Mon Sep 17 00:00:00 2001 From: jiayuLian <87891011+jiayuLian@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:34:17 +0800 Subject: [PATCH 05/10] tune(playback): -460 backoff 800ms -> 2500ms, matching the observed risk-control window --- src/bot/url-retry.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/bot/url-retry.ts b/src/bot/url-retry.ts index d791bb5..717e181 100644 --- a/src/bot/url-retry.ts +++ b/src/bot/url-retry.ts @@ -42,10 +42,15 @@ export const QUALITY_SWITCH_BACKOFF_MS = 120; * 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. 800ms × attempt (800, 1600, …) covers roughly the window users - * reported clicking through by hand, without stalling the queue for long. + * budget. + * + * Sized against the manual workaround users reported: the first click fails, the + * toast sits there for ~2-3s, and the very next click succeeds. So the window is + * a couple of seconds, not a couple hundred milliseconds. 2500ms × attempt puts + * the second attempt at 2.5s and the third at ~7.5s, which is reliably outside + * it; anything shorter just spends the retry budget inside the window. */ -export const RISK_CONTROL_BACKOFF_MS = 800; +export const RISK_CONTROL_BACKOFF_MS = 2500; /** * Normalise a config value into a usable retry count. From d2c44ed256e066125c808cbc66be342b765cd235 Mon Sep 17 00:00:00 2001 From: jiayuLian <87891011+jiayuLian@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:13:39 +0800 Subject: [PATCH 06/10] fix(playback): stop walking the quality ladder once -460 hits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -460 is NetEase refusing the caller's IP, not a property of the track, so asking for a lower quality cannot succeed — it only adds another RISK_CONTROL_BACKOFF_MS of silence before the same error surfaces. With the default budget (2 retries + 2 NetEase fallback levels) a blocked host spent ~17s before the user saw anything, which is worse than the instant failure this replaced. Bail out as soon as the phase changes instead. --- src/bot/url-retry.test.ts | 39 +++++++++++++++++++++++++++++++++------ src/bot/url-retry.ts | 8 ++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/src/bot/url-retry.test.ts b/src/bot/url-retry.test.ts index 3193e76..6ab20ea 100644 --- a/src/bot/url-retry.test.ts +++ b/src/bot/url-retry.test.ts @@ -341,20 +341,47 @@ describe("resolveUrlWithRetry — risk control backoff", () => { for (const d of delays) expect(d).toBeGreaterThan(DEFAULT_URL_RETRY_BACKOFF_MS); }); - it("does not fall back to the fast level-switch delay while risk controlled", async () => { + it("gives up instead of stepping down the ladder while risk controlled", async () => { + let attempts = 0; const { sleep, delays } = recordingSleep(); - await resolveUrlWithRetry({ - retries: 0, + const result = await resolveUrlWithRetry({ + retries: 1, resolve: async () => { + attempts += 1; throw new RiskControlError("网络环境风险 (-460)"); }, fallbacks: ["higher", "standard"], sleep, }); - // -460 ignores which quality we ask for, so 120ms would just burn attempts. - expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS, RISK_CONTROL_BACKOFF_MS]); - expect(delays).not.toContain(QUALITY_SWITCH_BACKOFF_MS); + expect(result).toBeNull(); + // 1 + retries attempts at the configured quality, then stop. -460 ignores + // which level we ask for, so each ladder step would only add another + // RISK_CONTROL_BACKOFF_MS of 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 ladder keeps its normal cost. + expect(attempts).toBe(4); }); it("recovers as soon as the window passes, and stops spending", async () => { diff --git a/src/bot/url-retry.ts b/src/bot/url-retry.ts index 717e181..dd105e3 100644 --- a/src/bot/url-retry.ts +++ b/src/bot/url-retry.ts @@ -130,6 +130,14 @@ export async function resolveUrlWithRetry( 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 costs another RISK_CONTROL_BACKOFF_MS. With the + // default budget that turned a blocked host into 17s of silence before the + // failure message — worse than the instant error it replaced. Give up as + // soon as the phase changes rather than when the plan runs out. + if (step.fallback && riskControlled) break; + if (i > 0) { const wait = riskControlled ? RISK_CONTROL_BACKOFF_MS * Math.max(1, sameQualityAttempt) From 178935a63d253a9d0eac6d6b69a42989b42ca9fb Mon Sep 17 00:00:00 2001 From: jiayuLian <87891011+jiayuLian@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:19:58 +0800 Subject: [PATCH 07/10] fix(playback): give every failure a cause, not just the retried ones MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit resolveAndPlay recorded lastPlayFailure only when the retry budget was exhausted. Every early return (bot offline, local audio disabled) and the outer catch left it null, so the web route fell back to the catch-all 「区域/版权限制」 for causes that have nothing to do with copyright. Also move the bilibili detail lookup inside its own try: it is metadata only, and an upstream 4xx there aborted the resolve before the retry budget could even start. --- src/bot/instance.ts | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/src/bot/instance.ts b/src/bot/instance.ts index 8d77ca8..69362cb 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -1046,10 +1046,25 @@ export class BotInstance extends EventEmitter { this.lastPlayFailure = null; if (!this.connected) { this.logger.warn({ songId: song.id, name: song.name }, "resolveAndPlay called on disconnected bot — skipping"); + // Recorded so the web route can say this instead of blaming copyright: + // every early return used to leave lastPlayFailure null, which made the + // UI fall back to the catch-all 「区域/版权限制」 for unrelated causes. + this.lastPlayFailure = { + platform: song.platform, + songId: song.id, + code: "unknown", + message: "机器人未连接,无法播放", + }; return false; } if (song.platform === "local" && !this.isLocalAudioEnabled()) { this.logger.warn({ songId: song.id, name: song.name }, "Local audio playback disabled — refusing track"); + this.lastPlayFailure = { + platform: song.platform, + songId: song.id, + code: "unknown", + message: "该机器人已关闭本地音频播放", + }; return false; } // Clear any accumulated skip votes — every fresh track starts with a @@ -1059,11 +1074,18 @@ export class BotInstance extends EventEmitter { const provider = this.getProviderFor(song.platform); try { 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 (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"); } } // Retries happen here (not in the provider) so every queue path — web @@ -1257,6 +1279,10 @@ export class BotInstance extends EventEmitter { return true; } catch (err) { this.logger.error({ err, songId: song.id }, "Failed to resolve URL"); + // Anything thrown outside the retry budget (detail lookup, spotify + // handoff, player start) still needs a cause, otherwise the web route + // prints the old 「区域/版权限制」 for a cause that is not copyright. + this.lastPlayFailure = toPlayFailure(song.platform, song.id, err); return false; } } From 97ee05f1ef12519273f04525d4d72e014cfc749f Mon Sep 17 00:00:00 2001 From: jiayuLian <87891011+jiayuLian@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:44:15 +0800 Subject: [PATCH 08/10] tune(playback): spend two requests on -460, not three with a 7.5s tail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The risk-control branch grew its delay per attempt (2.5s, then 7.5s) on the assumption that a blocked IP unlocks on a timer. Measured behaviour says otherwise: six back-to-back 128k requests from a blocked host answered -460, -460, -460, -460, 200 — it lets a few through after a while, it does not unlock at a fixed moment. So the third attempt mostly bought silence: five requests and ~4s worst case for the same "still blocked". Cap the whole risk-controlled budget at two requests (one retry after 2.5s) and skip the quality ladder in that state, which -460 ignores anyway. Worst case drops to 2.5s, and when it still fails the message now names the wait (「约 5 秒后再试」) instead of 「请稍后重试」 — a spinner cannot be acted on, a number can. --- src/bot/url-retry.test.ts | 41 ++++++++++++++++++----------------- src/bot/url-retry.ts | 45 +++++++++++++++++++++++++++------------ src/music/provider.ts | 5 ++++- 3 files changed, 56 insertions(+), 35 deletions(-) diff --git a/src/bot/url-retry.test.ts b/src/bot/url-retry.test.ts index 6ab20ea..030dbd2 100644 --- a/src/bot/url-retry.test.ts +++ b/src/bot/url-retry.test.ts @@ -325,27 +325,27 @@ describe("resolveUrlWithRetry — quality fallback", () => { // window and the whole budget is wasted. These tests pin the longer wait. // --------------------------------------------------------------------------- describe("resolveUrlWithRetry — risk control backoff", () => { - it("grows the wait from RISK_CONTROL_BACKOFF_MS instead of 250ms", async () => { + it("retries once after RISK_CONTROL_BACKOFF_MS, then stops", async () => { const { sleep, delays } = recordingSleep(); - const result = await resolveUrlWithRetry({ - retries: 2, - resolve: async () => { - throw new RiskControlError("网络环境风险 (-460)"); - }, - sleep, + const resolve = vi.fn(async () => { + throw new RiskControlError("网络环境风险 (-460)"); }); + const result = await resolveUrlWithRetry({ retries: 2, resolve, sleep }); expect(result).toBeNull(); - expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS, RISK_CONTROL_BACKOFF_MS * 2]); - // Every one of them is longer than a plain transient retry would have been. - for (const d of delays) expect(d).toBeGreaterThan(DEFAULT_URL_RETRY_BACKOFF_MS); + // 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("gives up instead of stepping down the ladder while risk controlled", async () => { + 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: 1, + retries: 5, resolve: async () => { attempts += 1; throw new RiskControlError("网络环境风险 (-460)"); @@ -355,9 +355,9 @@ describe("resolveUrlWithRetry — risk control backoff", () => { }); expect(result).toBeNull(); - // 1 + retries attempts at the configured quality, then stop. -460 ignores - // which level we ask for, so each ladder step would only add another - // RISK_CONTROL_BACKOFF_MS of silence before the same failure surfaces. + // -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]); }); @@ -380,26 +380,27 @@ describe("resolveUrlWithRetry — risk control backoff", () => { 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 ladder keeps its normal cost. + // plain miss, not -460, so the cap no longer applies and the ladder keeps + // its normal cost. expect(attempts).toBe(4); }); - it("recovers as soon as the window passes, and stops spending", async () => { + 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 < 3) throw new RiskControlError("网络环境风险 (-460)"); + 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(3); - expect(delays).toHaveLength(2); + expect(attempts).toBe(2); + expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS]); }); it("still uses the short delay for a plain error", async () => { diff --git a/src/bot/url-retry.ts b/src/bot/url-retry.ts index dd105e3..0094747 100644 --- a/src/bot/url-retry.ts +++ b/src/bot/url-retry.ts @@ -37,21 +37,32 @@ export const DEFAULT_URL_RETRY_BACKOFF_MS = 250; export const QUALITY_SWITCH_BACKOFF_MS = 120; /** - * Delay after a -460 (NetEase IP risk control) failure. + * 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. + * budget inside the same window. * - * Sized against the manual workaround users reported: the first click fails, the - * toast sits there for ~2-3s, and the very next click succeeds. So the window is - * a couple of seconds, not a couple hundred milliseconds. 2500ms × attempt puts - * the second attempt at 2.5s and the third at ~7.5s, which is reliably outside - * it; anything shorter just spends the retry budget inside the 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 @@ -100,7 +111,9 @@ export interface ResolveUrlWithRetryOptions { * * 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. + * 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, @@ -120,6 +133,10 @@ export async function resolveUrlWithRetry( // 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. @@ -132,15 +149,14 @@ export async function resolveUrlWithRetry( // -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 costs another RISK_CONTROL_BACKOFF_MS. With the - // default budget that turned a blocked host into 17s of silence before the - // failure message — worse than the instant error it replaced. Give up as - // soon as the phase changes rather than when the plan runs out. - if (step.fallback && riskControlled) break; + // 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 * Math.max(1, sameQualityAttempt) + ? RISK_CONTROL_BACKOFF_MS : step.fallback ? QUALITY_SWITCH_BACKOFF_MS : backoffMs * sameQualityAttempt; @@ -150,6 +166,7 @@ export async function resolveUrlWithRetry( } let error: unknown; + requestsMade += 1; try { const result = await opts.resolve(step.quality); if (result?.url) return result; diff --git a/src/music/provider.ts b/src/music/provider.ts index 52ecee6..a2c76d1 100644 --- a/src/music/provider.ts +++ b/src/music/provider.ts @@ -119,7 +119,10 @@ export function riskControlFailure( platform, songId, code: "risk_control", - message: "被音源风控拦截(-460),请稍后重试", + // 「约 5 秒」是有依据的:实测同一 IP 连续请求一般是 -460 几次之后放行, + // 重试预算也已经只留一次(RISK_CONTROL_BACKOFF_MS)。给一个具体的等待值, + // 比「请稍后重试」更能让人知道该干嘛。 + message: "被网易云风控拦截(-460),约 5 秒后再试", upstream: detail ? { detail } : undefined, }; } From 406ecda7d7f3e8aab0ff18104d28507d3c28a8c7 Mon Sep 17 00:00:00 2001 From: TIANYAO ZHANG <88520881+ZHANGTIANYAO1@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:52:58 +0800 Subject: [PATCH 09/10] fix(playback): keep retry changes independent of proxy settings --- src/data/config.ts | 23 ------------ src/index.ts | 21 ----------- src/music/netease.test.ts | 70 ----------------------------------- src/music/netease.ts | 78 ++++++++++----------------------------- 4 files changed, 20 insertions(+), 172 deletions(-) mode change 100644 => 100755 src/data/config.ts mode change 100644 => 100755 src/index.ts diff --git a/src/data/config.ts b/src/data/config.ts old mode 100644 new mode 100755 index ca58ad1..ff0623c --- a/src/data/config.ts +++ b/src/data/config.ts @@ -150,18 +150,6 @@ export interface BotConfig { * a hand-edited config cannot turn every failed track into a long stall. */ playUrlRetries: number; - /** - * Outbound HTTP proxy for the NetEase sidecar, e.g. `http://192.168.1.2:8118`. - * - * NetEase rejects cloud-datacenter IPs with `-460` ("网络环境存在风险") no matter - * which account is used, so on a VPS the only fix is to send the request out - * through somewhere else. Empty (the default) = direct, i.e. unchanged. - * - * Only `http://` proxies are supported — the sidecar implements this with a - * CONNECT tunnel. When left empty, `HTTPS_PROXY`/`HTTP_PROXY` from the - * environment is used as a fallback (see index.ts). - */ - musicProxy: string; // 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" @@ -220,7 +208,6 @@ export function getDefaultConfig(): BotConfig { // 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, - musicProxy: "", publicUrl: "", trustProxy: false, guestMode: { @@ -434,15 +421,6 @@ export function loadConfig(path: string): BotConfig { ? Math.min(5, Math.max(0, Math.trunc(rawRetries))) : defaults.playUrlRetries; - // Outbound proxy for the NetEase sidecar. Only http(s) URLs are kept: a - // stray value here would silently break every music request, so anything - // unparseable is dropped back to "direct" instead of being passed through. - const rawMusicProxy = partial.musicProxy; - const musicProxy = - typeof rawMusicProxy === "string" && /^https?:\/\/[^\s]+$/i.test(rawMusicProxy.trim()) - ? rawMusicProxy.trim() - : defaults.musicProxy; - // 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. @@ -506,7 +484,6 @@ export function loadConfig(path: string): BotConfig { savedQueuesEnabled, playKeepsQueue, playUrlRetries, - musicProxy, voiceDucking, defaultPlatform: defaultPlatformPref, }; diff --git a/src/index.ts b/src/index.ts old mode 100644 new mode 100755 index 5dda266..d7d14d1 --- a/src/index.ts +++ b/src/index.ts @@ -81,27 +81,6 @@ async function main() { const cookieStore = createCookieStore(COOKIE_DIR); const avatarStore = createAvatarStore(AVATAR_DIR); - - // Outbound proxy for the NetEase sidecar. On a cloud host NetEase answers - // -460 ("网络环境存在风险") by IP, so the request has to leave through somewhere - // else. Config wins over the environment: a container-wide HTTPS_PROXY set - // for unrelated tools must not silently reroute music traffic. - const musicProxy = - config.musicProxy || - process.env.HTTPS_PROXY || - process.env.https_proxy || - process.env.HTTP_PROXY || - process.env.http_proxy || - ""; - if (musicProxy) { - neteaseProvider.setProxy(musicProxy); - // Credentials in a proxy URL are common; never put them in the log. - logger.info( - { proxy: musicProxy.replace(/\/\/[^@/]+@/, "//***@") }, - "NetEase requests will go through a proxy", - ); - } - const neteaseCookie = cookieStore.load("netease"); if (neteaseCookie) neteaseProvider.setCookie(neteaseCookie); const qqCookie = cookieStore.load("qq"); diff --git a/src/music/netease.test.ts b/src/music/netease.test.ts index f5793d5..0eb39f9 100644 --- a/src/music/netease.test.ts +++ b/src/music/netease.test.ts @@ -485,73 +485,3 @@ describe("NetEase — why a track has no URL", () => { expect(err.failure.upstream).toMatchObject({ fee: 8, payed: 0, level: "higher", br: 192000 }); }); }); - -// --------------------------------------------------------------------------- -// Outbound proxy -// -// On a cloud host NetEase answers -460 by IP, so the request has to leave from -// somewhere else. The sidecar (NeteaseCloudMusicApi) supports this natively via -// a `proxy` request parameter — no new dependency, no global-agent patching. -// These tests pin that it is carried on EVERY call and that the default stays -// exactly as before. -// --------------------------------------------------------------------------- -describe("NetEase — outbound proxy", () => { - function capture() { - const seen: Array> = []; - const p = new NeteaseProvider("http://127.0.0.1:3001"); - (p as unknown as { api: { get: (u: string, c: any) => Promise } }).api = { - get: async (_url: string, cfg: any) => { - seen.push({ ...cfg?.params }); - return { data: { result: {}, data: [{ url: null, code: 200, fee: 8, level: "exhigh" }] } }; - }, - }; - return { p, seen }; - } - - it("sends no proxy parameter by default — behaviour is unchanged", async () => { - const { p, seen } = capture(); - await p.search("x").catch(() => {}); - expect(seen.length).toBeGreaterThan(0); - for (const params of seen) expect(params.proxy).toBeUndefined(); - }); - - it("carries the proxy on every call once configured", async () => { - const { p, seen } = capture(); - p.setProxy("http://192.168.1.9:8118"); - await p.search("x").catch(() => {}); - expect(seen.length).toBeGreaterThan(0); - for (const params of seen) expect(params.proxy).toBe("http://192.168.1.9:8118"); - }); - - it("carries it on the playback call too — that is the one that gets -460", async () => { - const { p, seen } = capture(); - p.setProxy("http://192.168.1.9:8118"); - await p.getSongUrl("1", "standard").catch(() => {}); - expect(seen).toHaveLength(1); - expect(seen[0]).toMatchObject({ id: "1", level: "standard", proxy: "http://192.168.1.9:8118" }); - }); - - it("keeps the cookie alongside the proxy", async () => { - const { p, seen } = capture(); - p.setCookie("MUSIC_U=abc"); - p.setProxy("http://h:1"); - await p.getSongUrl("1").catch(() => {}); - // cookie is normalised on the way in, so compare loosely. - expect(String(seen[0].cookie)).toContain("MUSIC_U=abc"); - expect(seen[0].proxy).toBe("http://h:1"); - }); - - it("treats a blank value as direct service", async () => { - const { p, seen } = capture(); - p.setProxy(" "); - await p.search("x").catch(() => {}); - for (const params of seen) expect(params.proxy).toBeUndefined(); - expect(p.getProxy()).toBe(""); - }); - - it("trims the value it is given", () => { - const p = new NeteaseProvider("http://x"); - p.setProxy(" http://h:1 "); - expect(p.getProxy()).toBe("http://h:1"); - }); -}); diff --git a/src/music/netease.ts b/src/music/netease.ts index 41b484e..1e8a3ad 100644 --- a/src/music/netease.ts +++ b/src/music/netease.ts @@ -209,8 +209,6 @@ export class NeteaseProvider implements MusicProvider { private api: AxiosInstance; private cookie = ""; private quality = "exhigh"; - /** Outbound HTTP proxy for the sidecar's own requests. "" = direct. */ - private proxy = ""; private readonly baseUrl: string; constructor(baseUrl: string) { @@ -233,49 +231,13 @@ export class NeteaseProvider implements MusicProvider { return this.cookie ? { cookie: this.cookie } : {}; } - /** - * Outbound proxy for every sidecar call. - * - * NetEase limits by IP: a cloud-datacenter address answers `-460` - * ("检测到您的网络环境存在风险") on most requests no matter which account asks, - * while the same account from a residential IP works. There is no code-level - * fix — the request has to originate somewhere else. - * - * The sidecar already knows how: `NeteaseCloudMusicApi` reads a `proxy` - * request parameter and tunnels through it itself (`util/request.js`, via the - * `tunnel` package). So this needs no new dependency and no global-agent - * patching — just carry the value. - * - * Only `http://` proxies work (the sidecar implements this with CONNECT). - * Empty means direct, i.e. exactly the previous behaviour. - */ - setProxy(proxy: string): void { - this.proxy = (proxy ?? "").trim(); - } - - getProxy(): string { - return this.proxy; - } - - private get proxyParams(): Record { - return this.proxy ? { proxy: this.proxy } : {}; - } - - /** - * Everything every call needs. One getter so a field added here cannot be - * forgotten on any of the ~20 call sites. - */ - private get requestParams(): Record { - return { ...this.cookieParams, ...this.proxyParams }; - } - async search(query: string, limit = 20, offset = 0): Promise { // /cloudsearch supports offset for every type. Songs, playlists (type 1000) // and albums (type 10) are all limit/offset-driven so the web can page past // the first page (playlists/albums were previously hardcoded to limit: 10). const [songRes, playlistRes, albumRes, artistRes] = await Promise.all([ this.api.get("/cloudsearch", { - params: { keywords: query, type: 1, limit, offset, ...this.requestParams }, + params: { keywords: query, type: 1, limit, offset, ...this.cookieParams }, }), this.api.get("/cloudsearch", { params: { @@ -283,14 +245,14 @@ export class NeteaseProvider implements MusicProvider { type: 1000, limit, offset, - ...this.requestParams, + ...this.cookieParams, }, }), this.api.get("/cloudsearch", { - params: { keywords: query, type: 10, limit, offset, ...this.requestParams }, + params: { keywords: query, type: 10, limit, offset, ...this.cookieParams }, }), this.api.get("/cloudsearch", { - params: { keywords: query, type: 100, limit, offset, ...this.requestParams }, + params: { keywords: query, type: 100, limit, offset, ...this.cookieParams }, }), ]); @@ -318,7 +280,7 @@ export class NeteaseProvider implements MusicProvider { let res; try { res = await this.api.get("/song/url/v1", { - params: { id: songId, level, ...this.requestParams }, + params: { id: songId, level, ...this.cookieParams }, }); } catch (err) { // -460 arrives as HTTP 400, and left as-is it looks like "this track is @@ -359,21 +321,21 @@ export class NeteaseProvider implements MusicProvider { async getSongDetail(songId: string): Promise { const res = await this.api.get("/song/detail", { - params: { ids: songId, ...this.requestParams }, + params: { ids: songId, ...this.cookieParams }, }); return mapNeteaseSongs(res.data?.songs)[0] ?? null; } async getPlaylistSongs(playlistId: string): Promise { const res = await this.api.get("/playlist/track/all", { - params: { id: playlistId, ...this.requestParams }, + params: { id: playlistId, ...this.cookieParams }, }); return mapNeteaseSongs(res.data?.songs); } async getRecommendPlaylists(): Promise { const res = await this.api.get("/personalized", { - params: { limit: 10, ...this.requestParams }, + params: { limit: 10, ...this.cookieParams }, }); return (res.data?.result ?? []).map((p: any) => ({ id: String(p.id), @@ -386,7 +348,7 @@ export class NeteaseProvider implements MusicProvider { async getAlbumSongs(albumId: string): Promise { const res = await this.api.get("/album", { - params: { id: albumId, ...this.requestParams }, + params: { id: albumId, ...this.cookieParams }, }); return mapNeteaseSongs(res.data?.songs); } @@ -396,7 +358,7 @@ export class NeteaseProvider implements MusicProvider { // separately via /artist/songs (order=hot) so the artist page's three // upstream calls stay independent of each other. const res = await this.api.get("/artists", { - params: { id: artistId, ...this.requestParams }, + params: { id: artistId, ...this.cookieParams }, }); const a = res.data?.artist; if (!a) return null; @@ -413,7 +375,7 @@ export class NeteaseProvider implements MusicProvider { limit, offset: 0, order: "hot", - ...this.requestParams, + ...this.cookieParams, }, }); return mapNeteaseSongs(res.data?.songs); @@ -421,7 +383,7 @@ export class NeteaseProvider implements MusicProvider { async getArtistAlbums(artistId: string, limit = 20): Promise { const res = await this.api.get("/artist/album", { - params: { id: artistId, limit, offset: 0, ...this.requestParams }, + params: { id: artistId, limit, offset: 0, ...this.cookieParams }, }); return mapNeteaseAlbums(res.data?.hotAlbums); } @@ -442,7 +404,7 @@ export class NeteaseProvider implements MusicProvider { limit: safeLimit, offset: safeOffset, order: "hot", - ...this.requestParams, + ...this.cookieParams, }, }); const songs = mapNeteaseSongs(res.data?.songs); @@ -456,7 +418,7 @@ export class NeteaseProvider implements MusicProvider { async getLyrics(songId: string): Promise { const res = await this.api.get("/lyric", { - params: { id: songId, ...this.requestParams }, + params: { id: songId, ...this.cookieParams }, }); return parseLyrics( res.data?.lrc?.lyric ?? "", @@ -552,7 +514,7 @@ export class NeteaseProvider implements MusicProvider { if (!this.cookie) return { loggedIn: false }; try { const res = await this.api.get("/login/status", { - params: { ...this.requestParams }, + params: { ...this.cookieParams }, }); const profile = res.data?.data?.profile; if (profile) { @@ -570,21 +532,21 @@ export class NeteaseProvider implements MusicProvider { async getPersonalFm(): Promise { const res = await this.api.get("/personal_fm", { - params: { ...this.requestParams }, + params: { ...this.cookieParams }, }); return mapNeteaseSongs(res.data?.data); } async getDailyRecommendSongs(): Promise { const res = await this.api.get("/recommend/songs", { - params: { ...this.requestParams }, + params: { ...this.cookieParams }, }); return mapNeteaseSongs(res.data?.data?.dailySongs); } async getPlaylistDetail(playlistId: string): Promise { const res = await this.api.get("/playlist/detail", { - params: { id: playlistId, ...this.requestParams }, + params: { id: playlistId, ...this.cookieParams }, }); const p = res.data?.playlist; if (!p) return null; @@ -600,13 +562,13 @@ export class NeteaseProvider implements MusicProvider { async getUserPlaylists(): Promise { // First get user ID from login status const statusRes = await this.api.get("/login/status", { - params: { ...this.requestParams }, + params: { ...this.cookieParams }, }); const uid = statusRes.data?.data?.profile?.userId; if (!uid) return []; const res = await this.api.get("/user/playlist", { - params: { uid, ...this.requestParams }, + params: { uid, ...this.cookieParams }, }); return (res.data?.playlist ?? []).map((p: any) => ({ id: String(p.id), From 90a4d809581b6f323628b58c714a4c9075d0f57a Mon Sep 17 00:00:00 2001 From: TIANYAO ZHANG <88520881+ZHANGTIANYAO1@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:57:48 +0800 Subject: [PATCH 10/10] fix(playback): cancel stale retries and scope failure messages --- src/bot/instance.test.ts | 17 +++++ src/bot/instance.ts | 126 +++++++++++++++++--------------------- src/bot/url-retry.ts | 6 +- src/music/netease.test.ts | 6 +- src/music/netease.ts | 4 +- src/music/provider.ts | 61 +++--------------- src/web/api/player.ts | 80 +++++++++++------------- 7 files changed, 126 insertions(+), 174 deletions(-) diff --git a/src/bot/instance.test.ts b/src/bot/instance.test.ts index 184c5a6..adddf54 100644 --- a/src/bot/instance.test.ts +++ b/src/bot/instance.test.ts @@ -461,6 +461,7 @@ function makeResolveCtx(opts: { config: {}, id: "bot1", voteSkipUsers: new Set(), + queue: { current: vi.fn(() => null) }, autoPaused: false, currentSourceIsSpotify: opts.currentSourceIsSpotify ?? false, effectiveDuration: undefined, @@ -487,6 +488,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(); diff --git a/src/bot/instance.ts b/src/bot/instance.ts index 69362cb..fae6a8b 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -204,14 +204,7 @@ export class BotInstance extends EventEmitter { private fmRequesterName: string | undefined; /** Results of the most recent !search, for "#N" selection (issue #90). */ private lastSearchResults: Song[] = []; - /** - * Why the most recent resolveAndPlay produced nothing, or null. - * - * Kept as an instance field rather than a second return value: `resolveAndPlay` - * has ~20 call sites and its boolean is load-bearing in tests, while only the - * web routes need the explanation. They read this right after a false. - */ - private lastPlayFailure: PlayFailure | null = null; + private playbackRequest?: symbol; /** 当前曲实际播放时长(试听片段秒数或完整 duration);resolveAndPlay 赋值。 */ private effectiveDuration: number | undefined; /** Resume attempts for the current song's stream (#161); see resumeInterruptedStream. */ @@ -1032,53 +1025,41 @@ export class BotInstance extends EventEmitter { return requestedBy ? { ...song, requestedBy } : { ...song }; } - /** - * Why the last `resolveAndPlay(false)` produced nothing, or null after a - * success. Web routes read this to say what actually went wrong instead of - * the old catch-all 「区域/版权限制」. - */ - getLastPlayFailure(): PlayFailure | null { - return this.lastPlayFailure; - } - - /** Resolve URL for a song and start playing it. Skips to next if URL fails. */ - async resolveAndPlay(song: QueuedSong): Promise { - this.lastPlayFailure = null; + /** Resolve the URL and start playback if this request still owns the queue. */ + async resolveAndPlay(song: QueuedSong, onFailure?: (failure: PlayFailure) => void): Promise { + 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"); - // Recorded so the web route can say this instead of blaming copyright: - // every early return used to leave lastPlayFailure null, which made the - // UI fall back to the catch-all 「区域/版权限制」 for unrelated causes. - this.lastPlayFailure = { - platform: song.platform, - songId: song.id, - code: "unknown", - message: "机器人未连接,无法播放", - }; + fail("机器人未连接"); return false; } if (song.platform === "local" && !this.isLocalAudioEnabled()) { - this.logger.warn({ songId: song.id, name: song.name }, "Local audio playback disabled — refusing track"); - this.lastPlayFailure = { - platform: song.platform, - songId: song.id, - code: "unknown", - message: "该机器人已关闭本地音频播放", - }; + 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)) { // 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; @@ -1101,7 +1082,7 @@ export class BotInstance extends EventEmitter { fallbacks: provider.getFallbackQualities?.() ?? [], // Stop / disconnect must abort the budget: retrying into a dead // connection only delays the queue. - isCancelled: () => !this.connected, + isCancelled, onAttemptFailed: ({ attempt, total, quality, error }) => { const fields = { songId: song.id, name: song.name, attempt, total, quality }; if (error instanceof RiskControlError) { @@ -1130,7 +1111,7 @@ export class BotInstance extends EventEmitter { code: "unknown" as const, message: `没有拿到播放地址(${quality ?? "默认音质"})`, }; - this.lastPlayFailure = failure; + onFailure?.(failure); this.logger.warn( { songId: song.id, @@ -1145,29 +1126,17 @@ export class BotInstance extends EventEmitter { ); }, }); - if (!result?.url) { - 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; - } + 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; } @@ -1177,8 +1146,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; } @@ -1278,11 +1249,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"); - // Anything thrown outside the retry budget (detail lookup, spotify - // handoff, player start) still needs a cause, otherwise the web route - // prints the old 「区域/版权限制」 for a cause that is not copyright. - this.lastPlayFailure = toPlayFailure(song.platform, song.id, err); + onFailure?.(toPlayFailure(song.platform, song.id, err)); return false; } } @@ -1466,8 +1435,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}`; } @@ -1483,7 +1453,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 { + async playSingleSong(song: QueuedSong, requesterName?: string, onFailure?: (failure: PlayFailure) => void): Promise { const s = this.withRequester(song, requesterName); if (this.config.playKeepsQueue && !this.queue.isEmpty()) { const insertedAt = @@ -1496,7 +1466,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(); @@ -1510,7 +1480,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. @@ -2202,24 +2172,39 @@ export class BotInstance extends EventEmitter { * * Returns true if a song actually started playing, false otherwise. */ - async playNext(maxRetries = 3): Promise { + async playNext(maxRetries = 3, onFailure?: (failure: PlayFailure) => void): Promise { 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) { @@ -2235,7 +2220,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(); diff --git a/src/bot/url-retry.ts b/src/bot/url-retry.ts index 0094747..2a2ed5a 100644 --- a/src/bot/url-retry.ts +++ b/src/bot/url-retry.ts @@ -167,12 +167,14 @@ export async function resolveUrlWithRetry( let error: unknown; requestsMade += 1; + let result: SongUrlResult | null = null; try { - const result = await opts.resolve(step.quality); - if (result?.url) return result; + 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; diff --git a/src/music/netease.test.ts b/src/music/netease.test.ts index bd108bb..cea61e2 100644 --- a/src/music/netease.test.ts +++ b/src/music/netease.test.ts @@ -442,11 +442,11 @@ describe("NetEase risk control (-460)", () => { await expect(p.getSongUrl("1827600686")).rejects.toBeInstanceOf(RiskControlError); }); - it("keeps the upstream message so the log says what happened", async () => { + it("returns a fixed risk-control error without exposing the upstream message", async () => { const p = providerWithApi(async () => { - throw httpError(400, { code: -460, message: "检测到您的网络环境存在风险,请稍后再试" }); + throw httpError(400, { code: -460, message: "upstream sample detail" }); }); - await expect(p.getSongUrl("1827600686")).rejects.toThrow(/风险/); + await expect(p.getSongUrl("1827600686")).rejects.toThrow("网易云请求被风控拦截 (-460)"); }); it("does not disguise a genuine bad request", async () => { diff --git a/src/music/netease.ts b/src/music/netease.ts index 5741d02..18d8dc0 100644 --- a/src/music/netease.ts +++ b/src/music/netease.ts @@ -124,10 +124,10 @@ export function parseNeteaseTrial(item: any): number | undefined { */ function riskControlFrom(err: unknown): RiskControlError | null { const e = err as { - response?: { status?: number; data?: { code?: number; message?: string } }; + response?: { status?: number; data?: { code?: number } }; }; if (e?.response?.status === 400 && e.response.data?.code === RISK_CONTROL_CODE) { - return new RiskControlError(e.response.data.message ?? "网络环境风险 (-460)"); + return new RiskControlError("网易云请求被风控拦截 (-460)"); } return null; } diff --git a/src/music/provider.ts b/src/music/provider.ts index a2c76d1..c315919 100644 --- a/src/music/provider.ts +++ b/src/music/provider.ts @@ -34,24 +34,7 @@ export interface SongUrlResult { trialDuration?: number; } -/** - * NetEase rate-limits by IP, not by request shape. When it decides the caller's - * network looks risky it answers **HTTP 400** with - * - * {"code":-460,"message":"检测到您的网络环境存在风险,请稍后再试"} - * - * Cloud-host IPs hit this constantly; it clears up on its own after a few - * seconds. Because it is a 4xx, axios reports `ERR_BAD_REQUEST` — identical to - * a genuinely malformed request — so the only way to tell them apart is to read - * the response body. The distinction matters: -460 is worth retrying, a bad - * request never is. - * - * Measured on a live host: the anonymous call `?id=…&level=exhigh` answered - * 400/-460 every time, while the same call with the account cookie answered 200 - * and returned a full 320k URL. Intermittently, the cookie version is also - * rejected — which is exactly the "click play five times until it works" - * behaviour users report. - */ +/** NetEase upstream risk-control response code. */ export const RISK_CONTROL_CODE = -460; export class RiskControlError extends Error { @@ -109,45 +92,17 @@ export class SongUrlUnavailable extends Error { } } -/** Build the -460 flavour. Kept here so every provider names it identically. */ -export function riskControlFailure( - platform: string, - songId: string, - detail?: string, -): PlayFailure { - return { - platform, - songId, - code: "risk_control", - // 「约 5 秒」是有依据的:实测同一 IP 连续请求一般是 -460 几次之后放行, - // 重试预算也已经只留一次(RISK_CONTROL_BACKOFF_MS)。给一个具体的等待值, - // 比「请稍后重试」更能让人知道该干嘛。 - message: "被网易云风控拦截(-460),约 5 秒后再试", - upstream: detail ? { detail } : undefined, - }; -} - -/** - * Normalise anything a failed attempt threw into a `PlayFailure`, so callers - * never have to pattern-match on error classes themselves. - * - * The `unknown` branch truncates the message: axios errors carry the whole - * request config (including the cookie) and would otherwise put kilobytes into - * a UI toast and the log. - */ export function toPlayFailure(platform: string, songId: string, error: unknown): PlayFailure { if (error instanceof SongUrlUnavailable) return error.failure; if (error instanceof RiskControlError) { - return riskControlFailure(platform, songId, error.message); + return { + platform, + songId, + code: "risk_control", + message: "网易云暂时拒绝播放请求(-460),请稍后重试", + }; } - const raw = error instanceof Error ? error.message : ""; - const short = raw.replace(/\s+/g, " ").trim().slice(0, 120); - return { - platform, - songId, - code: "unknown", - message: short ? `解析播放地址失败:${short}` : "解析播放地址失败", - }; + return { platform, songId, code: "unknown", message: "解析播放地址失败" }; } export interface Playlist { diff --git a/src/web/api/player.ts b/src/web/api/player.ts index 9637e84..ce3880e 100644 --- a/src/web/api/player.ts +++ b/src/web/api/player.ts @@ -1,7 +1,9 @@ import { Router } 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 type { Logger } from "../../logger.js"; import { parseCommand } from "../../bot/commands.js"; import { requireBotAccess } from "../middleware/requirePermission.js"; @@ -61,28 +63,20 @@ export function createPlayerRouter( next(); }); - /** - * One line explaining why a track would not play. - * - * Every failure used to say 「(区域/版权限制)」 — including a lapsed - * membership, a delisted track and a quality level the account cannot - * stream. That single string is why three separate investigations went - * hunting for a copyright problem that was not there. The bot now records - * the real cause; this only falls back to the old wording when it has none. - */ - const whyUnplayable = (bot: any, song: { name?: string; id?: string }): string => { + const whyUnplayable = (song: { name?: string; id?: string }, reason?: string): string => { const label = song.name || song.id || "这首歌"; - const reason: string | undefined = bot?.getLastPlayFailure?.()?.message; - return reason - ? `无法播放「${label}」:${reason}` - : `无法播放「${label}」(区域/版权限制)`; + return reason ? `无法播放「${label}」:${reason}` : `无法播放「${label}」`; }; - /** Same, for the batch paths where a cause is context, not the headline. */ - const lastReason = (bot: any): string => { - const failure = bot?.getLastPlayFailure?.(); - return failure?.message ? `,最近一次:${failure.message}` : ""; - }; + 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 => { @@ -393,7 +387,7 @@ export function createPlayerRouter( // the sequential retry path, which still has a chance. } if (queueable.length === 0) { - res.json({ ok: false, message: `歌单 ${totalCount} 首歌曲均无法播放${lastReason(bot)}` }); + res.json({ ok: false, message: `歌单 ${totalCount} 首歌曲均无法播放` }); return; } @@ -422,19 +416,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} 首(其余无法播放${lastReason(bot)})` + ? `已加载 ${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) { logger.error({ err }, "Play playlist failed"); @@ -479,7 +470,7 @@ export function createPlayerRouter( } } if (queueable.length === 0) { - res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无法播放${lastReason(bot)}` }); + res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无法播放` }); return; } @@ -500,19 +491,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} 首(其余无法播放${lastReason(bot)})` + ? `已加载 ${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) { logger.error({ err }, "play-album failed"); @@ -569,7 +557,7 @@ export function createPlayerRouter( } } if (queueable.length === 0) { - res.json({ ok: false, message: `歌手 ${totalCount} 首歌曲均无法播放${lastReason(bot)}` }); + res.json({ ok: false, message: `歌手 ${totalCount} 首歌曲均无法播放` }); return; } @@ -595,16 +583,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} 首(其余无法播放${lastReason(bot)})` + ? `已加载 ${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) { @@ -634,10 +621,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: whyUnplayable(bot, song) }; + : { ok: false, message: whyUnplayable(song, reason) }; }); res.json(body); } catch (err) { @@ -677,9 +665,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: whyUnplayable(bot, song) }; + return { ok: false, message: whyUnplayable(song, reason) }; } return { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` }; } @@ -716,9 +705,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: whyUnplayable(bot, song) }; + return { ok: false, message: whyUnplayable(song, reason) }; } return { ok: true, message: `正在播放:${song.name || "Unknown"} - ${song.artist || "Unknown"}` }; });