mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-11-30 18:02:50 +08:00
fix(playback): skip blocked providers while advancing mixed queues
This commit is contained in:
1 parent
0adf21c566
commit
afb1cd7c14
5 files changed
+77
-11
No files matched your search
@@ -2,14 +2,14 @@ import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { BotInstance, COMMAND_DENIED_MESSAGE, spotifyPortsForBotId } from "./instance.js";
|
||||
import type { BotInstanceOptions } from "./instance.js";
|
||||
import { PlayQueue, PlayMode } from "../audio/queue.js";
|
||||
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { createDatabase, SHARED_QUEUE_OWNER } from "../data/database.js";
|
||||
import { parseCommand } from "./commands.js";
|
||||
import type { TS3TextMessage } from "../ts-protocol/client.js";
|
||||
import type { SpotifyController } from "../music/spotify/controller.js";
|
||||
import type { SpotifyOAuth } from "../music/spotify/spotify-oauth.js";
|
||||
import type { MusicProvider } from "../music/provider.js";
|
||||
import type { MusicProvider, PlayFailure } from "../music/provider.js";
|
||||
import type { BotDatabase } from "../data/database.js";
|
||||
import type { AvatarStore } from "../data/avatars.js";
|
||||
import type { BotConfig } from "../data/config.js";
|
||||
@@ -583,6 +583,36 @@ it("reports the reason when the next track cannot be started", async () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("queue advancement after a provider-wide failure", () => {
|
||||
it.each([
|
||||
["netease", "risk_control"],
|
||||
["kugou", "provider_verification_required"],
|
||||
] as const)("skips queued %s tracks without spending retries for other sources", async (platform, code) => {
|
||||
const queue = new PlayQueue();
|
||||
for (let i = 0; i < 8; i++) queue.add({ ...spotifySong(), id: String(i), platform });
|
||||
const available = { ...spotifySong(), id: "available", platform: "qq" as const };
|
||||
queue.add(available);
|
||||
const ctx = {
|
||||
connected: true,
|
||||
queue,
|
||||
player: makePlayer(),
|
||||
voteSkipUsers: new Set<string>(),
|
||||
resolveAndPlay: vi.fn(async (track: QueuedSong, onFailure: (failure: PlayFailure) => void) => {
|
||||
if (track.platform === "qq") return true;
|
||||
onFailure({ platform, songId: track.id, code, message: "Provider unavailable" });
|
||||
return false;
|
||||
}),
|
||||
profileManager: { onSongChange: vi.fn(async () => {}) },
|
||||
sweepLocalAudio: vi.fn(),
|
||||
emit: vi.fn(),
|
||||
};
|
||||
|
||||
expect(await playNext.call(ctx)).toBe(true);
|
||||
expect(ctx.resolveAndPlay.mock.calls.map(([track]) => track.id)).toEqual(["0", "available"]);
|
||||
expect(queue.current()?.id).toBe("available");
|
||||
});
|
||||
});
|
||||
|
||||
describe("BotInstance.resolveAndPlay — Spotify routing (C4)", () => {
|
||||
it("routes a spotify song to controller.playTrack + player.playPcmStream, not player.play", async () => {
|
||||
const controller = makeController();
|
||||
|
||||
+21
-6
@@ -9,7 +9,7 @@ import {
|
||||
} from "../ts-protocol/client.js";
|
||||
import { OpenProtocolManager } from "../ts-protocol/open-protocol.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { resolveUrlWithRetry } from "./url-retry.js";
|
||||
import { blocksProviderForAdvance, resolveUrlWithRetry } from "./url-retry.js";
|
||||
import { RISK_CONTROL_CODE, RiskControlError, toPlayFailure } from "../music/provider.js";
|
||||
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
|
||||
import type { MusicProvider, Platform, PlayFailure, Song, SongUrlResult } from "../music/provider.js";
|
||||
@@ -1154,7 +1154,7 @@ export class BotInstance extends EventEmitter {
|
||||
"URL resolve hit NetEase risk control (-460) — backing off",
|
||||
);
|
||||
} else if (error) {
|
||||
this.logger.warn({ ...fields, err: error }, "URL resolve threw — retrying");
|
||||
this.logger.warn({ ...fields, err: error }, "URL resolve attempt failed");
|
||||
} else if (attempt < total) {
|
||||
this.logger.debug(fields, "URL resolve returned no URL — retrying");
|
||||
}
|
||||
@@ -2247,11 +2247,26 @@ export class BotInstance extends EventEmitter {
|
||||
if (this.isAdvancing || !this.connected) return false;
|
||||
this.isAdvancing = true;
|
||||
let started = false;
|
||||
let riskControlled = false;
|
||||
const blockedProviders = new Set<string>();
|
||||
const captureFailure = (failure: PlayFailure) => {
|
||||
riskControlled = failure.code === "risk_control";
|
||||
if (blocksProviderForAdvance(failure.code)) blockedProviders.add(failure.platform);
|
||||
onFailure?.(failure);
|
||||
};
|
||||
const nextCandidate = (): QueuedSong | null => {
|
||||
if (blockedProviders.size === 0) return this.queue.next();
|
||||
const sequential = this.queue.getMode() === PlayMode.Sequential;
|
||||
const currentIndex = this.queue.getCurrentIndex();
|
||||
if (!this.queue.list().some((track, index) =>
|
||||
(!sequential || index > currentIndex) && !blockedProviders.has(track.platform),
|
||||
)) return null;
|
||||
// Do not spend URL attempts on a blocked source. Allow for crossing a
|
||||
// shuffle boundary, but always terminate in looping modes.
|
||||
for (let i = 0; i < this.queue.size() * 2; i++) {
|
||||
const candidate = this.queue.next();
|
||||
if (!candidate || !blockedProviders.has(candidate.platform)) return candidate;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const generation = this.lifecycleGeneration;
|
||||
const unchanged = (song: QueuedSong, request: symbol | undefined) =>
|
||||
this.connected && this.lifecycleGeneration === generation &&
|
||||
@@ -2266,8 +2281,8 @@ export class BotInstance extends EventEmitter {
|
||||
started = await playback;
|
||||
if (!started && !unchanged(next, request)) return false;
|
||||
if (!started) {
|
||||
for (let i = 0; i < maxRetries && this.connected && !riskControlled; i++) {
|
||||
const retry = this.queue.next();
|
||||
for (let i = 0; i < maxRetries && this.connected; i++) {
|
||||
const retry = nextCandidate();
|
||||
if (!retry) break;
|
||||
const retryPlayback = this.resolveAndPlay(retry, captureFailure);
|
||||
const retryRequest = this.playbackRequest;
|
||||
|
||||
@@ -41,6 +41,20 @@ describe("normalizeRetryCount", () => {
|
||||
});
|
||||
|
||||
describe("resolveUrlWithRetry", () => {
|
||||
it("stops immediately when the provider asks the user to verify", async () => {
|
||||
const error = new SongUrlUnavailable({
|
||||
platform: "kugou", songId: "song", code: "provider_verification_required", message: "Verification required",
|
||||
});
|
||||
const resolve = vi.fn(async () => { throw error; });
|
||||
const onExhausted = vi.fn();
|
||||
const { sleep, delays } = recordingSleep();
|
||||
|
||||
expect(await resolveUrlWithRetry({ retries: 5, fallbacks: ["standard"], resolve, onExhausted, sleep })).toBeNull();
|
||||
expect(resolve).toHaveBeenCalledTimes(1);
|
||||
expect(delays).toEqual([]);
|
||||
expect(onExhausted).toHaveBeenCalledExactlyOnceWith({ error, quality: undefined });
|
||||
});
|
||||
|
||||
it("makes exactly one attempt when retries is 0", async () => {
|
||||
const resolve = vi.fn(async () => null);
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { RiskControlError } from "../music/provider.js";
|
||||
import type { SongUrlResult } from "../music/provider.js";
|
||||
import { RiskControlError, SongUrlUnavailable } from "../music/provider.js";
|
||||
import type { PlayFailureCode, SongUrlResult } from "../music/provider.js";
|
||||
|
||||
/** These failures apply to the provider for the current queue transition. */
|
||||
export function blocksProviderForAdvance(code: PlayFailureCode | undefined): boolean {
|
||||
return code === "risk_control" || code === "provider_verification_required";
|
||||
}
|
||||
|
||||
/**
|
||||
* Silent re-resolve of a playable URL.
|
||||
@@ -179,6 +184,7 @@ export async function resolveUrlWithRetry(
|
||||
lastError = error;
|
||||
lastQuality = step.quality;
|
||||
opts.onAttemptFailed?.({ attempt: i + 1, total: plan.length, quality: step.quality, error });
|
||||
if (error instanceof SongUrlUnavailable && error.failure.code === "provider_verification_required") break;
|
||||
// Only same-quality attempts grow the backoff; a level switch resets it.
|
||||
sameQualityAttempt = step.fallback ? 0 : sameQualityAttempt + 1;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Router, type Request } from "express";
|
||||
import type { BotInstance } from "../../bot/instance.js";
|
||||
import { blocksProviderForAdvance } from "../../bot/url-retry.js";
|
||||
import type { QueuedSong } from "../../audio/queue.js";
|
||||
import type { BotManager } from "../../bot/manager.js";
|
||||
import type { BotDatabase } from "../../data/database.js";
|
||||
@@ -127,7 +128,7 @@ export function createPlayerRouter(
|
||||
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" && queue.current() === first) {
|
||||
if (first && !started && !blocksProviderForAdvance(failure?.code) && queue.current() === first) {
|
||||
// Many collections contain several consecutive unavailable tracks.
|
||||
started = await bot.playNext(20, capture);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user