mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-03 03:12:51 +08:00
fix(bilibili): rotate CDN hosts during stream recovery
This commit is contained in:
1 parent
fbc12aa11b
commit
1b57af6722
5 files changed
+86
-19
No files matched your search
@@ -3,6 +3,7 @@ import { EventEmitter } from "node:events";
|
||||
import { BotInstance } from "./instance.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { PlayQueue } from "../audio/queue.js";
|
||||
import { BiliBiliProvider } from "../music/bilibili.js";
|
||||
import { ManagedVoiceClientRegistry } from "./managed-voice-clients.js";
|
||||
|
||||
function deferred<T>() {
|
||||
@@ -82,6 +83,44 @@ beforeEach(() => vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }));
|
||||
afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
|
||||
|
||||
describe("Bilibili recovery retries transient URL failures", () => {
|
||||
it("rotates to untried CDN hosts after a long stream ends repeatedly at the same point", async () => {
|
||||
const bot = makeBot();
|
||||
const song = bot.queue.current();
|
||||
song.url = "https://upos-primary.bilivideo.com/audio.m4s?deadline=1";
|
||||
bot.player.elapsed = 2220;
|
||||
bot.effectiveDuration = 4020;
|
||||
song.duration = 4020;
|
||||
const primary = "https://upos-primary.bilivideo.com/audio.m4s?deadline=2";
|
||||
const backup = "https://upos-backup.bilivideo.com/audio.m4s?deadline=2";
|
||||
const edge = "https://fixture.szbdyd.com/audio.m4s?deadline=2";
|
||||
const provider = new BiliBiliProvider() as any;
|
||||
provider.cidCache.set(song.id, 42);
|
||||
provider.api = {
|
||||
get: vi.fn(async () => ({
|
||||
data: { data: { dash: { audio: [{ bandwidth: 192000, baseUrl: primary, backupUrl: [edge, backup] }] } } },
|
||||
})),
|
||||
};
|
||||
bot.getProviderFor = () => provider;
|
||||
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.player.play).toHaveBeenLastCalledWith(backup, 2220, 4020);
|
||||
|
||||
bot.player.state = "idle";
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.player.play).toHaveBeenLastCalledWith(edge, 2220, 4020);
|
||||
|
||||
// Once playback advances, a previously failed host can be used again.
|
||||
bot.player.elapsed += 31;
|
||||
bot.player.state = "idle";
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.player.play).toHaveBeenLastCalledWith(primary, 2251, 4020);
|
||||
expect(bot.queue.current()).toBe(song);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the same queue and seek through a null lookup, then resumes after one second", async () => {
|
||||
const bot = makeBot();
|
||||
const song = bot.queue.current();
|
||||
|
||||
+19
-3
@@ -227,7 +227,16 @@ export class BotInstance extends EventEmitter {
|
||||
/** 当前曲实际播放时长(试听片段秒数或完整 duration);resolveAndPlay 赋值。 */
|
||||
private effectiveDuration: number | undefined;
|
||||
/** Resume attempts for the current song's stream (#161); see resumeInterruptedStream. */
|
||||
private streamRecovery: { song: QueuedSong; attempts: number; position: number; session: number; generation: number; pauseRequested: boolean; inFlight: boolean } | null = null;
|
||||
private streamRecovery: {
|
||||
song: QueuedSong;
|
||||
attempts: number;
|
||||
position: number;
|
||||
session: number;
|
||||
generation: number;
|
||||
pauseRequested: boolean;
|
||||
inFlight: boolean;
|
||||
failedHosts: Set<string>;
|
||||
} | null = null;
|
||||
private playGate: Promise<unknown> = Promise.resolve();
|
||||
/** Per-bot Jellyfin playback-report session (start / ~10s progress / stop).
|
||||
* null when the wired provider has no reporting capability. */
|
||||
@@ -1339,7 +1348,10 @@ export class BotInstance extends EventEmitter {
|
||||
recovery.generation !== generation ||
|
||||
position - recovery.position > BotInstance.STREAM_END_TOLERANCE_S
|
||||
) {
|
||||
this.streamRecovery = { song, attempts: 0, position, session: endedSession, generation, pauseRequested: false, inFlight: false };
|
||||
this.streamRecovery = {
|
||||
song, attempts: 0, position, session: endedSession, generation,
|
||||
pauseRequested: false, inFlight: false, failedHosts: new Set(),
|
||||
};
|
||||
}
|
||||
const state = this.streamRecovery!;
|
||||
if (state.inFlight) return true;
|
||||
@@ -1352,6 +1364,8 @@ export class BotInstance extends EventEmitter {
|
||||
return false;
|
||||
}
|
||||
state.position = position;
|
||||
const failedHost = song.url ? URL.parse(song.url)?.hostname.replace(/\.$/, "") : undefined;
|
||||
if (failedHost) state.failedHosts.add(failedHost);
|
||||
|
||||
this.logger.warn(
|
||||
{ songId: song.id, position, duration, attempt: state.attempts + 1 },
|
||||
@@ -1375,7 +1389,9 @@ export class BotInstance extends EventEmitter {
|
||||
let result: Awaited<ReturnType<MusicProvider["getSongUrl"]>> = null;
|
||||
let reason = "no-url";
|
||||
try {
|
||||
result = await this.getProviderFor(song.platform).getSongUrl(song.id);
|
||||
result = await this.getProviderFor(song.platform).getSongUrl(
|
||||
song.id, undefined, { avoidHosts: state.failedHosts },
|
||||
);
|
||||
} catch {
|
||||
reason = "lookup-error";
|
||||
}
|
||||
|
||||
@@ -185,6 +185,11 @@ describe("pickStableAudioUrl (#161 long streams dying mid-play)", () => {
|
||||
expect(pickStableAudioUrl({ baseUrl: pcdn, backupUrl: [szbdyd] })).toBe(pcdn);
|
||||
});
|
||||
|
||||
it("allows a refreshed URL from the same host if no alternative is available", () => {
|
||||
const host = new URL(upos).hostname;
|
||||
expect(pickStableAudioUrl({ baseUrl: upos }, new Set([host]))).toBe(upos);
|
||||
});
|
||||
|
||||
it("returns undefined when there is no url at all", () => {
|
||||
expect(pickStableAudioUrl({})).toBeUndefined();
|
||||
});
|
||||
|
||||
+17
-15
@@ -4,6 +4,7 @@ import axios, { type AxiosInstance } from "axios";
|
||||
import type {
|
||||
MusicProvider,
|
||||
Song,
|
||||
SongUrlRequestOptions,
|
||||
SongUrlResult,
|
||||
Playlist,
|
||||
LyricLine,
|
||||
@@ -52,26 +53,23 @@ const BILI_PCDN_HOST = /\.mcdn\.bilivideo\.cn$|\.szbdyd\.com$/i;
|
||||
|
||||
/**
|
||||
* Pick the audio URL least likely to die mid-stream: the first upos/cos
|
||||
* mirror among baseUrl + backupUrl, else the baseUrl as before.
|
||||
* mirror among baseUrl + backupUrl. When recovering, exhaust untried hosts
|
||||
* before reusing a failed host whose newly signed URL may still work.
|
||||
*/
|
||||
export function pickStableAudioUrl(stream: {
|
||||
baseUrl?: string;
|
||||
base_url?: string;
|
||||
backupUrl?: string[];
|
||||
backup_url?: string[];
|
||||
}): string | undefined {
|
||||
}, avoidHosts?: ReadonlySet<string>): string | undefined {
|
||||
const primary = stream.baseUrl ?? stream.base_url;
|
||||
const candidates = [primary, ...(stream.backupUrl ?? stream.backup_url ?? [])].filter(
|
||||
(u): u is string => typeof u === "string" && u.length > 0,
|
||||
);
|
||||
const stable = candidates.find((u) => {
|
||||
try {
|
||||
return !BILI_PCDN_HOST.test(new URL(u).hostname);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return stable ?? primary;
|
||||
const candidates = [primary, ...(stream.backupUrl ?? stream.backup_url ?? [])]
|
||||
.filter((url): url is string => typeof url === "string" && url.length > 0)
|
||||
.map((url) => ({ url, host: URL.parse(url)?.hostname.replace(/\.$/, "") }));
|
||||
const stable = candidates.filter(({ host }) => host && !BILI_PCDN_HOST.test(host));
|
||||
const isUntried = ({ host }: (typeof candidates)[number]) => host && !avoidHosts?.has(host);
|
||||
|
||||
return stable.find(isUntried)?.url ?? candidates.find(isUntried)?.url ?? stable[0]?.url ?? primary;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -362,7 +360,11 @@ export class BiliBiliProvider implements MusicProvider {
|
||||
return this.cidCache.get(key) ?? this.cidCache.get(`${bvid}?p=${page}`) ?? this.cidCache.get(bvid) ?? null;
|
||||
}
|
||||
|
||||
async getSongUrl(songId: string, _quality?: string): Promise<SongUrlResult | null> {
|
||||
async getSongUrl(
|
||||
songId: string,
|
||||
_quality?: string,
|
||||
options?: SongUrlRequestOptions,
|
||||
): Promise<SongUrlResult | null> {
|
||||
const { bvid, page } = parseBilibiliId(songId);
|
||||
const cid = await this.getCid(bvid, page);
|
||||
if (!cid) return null;
|
||||
@@ -385,7 +387,7 @@ export class BiliBiliProvider implements MusicProvider {
|
||||
(b.bandwidth ?? 0) > (a.bandwidth ?? 0) ? b : a
|
||||
);
|
||||
|
||||
const biliUrl = pickStableAudioUrl(best);
|
||||
const biliUrl = pickStableAudioUrl(best, options?.avoidHosts);
|
||||
return biliUrl ? { url: biliUrl } : null;
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -213,11 +213,16 @@ export interface AuthStatus {
|
||||
avatarUrl?: string;
|
||||
}
|
||||
|
||||
export interface SongUrlRequestOptions {
|
||||
/** CDN hosts that already failed around this playback position (where supported). */
|
||||
avoidHosts?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
export interface MusicProvider {
|
||||
readonly platform: Platform;
|
||||
|
||||
search(query: string, limit?: number, offset?: number): Promise<SearchResult>;
|
||||
getSongUrl(songId: string, quality?: string): Promise<SongUrlResult | null>;
|
||||
getSongUrl(songId: string, quality?: string, options?: SongUrlRequestOptions): Promise<SongUrlResult | null>;
|
||||
setQuality(quality: string): void;
|
||||
getQuality(): string;
|
||||
getSongDetail(songId: string): Promise<Song | null>;
|
||||
|
||||
Reference in new issue
Block a user