fix(playback): preserve active playback and report actual start failures

This commit is contained in:
TIANYAO ZHANG committed 2026-11-18 18:21:08 +08:00
1 parent 23b36e2019
commit 0adf21c566
6 files changed
+300 -200

No files matched your search

+65
View File
@@ -518,6 +518,71 @@ it("does not start a track whose URL resolved after the queue was cleared", asyn
expect(player.play).not.toHaveBeenCalled();
});
it.each(["netease", "spotify"])("keeps %s playback successful when saving history fails", async platform => {
const player = makePlayer();
const url = platform === "spotify" ? "spotify:track:abc" : "https://example.com/track";
const ctx = makeResolveCtx({ controller: makeController(), player, url });
ctx.database.addPlayHistory.mockImplementation(() => { throw new Error("Database temporarily unavailable"); });
expect(await resolveAndPlay.call(ctx, { ...spotifySong(), platform })).toBe(true);
expect(player.getState()).toBe("playing");
expect(ctx.emit).toHaveBeenCalledWith("stateChange");
expect(ctx.syncProfileToSong).toHaveBeenCalledTimes(1);
});
it("advances again when a track ends during a slow profile upload", async () => {
const player = Object.assign(new EventEmitter(), makePlayer(), {
getPlaybackSessionId: vi.fn(() => 1),
});
const ctx = makeResolveCtx({ controller: makeController(), player, url: "https://example.com/track" });
const queue = new PlayQueue();
for (const id of ["previous", "short", "following"]) {
queue.add({ ...spotifySong(), id, platform: "netease" });
}
queue.play();
ctx.queue = queue;
ctx.resumeInterruptedStream = vi.fn(async () => false);
ctx.resolveAndPlay = resolveAndPlay.bind(ctx);
ctx.playNext = playNext.bind(ctx);
ctx.sweepLocalAudio = vi.fn();
ctx.spotifyController = Object.assign(new EventEmitter(), { on: EventEmitter.prototype.on });
const profileStarted = deferred();
const finishProfile = deferred();
ctx.syncProfileToSong.mockImplementationOnce(() => {
profileStarted.resolve();
return finishProfile.promise;
});
setupPlayerEvents.call(ctx);
const advancing = ctx.playNext();
await profileStarted.promise;
try {
player.stop();
player.emit("trackEnd");
await new Promise<void>(resolve => setImmediate(resolve));
expect(queue.current()?.id).toBe("following");
} finally {
finishProfile.resolve();
await advancing;
}
});
it("reports the reason when the next track cannot be started", async () => {
const current = { ...spotifySong(), id: "next", platform: "netease" };
const ctx = {
connected: true,
queue: { current: () => current },
playNext: async (_maxRetries: number, report?: (failure: { message: string }) => void) => {
report?.({ message: "网易云暂时拒绝播放请求(-460),请稍后重试" });
return false;
},
};
expect(await BotInstance.prototype.skipToNext.call(ctx as unknown as BotInstance)).toEqual({
ok: false,
message: expect.stringContaining("-460"),
});
});
describe("BotInstance.resolveAndPlay — Spotify routing (C4)", () => {
it("routes a spotify song to controller.playTrack + player.playPcmStream, not player.play", async () => {
const controller = makeController();
+41 -48
View File
@@ -976,7 +976,7 @@ export class BotInstance extends EventEmitter {
return this.cmdStop();
case "next":
case "skip":
return this.cmdNext();
return (await this.skipToNext()).message;
case "prev":
return this.cmdPrev();
case "vol":
@@ -1255,45 +1255,36 @@ export class BotInstance extends EventEmitter {
this.player.resume();
}
this.currentSourceIsSpotify = true;
this.jellyfinReporter?.onStop();
song.url = result.url;
// No trial clip for Spotify — full-track duration only (the near-end
// stall watchdog is disabled for the external stream anyway).
// Spotify has no preview clip or URL stall watchdog.
this.effectiveDuration = song.duration;
this.autoPaused = false;
this.database.addPlayHistory({
botId: this.id,
songId: song.id,
songName: song.name,
artist: song.artist,
album: song.album,
platform: song.platform,
coverUrl: song.coverUrl,
requestedBy: song.requestedBy,
});
await this.syncProfileToSong(song);
this.emit("stateChange");
return true;
}
// Non-Spotify track: if we were on Spotify, pause the sidecar so it stops
// decoding ahead before the URL ffmpeg reclaims the PCM buffer.
if (this.currentSourceIsSpotify) {
this.spotifyController.pause().catch((err) =>
this.logger.warn({ err }, "Failed to pause Spotify sidecar on source switch"));
this.currentSourceIsSpotify = false;
} else {
// Pause the sidecar before URL playback reclaims the PCM buffer.
if (this.currentSourceIsSpotify) {
this.spotifyController.pause().catch((err) =>
this.logger.warn({ err }, "Failed to pause Spotify sidecar on source switch"));
this.currentSourceIsSpotify = false;
}
this.effectiveDuration = result.trialDuration ?? song.duration;
this.player.play(result.url, 0, this.effectiveDuration);
}
song.url = result.url;
// 试听片段用试听时长(让 player nearEnd 正确触发自动切歌);完整曲回退 song.duration
this.effectiveDuration = result.trialDuration ?? song.duration;
this.player.play(result.url, 0, this.effectiveDuration);
// Jellyfin playback reporting: open a session for jellyfin tracks (the
// reporter closes the previous one itself); close any open session when
// playback moves to another source. Fire-and-forget — never blocks play.
} catch (err) {
if (isCancelled()) return false;
this.logger.error({ err, songId: song.id }, "Failed to resolve URL");
onFailure?.(toPlayFailure(song.platform, song.id, err));
return false;
}
// Playback has started. Failures in bookkeeping must not skip a track
// or turn an otherwise successful playback request into an error.
this.autoPaused = false;
try {
if (song.platform === "jellyfin") this.jellyfinReporter?.onTrackStart(song.id);
else this.jellyfinReporter?.onStop();
// Fresh playback (re)start — clear auto-pause so a later occupancy
// change won't try to "resume" a track the user already restarted.
this.autoPaused = false;
} catch (err) {
this.logger.warn({ err, songId: song.id }, "Failed to report playback session");
}
try {
this.database.addPlayHistory({
botId: this.id,
songId: song.id,
@@ -1304,16 +1295,14 @@ export class BotInstance extends EventEmitter {
coverUrl: song.coverUrl,
requestedBy: song.requestedBy,
});
// Keep TeamSpeak-side profile updates on the same path for play/next/FM.
await this.syncProfileToSong(song);
this.emit("stateChange");
return true;
} catch (err) {
if (isCancelled()) return false;
this.logger.error({ err, songId: song.id }, "Failed to resolve URL");
onFailure?.(toPlayFailure(song.platform, song.id, err));
return false;
this.logger.warn({ err, songId: song.id }, "Failed to save play history");
}
this.emit("stateChange");
// Profile uploads can outlive a short track. Let the queue advance while
// the profile manager's generation checks discard superseded updates.
void this.syncProfileToSong(song);
return true;
}
/** Platforms whose CDN stream can die mid-file on long content (#89, #161). */
@@ -1704,12 +1693,16 @@ export class BotInstance extends EventEmitter {
return "Stopped and queue cleared";
}
private async cmdNext(): Promise<string> {
await this.playNext();
async skipToNext(): Promise<{ ok: boolean; message: string }> {
if (!this.connected) throw new Error("Bot is not connected to TeamSpeak");
if (this.isAdvancing) return { ok: false, message: "正在切歌,请稍后" };
let reason: string | undefined;
const started = await this.playNext(3, failure => { reason = failure.message; });
const current = this.queue.current();
if (current)
return `Now playing: ${current.name} - ${current.artist}`;
return "Queue is empty";
if (started && current) {
return { ok: true, message: `Now playing: ${current.name} - ${current.artist}` };
}
return { ok: false, message: reason ?? (current ? "没有可播放的下一首" : "队列为空") };
}
private async cmdPrev(): Promise<string> {
+53 -6
View File
@@ -75,8 +75,8 @@ describe("collectArtistSongs (play-artist all:true)", () => {
});
});
describe("play-artist playback serialization", () => {
it("keeps the queue and audible song consistent when single-song playback overlaps artist playback", async () => {
describe("collection playback serialization", () => {
it.each(["artist", "album", "playlist"])("serializes %s playback and single-song playback", async kind => {
const queue = new PlayQueue();
let audible: string | null = null;
let releaseArtist!: () => void;
@@ -87,7 +87,14 @@ describe("play-artist playback serialization", () => {
const singleArrived = new Promise<void>((resolve) => { notifySingleArrived = resolve; });
const bot: any = {
playGate: Promise.resolve(),
getProviderFor: () => ({ platform: "netease", getArtistSongs: async () => [song("A")], getArtistAllSongs: async () => page(["A"], 1, false) }),
getProviderFor: () => ({
platform: "netease",
getAlbumSongs: async () => [song("A")],
getPlaylistSongs: async () => [song("A")],
getArtistSongs: async () => [song("A")],
getArtistAllSongs: async () => page(["A"], 1, false),
}),
emit: vi.fn(),
getPlayer: () => ({ stop: () => { audible = null; }, resetFailures: () => {} }),
getQueueManager: () => queue,
resolveAndPlay: async (track: Song) => {
@@ -110,7 +117,8 @@ describe("play-artist playback serialization", () => {
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
app.use("/api/player/b/play-song", (_req, _res, next) => { notifySingleArrived(); next(); });
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
const artistRequest = request(app).post("/api/player/b/play-artist").send({ artistId: "artist", platform: "netease" }).then((res) => res);
const collectionRequest = request(app).post(`/api/player/b/play-${kind}`)
.send({ [`${kind}Id`]: "collection", platform: "netease" }).then((res) => res);
await artistStarted;
const singleRequest = request(app).post("/api/player/b/play-song").send({ song: song("B") }).then((res) => res);
// Let the overlapping HTTP request enter the real route while A's URL is pending.
@@ -119,11 +127,50 @@ describe("play-artist playback serialization", () => {
await Promise.resolve();
const whileArtistPending = queue.current()?.id;
releaseArtist();
const [artistResponse, singleResponse] = await Promise.all([artistRequest, singleRequest]);
expect(artistResponse.status).toBe(200);
const [collectionResponse, singleResponse] = await Promise.all([collectionRequest, singleRequest]);
expect(collectionResponse.status).toBe(200);
expect(singleResponse.status).toBe(200);
expect(whileArtistPending).toBe("A");
expect(queue.current()?.id).toBe("B");
expect(audible).toBe("B");
});
});
describe("collection preflight", () => {
it.each([
["playlist", "empty", 200],
["playlist", "unavailable", 200],
["album", "empty", 200],
["album", "error", 500],
])("preserves current playback if the %s is %s", async (kind, result, status) => {
const queue = new PlayQueue();
queue.add(song("playing"));
queue.play();
const player = { stop: vi.fn(), resetFailures: vi.fn() };
const loadSongs = async () => {
if (result === "error") throw new Error("Upstream failed");
return result === "empty" ? [] : [song("next")];
};
const bot = {
getProviderFor: () => ({
platform: "qq",
getPlaylistSongs: loadSongs,
getAlbumSongs: loadSongs,
getPlayableSongIds: async () => new Set<string>(),
}),
getQueueManager: () => queue,
getPlayer: () => player,
};
const app = express();
app.use(express.json());
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
const response = await request(app).post(`/api/player/b/play-${kind}`).send({ [`${kind}Id`]: "id", platform: "qq" });
expect(response.status).toBe(status);
expect(player.stop).not.toHaveBeenCalled();
expect(player.resetFailures).not.toHaveBeenCalled();
expect(queue.current()?.id).toBe("playing");
});
});
+53 -119
View File
@@ -104,14 +104,43 @@ export function createPlayerRouter(
return reason ? `无法播放「${label}」:${reason}` : `无法播放「${label}」`;
};
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 };
async function startCollection(
bot: BotInstance, songs: Song[], platform: Song["platform"], requestedBy: string | undefined, totalCount: number,
) {
return bot.runExclusive(async () => {
bot.getPlayer().stop();
bot.getPlayer().resetFailures();
const queue = bot.getQueueManager();
queue.clear();
for (const song of songs) {
queue.add({ ...song, platform, requestedBy });
}
bot.cleanupQueuedLocalSongs?.("queue_replaced");
const mode = queue.getMode();
const first: QueuedSong | null = mode === "random" || mode === "rloop"
? queue.playAt(Math.floor(Math.random() * queue.size()))
: queue.play();
// Publish the new idle queue even if the first URL lookup ultimately fails.
bot.emit("stateChange");
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) {
// Many collections contain several consecutive unavailable tracks.
started = await bot.playNext(20, capture);
}
const playing = queue.current();
const loaded = songs.length < totalCount
? `已加载 ${songs.length}/${totalCount} 首(其余无法播放)`
: `已加载 ${songs.length} 首`;
const reason = failure?.message;
return started && playing
? { ok: true, message: `${loaded},正在播放:${playing.name}` }
: { ok: false, message: `${loaded},但无法开始播放${reason ? `:${reason}` : "。"}` };
});
}
/** Map API platform string to the corresponding command flag. */
@@ -191,7 +220,14 @@ export function createPlayerRouter(
router.post("/:botId/pause", authorize({ capability: "player.control", guestFlag: "transport" }), simpleCommand("!pause"));
router.post("/:botId/resume", authorize({ capability: "player.control", guestFlag: "transport" }), simpleCommand("!resume"));
router.post("/:botId/next", authorize({ capability: "player.control", guestFlag: "skip" }), simpleCommand("!next"));
router.post("/:botId/next", authorize({ capability: "player.control", guestFlag: "skip" }), async (req, res) => {
try {
const bot: BotInstance = (req as any).bot;
res.json(await bot.skipToNext());
} catch (err) {
res.status(500).json({ error: musicRequestError(err).message });
}
});
router.post("/:botId/prev", authorize({ capability: "player.control" }), simpleCommand("!prev"));
router.post("/:botId/stop", authorize({ capability: "player.control" }), simpleCommand("!stop"));
router.post("/:botId/clear", authorize({ capability: "player.queue", guestFlag: "removeClear" }), simpleCommand("!clear"));
@@ -378,13 +414,9 @@ export function createPlayerRouter(
// which the router's constructor params did not.
const provider = scopedProvider(req, bot, platform);
// Stop current playback
bot.getPlayer().stop();
bot.getPlayer().resetFailures();
const songs = await provider.getPlaylistSongs(playlistId);
if (songs.length === 0) {
res.json({ message: "Playlist is empty" });
res.json({ ok: false, message: "Playlist is empty" });
return;
}
@@ -392,7 +424,7 @@ export function createPlayerRouter(
// large fraction of songs that return result=104003 (region/copyright
// restricted). Batch-resolve URLs once and only queue the playable
// ones, otherwise the playback retry loop wastes time guessing.
let queueable: { id: string }[] = songs;
let queueable = songs;
const totalCount = songs.length;
const qqLike = provider as { getPlayableSongIds?: (ids: string[]) => Promise<Set<string> | null> };
if (typeof qqLike.getPlayableSongIds === "function") {
@@ -411,42 +443,7 @@ export function createPlayerRouter(
return;
}
const queue = bot.getQueueManager();
queue.clear();
for (const song of queueable) {
queue.add({ ...song, platform: provider.platform, requestedBy: requesterName(req) });
}
// Sweep AFTER the queue is rebuilt: the previous queue's local uploads are
// released and deleted, but an empty/failed playlist (early return above)
// leaves the previous queue — and its files — intact.
bot.cleanupQueuedLocalSongs?.("queue_replaced");
// Use queue.play() for sequential, or pick random index for random modes
const mode = queue.getMode();
let first;
if (mode === "random" || mode === "rloop") {
const idx = Math.floor(Math.random() * queue.size());
first = queue.playAt(idx);
} else {
first = queue.play();
}
// If the first picked song can't resolve (e.g., QQ song with no
// streaming entitlement → result 104003), fall back to playNext's
// 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.
const { started, reason } = await startCollection(bot, first);
const playing = queue.current();
const loadedMsg = queueable.length < totalCount
? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)`
: `已加载 ${queueable.length} 首`;
if (started && playing) {
res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` });
} else {
res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` });
}
res.json(await startCollection(bot, queueable, provider.platform, requesterName(req), totalCount));
} catch (err) {
const error = musicRequestError(err);
logger.error({ err: error }, "Play playlist failed");
@@ -465,19 +462,15 @@ export function createPlayerRouter(
}
const provider = scopedProvider(req, bot, platform);
// Stop current playback
bot.getPlayer().stop();
bot.getPlayer().resetFailures();
const songs = await provider.getAlbumSongs(albumId);
if (songs.length === 0) {
res.json({ message: "Album is empty" });
res.json({ ok: false, message: "Album is empty" });
return;
}
// QQ-specific optimization: batch-resolve playable IDs to avoid
// wasting retries on region/copyright-restricted tracks.
let queueable: { id: string }[] = songs;
let queueable = songs;
const totalCount = songs.length;
const qqLike = provider as { getPlayableSongIds?: (ids: string[]) => Promise<Set<string> | null> };
if (typeof qqLike.getPlayableSongIds === "function") {
@@ -491,34 +484,7 @@ export function createPlayerRouter(
return;
}
const queue = bot.getQueueManager();
queue.clear();
for (const song of queueable) {
queue.add({ ...song, platform: provider.platform, requestedBy: requesterName(req) });
}
// Sweep AFTER the queue is rebuilt (see play-playlist).
bot.cleanupQueuedLocalSongs?.("queue_replaced");
const mode = queue.getMode();
let first;
if (mode === "random" || mode === "rloop") {
const idx = Math.floor(Math.random() * queue.size());
first = queue.playAt(idx);
} else {
first = queue.play();
}
const { started, reason } = await startCollection(bot, first);
const playing = queue.current();
const loadedMsg = queueable.length < totalCount
? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)`
: `已加载 ${queueable.length} 首`;
if (started && playing) {
res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` });
} else {
res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` });
}
res.json(await startCollection(bot, queueable, provider.platform, requesterName(req), totalCount));
} catch (err) {
const error = musicRequestError(err);
logger.error({ err: error }, "play-album failed");
@@ -561,7 +527,7 @@ export function createPlayerRouter(
// Same QQ batch-resolve optimization as play-album: drop tracks that are
// region/copyright blocked instead of burning retries on them.
let queueable: { id: string }[] = songs;
let queueable = songs;
const totalCount = songs.length;
const qqLike = provider as { getPlayableSongIds?: (ids: string[]) => Promise<Set<string> | null> };
if (typeof qqLike.getPlayableSongIds === "function") {
@@ -575,39 +541,7 @@ export function createPlayerRouter(
return;
}
// Catalogue and copyright lookups leave current playback running. Only
// the queue replacement and playback itself occupy the shared play gate.
const body = await bot.runExclusive(async () => {
bot.getPlayer().stop();
bot.getPlayer().resetFailures();
const queue = bot.getQueueManager();
queue.clear();
for (const song of queueable) {
queue.add({ ...song, platform: provider.platform, requestedBy: requesterName(req) });
}
// Sweep AFTER the queue is rebuilt (see play-playlist).
bot.cleanupQueuedLocalSongs?.("queue_replaced");
const mode = queue.getMode();
let first;
if (mode === "random" || mode === "rloop") {
const idx = Math.floor(Math.random() * queue.size());
first = queue.playAt(idx);
} else {
first = queue.play();
}
const { started, reason } = await startCollection(bot, first);
const playing = queue.current();
const loadedMsg = queueable.length < totalCount
? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)`
: `已加载 ${queueable.length} 首`;
return started && playing
? { ok: true, message: `${loadedMsg},正在播放:${playing.name}` }
: { ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` };
});
res.json(body);
res.json(await startCollection(bot, queueable, provider.platform, requesterName(req), totalCount));
} catch (err) {
const error = musicRequestError(err);
logger.error({ err: error }, "play-artist failed");
+59 -2
View File
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, afterEach } from "vitest";
import { interpolateElapsed, type TimingState } from "./player.js";
import { describe, it, expect, vi, afterEach, beforeEach } from "vitest";
import { createPinia, setActivePinia } from "pinia";
import axios from "axios";
import { interpolateElapsed, usePlayerStore, type Song, type TimingState } from "./player.js";
afterEach(() => {
vi.restoreAllMocks();
@@ -42,3 +44,58 @@ describe("interpolateElapsed", () => {
expect(interpolateElapsed(t, false, 180)).toBe(180);
});
});
const track: Song = { id: "song", name: "song", artist: "", album: "", coverUrl: "", duration: 180, platform: "netease" };
describe("playback request timing", () => {
beforeEach(() => {
vi.stubGlobal("window", { matchMedia: () => ({ matches: false }) });
vi.useFakeTimers();
setActivePinia(createPinia());
});
afterEach(() => {
vi.clearAllTimers();
vi.useRealTimers();
vi.unstubAllGlobals();
});
it.each(["playSong", "playPlaylist", "playAlbum", "playArtist", "next"] as const)(
"keeps the current clock when %s fails",
async (action) => {
const store = usePlayerStore();
store.activeBotId = "a";
const current = timing({ serverElapsed: 63, serverSyncTime: 10_000, wasPlaying: true });
store.timings.a = current;
vi.spyOn(axios, "post").mockResolvedValue({ data: { ok: false, message: "播放失败" } });
if (action === "playSong") await store.playSong(track);
else if (action === "next") await store.next();
else await store[action]("collection");
expect(store.timings.a).toEqual(current);
expect(store.notification?.type).toBe("error");
},
);
it("keeps an in-flight elapsed response attached to its original bot", async () => {
const store = usePlayerStore();
const status = {
name: "bot", connected: true, playing: true, paused: false, currentSong: track,
queueSize: 1, volume: 50, playMode: "sequential",
};
store.bots = [{ ...status, id: "a" }, { ...status, id: "b" }];
store.activeBotId = "a";
store.timings.b = timing({ serverElapsed: 10 });
let sendElapsed!: (response: { data: { elapsed: number } }) => void;
const response = new Promise<{ data: { elapsed: number } }>(resolve => { sendElapsed = resolve; });
vi.spyOn(axios, "get").mockReturnValue(response);
const syncing = store.syncElapsed();
store.activeBotId = "b";
sendElapsed({ data: { elapsed: 58 } });
await syncing;
expect(store.timings.a?.serverElapsed).toBe(58);
expect(store.timings.b?.serverElapsed).toBe(10);
});
});
+29 -25
View File
@@ -401,12 +401,15 @@ export const usePlayerStore = defineStore('player', {
}
},
/** Poll server for real elapsed time for active bot */
async syncElapsed() {
if (!this.activeBotId || !this.isPlaying) return;
/** Poll the same bot for authoritative elapsed time. */
async syncElapsed(botId = this.activeBotId) {
if (!botId || !this.bots.some(bot => bot.id === botId && bot.playing && !bot.paused)) return;
const timing = this.timings[botId];
try {
const res = await axios.get(`/api/player/${this.activeBotId}/elapsed`);
this._setTiming(this.activeBotId, {
const res = await axios.get(`/api/player/${botId}/elapsed`);
// A newer WebSocket update or poll supersedes this result.
if (this.timings[botId] !== timing) return;
this._setTiming(botId, {
serverElapsed: res.data.elapsed,
serverSyncTime: Date.now(),
wasPlaying: true,
@@ -533,7 +536,8 @@ export const usePlayerStore = defineStore('player', {
},
async playSong(song: Song, skipPartCheck = false) {
if (!this.activeBotId) return;
const botId = this.activeBotId;
if (!botId) return;
if (!skipPartCheck && song.platform === 'bilibili' && !song.id.includes('?p=')) {
const handled = await this.checkBilibiliMultiPart(song, 'play');
if (handled) return;
@@ -541,12 +545,11 @@ export const usePlayerStore = defineStore('player', {
// Guests use the non-destructive "play now" (insert-next + skip) so they
// can't wipe everyone else's queue; members/admins keep the normal behavior.
const endpoint = useSession().isGuest.value ? 'play-now-song' : 'play-song';
const res = await axios.post(`/api/player/${this.activeBotId}/${endpoint}`, { song });
const res = await axios.post(`/api/player/${botId}/${endpoint}`, { song });
if (res.data?.ok === false && res.data?.message) {
this.notify(res.data.message, 'error');
}
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
if (res.data?.ok === true) void this.syncElapsed(botId);
},
async playNextSong(song: Song, skipPartCheck = false) {
@@ -583,14 +586,14 @@ export const usePlayerStore = defineStore('player', {
},
async playPlaylist(playlistId: string, platform = 'netease') {
if (!this.activeBotId) return;
const botId = this.activeBotId;
if (!botId) return;
try {
const res = await axios.post(`/api/player/${this.activeBotId}/play-playlist`, { playlistId, platform });
const res = await axios.post(`/api/player/${botId}/play-playlist`, { playlistId, platform });
if (res.data?.message) {
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
}
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
if (res.data?.ok === true) void this.syncElapsed(botId);
} catch (e: any) {
// A 403 here means a guest lacks the "play entire collection" permission
// (issue #103) — surface it instead of failing silently.
@@ -599,14 +602,14 @@ export const usePlayerStore = defineStore('player', {
},
async playAlbum(albumId: string, platform = 'netease') {
if (!this.activeBotId) return;
const botId = this.activeBotId;
if (!botId) return;
try {
const res = await axios.post(`/api/player/${this.activeBotId}/play-album`, { albumId, platform });
const res = await axios.post(`/api/player/${botId}/play-album`, { albumId, platform });
if (res.data?.message) {
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
}
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
if (res.data?.ok === true) void this.syncElapsed(botId);
} catch (e: any) {
this.notify(e?.response?.status === 403 ? '没有权限播放整个专辑' : '播放专辑失败', 'error');
}
@@ -618,18 +621,18 @@ export const usePlayerStore = defineStore('player', {
* trips, so the caller gets a "loading" notice first.
*/
async playArtist(artistId: string, platform = 'netease') {
if (!this.activeBotId) return;
const botId = this.activeBotId;
if (!botId) return;
this.notify('正在载入该歌手的全部歌曲…', 'info');
try {
const res = await axios.post(
`/api/player/${this.activeBotId}/play-artist`,
`/api/player/${botId}/play-artist`,
{ artistId, platform },
);
if (res.data?.message) {
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
}
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
if (res.data?.ok === true) void this.syncElapsed(botId);
} catch (e: any) {
const status = e?.response?.status;
this.notify(
@@ -665,10 +668,11 @@ export const usePlayerStore = defineStore('player', {
},
async next() {
if (!this.activeBotId) return;
await axios.post(`/api/player/${this.activeBotId}/next`);
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
const botId = this.activeBotId;
if (!botId) return;
const res = await axios.post(`/api/player/${botId}/next`);
if (res.data?.ok === false && res.data?.message) this.notify(res.data.message, 'error');
if (res.data?.ok === true) void this.syncElapsed(botId);
},
async prev() {