mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-03 03:12:51 +08:00
fix(playback): name the real reason instead of 「区域/版权限制」
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.
This commit is contained in:
1 parent
e9995c1e30
commit
4c25cfe5e5
7 files changed
+436
-23
No files matched your search
+48
-8
@@ -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<boolean> { if (!this.connected) {
|
||||
async resolveAndPlay(song: QueuedSong): Promise<boolean> {
|
||||
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;
|
||||
|
||||
+109
-1
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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<void>;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user