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;
|
||||
}
|
||||
@@ -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<string, unknown> | undefined): Promise<any> {
|
||||
const p = new NeteaseProvider("http://127.0.0.1:3001");
|
||||
(p as unknown as { api: { get: () => Promise<unknown> } }).api = {
|
||||
get: async () => ({ data: { data: item ? [item] : [] } }),
|
||||
};
|
||||
try {
|
||||
await p.getSongUrl("1");
|
||||
} catch (err) {
|
||||
return err;
|
||||
}
|
||||
throw new Error("expected getSongUrl to throw for a URL-less response");
|
||||
}
|
||||
|
||||
it("fee=1 未购买 → 需要会员", async () => {
|
||||
const err = await miss({ url: null, code: 200, fee: 1, payed: 0, level: "exhigh" });
|
||||
expect(err.failure.code).toBe("vip_required");
|
||||
expect(err.failure.message).toMatch(/需要会员/);
|
||||
});
|
||||
|
||||
it("fee=4 未购买 → 需要购买专辑(不是「会员」)", async () => {
|
||||
const err = await miss({ url: null, code: 200, fee: 4, payed: 0, level: "exhigh" });
|
||||
expect(err.failure.code).toBe("vip_required");
|
||||
expect(err.failure.message).toMatch(/专辑/);
|
||||
});
|
||||
|
||||
it("已付款的曲目不算会员问题", async () => {
|
||||
const err = await miss({ url: null, code: 200, fee: 1, payed: 1, level: "exhigh" });
|
||||
expect(err.failure.code).toBe("quality_denied");
|
||||
});
|
||||
|
||||
it("upstream code 404 → 无版权", async () => {
|
||||
const err = await miss({ url: null, code: 404, level: "exhigh" });
|
||||
expect(err.failure.code).toBe("no_copyright");
|
||||
expect(err.failure.message).toMatch(/无版权|下架/);
|
||||
});
|
||||
|
||||
// The measured case that broke the old single-message assumption: a free
|
||||
// track (fee=8) with no URL at exhigh that plays fine at higher.
|
||||
it("fee=8 且无 URL → 音质受限,而不是版权", async () => {
|
||||
const err = await miss({ url: null, code: 200, fee: 8, level: "exhigh" });
|
||||
expect(err.failure.code).toBe("quality_denied");
|
||||
expect(err.failure.message).toMatch(/音质/);
|
||||
});
|
||||
|
||||
it("空 data 数组 → 未知,但仍带得出上游字段", async () => {
|
||||
const err = await miss(undefined);
|
||||
expect(err.failure.code).toBe("unknown");
|
||||
expect(err.failure.upstream).toBeDefined();
|
||||
});
|
||||
|
||||
it("把 fee / payed / level 留在 upstream 里供日志使用", async () => {
|
||||
const err = await miss({ url: null, code: 200, fee: 8, payed: 0, level: "higher", br: 192000 });
|
||||
expect(err.failure.upstream).toMatchObject({ fee: 8, payed: 0, level: "higher", br: 192000 });
|
||||
});
|
||||
});
|
||||
+71
-2
@@ -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<string, any> | undefined,
|
||||
body: Record<string, any> | undefined,
|
||||
): PlayFailure {
|
||||
const upstream = {
|
||||
code: item?.code ?? body?.code,
|
||||
fee: item?.fee,
|
||||
payed: item?.payed,
|
||||
level: item?.level ?? level,
|
||||
br: item?.br,
|
||||
freeTrial: Boolean(item?.freeTrialInfo),
|
||||
};
|
||||
const suffix = `(${String(upstream.level)})`;
|
||||
const base = { platform: "netease" as const, songId, upstream };
|
||||
|
||||
if (!item) {
|
||||
return {
|
||||
...base,
|
||||
code: "unknown",
|
||||
message: `音源没有返回该曲目${suffix}`,
|
||||
};
|
||||
}
|
||||
if (upstream.code === 404) {
|
||||
return {
|
||||
...base,
|
||||
code: "no_copyright",
|
||||
message: `无版权或已下架${suffix}`,
|
||||
};
|
||||
}
|
||||
const fee = typeof upstream.fee === "number" ? upstream.fee : -1;
|
||||
if ((fee === 1 || fee === 4) && !upstream.payed) {
|
||||
return {
|
||||
...base,
|
||||
code: "vip_required",
|
||||
message: fee === 4 ? `需要购买该专辑${suffix}` : `需要会员${suffix}`,
|
||||
};
|
||||
}
|
||||
// Everything else that has the track but no URL is a per-level restriction:
|
||||
// the same id often plays at another level (measured: 192k OK while both
|
||||
// 320k and 128k returned null).
|
||||
return {
|
||||
...base,
|
||||
code: "quality_denied",
|
||||
message: `当前音质无播放权限${suffix}`,
|
||||
};
|
||||
}
|
||||
|
||||
// NetEase quality levels: standard(128k) higher(192k) exhigh(320k) lossless(flac) hires(hi-res) jyeffect jymaster
|
||||
export const NETEASE_QUALITY_LEVELS = [
|
||||
{ value: "standard", label: "标准 (128kbps)", bitrate: 128 },
|
||||
@@ -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) };
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when a provider knows *why* no URL came back.
|
||||
*
|
||||
* `resolveUrlWithRetry` still runs the full budget on it — a lower level can
|
||||
* genuinely help, and "deterministic" judgements about this API have been wrong
|
||||
* before — but it remembers the last one so the eventual message can name the
|
||||
* cause instead of falling back to a guess.
|
||||
*/
|
||||
export class SongUrlUnavailable extends Error {
|
||||
readonly failure: PlayFailure;
|
||||
constructor(failure: PlayFailure) {
|
||||
super(failure.message);
|
||||
this.name = "SongUrlUnavailable";
|
||||
this.failure = failure;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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;
|
||||
|
||||
+32
-9
@@ -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"}` };
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user