Keep the queue across restarts; add shuffle, loop, renaming and live events
- Save the queue to storage/runtime/queue.json and restore it at startup, the interrupted track first; playback resumes once someone is in the voice channel. Shutdown keeps the queued files instead of deleting them. - Shuffle the upcoming tracks; loop mode sends finished tracks back to the end of the queue, except removed or failed ones. - Rename library tracks (queued copies follow), enqueue the whole library, optionally shuffled. - Stream queue and library changes to the web page with Server-Sent Events (GET /api/events). - Sanitise the requester name sent when queueing a library track. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
39d2b6acfb
commit
9fb54798dd
12 changed files with 390 additions and 18 deletions
|
|
@ -1,4 +1,5 @@
|
|||
import { EventEmitter } from "events";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
AudioPlayerStatus,
|
||||
NoSubscriberBehavior,
|
||||
|
|
@ -24,11 +25,23 @@ const AUTO_DISCONNECT_DELAY = 5 * 60 * 1000;
|
|||
const CONNECT_RETRY_DELAYS = [5_000, 15_000, 30_000, 60_000, 60_000];
|
||||
|
||||
class MusicQueue extends EventEmitter {
|
||||
constructor(client, { retryDelays = CONNECT_RETRY_DELAYS } = {}) {
|
||||
// persistence : { load() → état | null, save(état) } pour garder la file d'un démarrage à
|
||||
// l'autre (voir queuePersistence.js). Sans elle, la file est perdue à l'arrêt.
|
||||
constructor(
|
||||
client,
|
||||
{ retryDelays = CONNECT_RETRY_DELAYS, persistence = null } = {}
|
||||
) {
|
||||
super();
|
||||
this.setMaxListeners(50); // une écoute par page web ouverte (flux d'événements)
|
||||
this.client = client;
|
||||
this.queue = [];
|
||||
this.currentTrack = null;
|
||||
this.loop = false;
|
||||
// Le morceau en cours ne doit pas revenir en fin de file en mode boucle (retiré, en
|
||||
// erreur, file vidée).
|
||||
this.discardCurrent = false;
|
||||
this.persistence = persistence;
|
||||
this.saveTimeout = null;
|
||||
this.connection = null;
|
||||
this.playbackStatus = AudioPlayerStatus.Idle;
|
||||
this.idleDisconnectTimeout = null;
|
||||
|
|
@ -55,21 +68,33 @@ class MusicQueue extends EventEmitter {
|
|||
this.client.on(Events.VoiceStateUpdate, this.voiceStateListener);
|
||||
|
||||
this.audioPlayer.on(AudioPlayerStatus.Idle, () => {
|
||||
if (this.currentTrack) {
|
||||
handleTrackCompletion(this.currentTrack);
|
||||
}
|
||||
const finished = this.currentTrack;
|
||||
this.currentTrack = null;
|
||||
if (finished) {
|
||||
if (this.loop && !this.discardCurrent && !this.shuttingDown) {
|
||||
// Mode boucle : le morceau repart en fin de file, fichier conservé.
|
||||
const { startedAt: _startedAt, ...track } = finished;
|
||||
this.queue.push({ ...track, id: randomUUID() });
|
||||
} else {
|
||||
handleTrackCompletion(finished);
|
||||
}
|
||||
}
|
||||
this.discardCurrent = false;
|
||||
if (!this.shuttingDown) {
|
||||
void this.playNext();
|
||||
}
|
||||
});
|
||||
|
||||
// Après une erreur, le player passe toujours en Idle : le gestionnaire ci-dessus
|
||||
// termine le morceau et lance le suivant.
|
||||
// termine le morceau et lance le suivant (sans le remettre en boucle).
|
||||
this.audioPlayer.on("error", (error) => {
|
||||
console.error("Audio player encountered an error", error);
|
||||
this.discardCurrent = true;
|
||||
});
|
||||
|
||||
this.on("queueUpdate", () => this.scheduleSave());
|
||||
this.restore();
|
||||
|
||||
this.audioPlayer.on("stateChange", (oldState, newState) => {
|
||||
this.playbackStatus = newState.status;
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
|
|
@ -81,6 +106,7 @@ class MusicQueue extends EventEmitter {
|
|||
current: serializeTrack(this.currentTrack),
|
||||
upcoming: serializeTracks(this.queue),
|
||||
status: this.playbackStatus,
|
||||
loop: this.loop,
|
||||
// Millisecondes déjà jouées du morceau en cours (pauses exclues).
|
||||
position: this.audioPlayer?.state?.resource?.playbackDuration ?? 0,
|
||||
};
|
||||
|
|
@ -286,6 +312,7 @@ class MusicQueue extends EventEmitter {
|
|||
if (this.currentTrack && this.currentTrack.id === trackId) {
|
||||
// skip() repasse le player en Idle tout de suite, ce qui efface currentTrack.
|
||||
const removed = this.currentTrack;
|
||||
this.discardCurrent = true;
|
||||
this.skip();
|
||||
return removed;
|
||||
}
|
||||
|
|
@ -322,10 +349,40 @@ class MusicQueue extends EventEmitter {
|
|||
this.cancelConnectRetry();
|
||||
this.queue.forEach((track) => deleteTrackFile(track));
|
||||
this.queue = [];
|
||||
this.discardCurrent = Boolean(this.currentTrack);
|
||||
this.audioPlayer.stop(true);
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
}
|
||||
|
||||
// Mélange les morceaux à venir (le morceau en cours n'est pas touché).
|
||||
shuffle() {
|
||||
for (let index = this.queue.length - 1; index > 0; index--) {
|
||||
const randomIndex = Math.floor(Math.random() * (index + 1));
|
||||
[this.queue[index], this.queue[randomIndex]] = [
|
||||
this.queue[randomIndex],
|
||||
this.queue[index],
|
||||
];
|
||||
}
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
return this.snapshot();
|
||||
}
|
||||
|
||||
setLoop(enabled) {
|
||||
this.loop = Boolean(enabled);
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
return this.snapshot();
|
||||
}
|
||||
|
||||
// Met à jour le titre des morceaux en file venant d'une entrée de bibliothèque renommée.
|
||||
renameLibraryTrack(libraryTrackId, title) {
|
||||
for (const track of [this.currentTrack, ...this.queue]) {
|
||||
if (track && track.libraryTrackId === libraryTrackId) {
|
||||
track.title = title;
|
||||
}
|
||||
}
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
}
|
||||
|
||||
pause() {
|
||||
this.audioPlayer.pause(true);
|
||||
}
|
||||
|
|
@ -363,6 +420,7 @@ class MusicQueue extends EventEmitter {
|
|||
this.currentTrack &&
|
||||
this.currentTrack.libraryTrackId === libraryTrackId
|
||||
) {
|
||||
this.discardCurrent = true;
|
||||
this.skip();
|
||||
}
|
||||
|
||||
|
|
@ -514,17 +572,82 @@ class MusicQueue extends EventEmitter {
|
|||
return this.listeners().length === 0;
|
||||
}
|
||||
|
||||
// Avec la persistance, la file (morceau en cours en tête) est enregistrée et ses fichiers
|
||||
// gardés pour le prochain démarrage ; sans elle, les fichiers temporaires sont supprimés.
|
||||
shutdown() {
|
||||
this.shuttingDown = true;
|
||||
this.cancelIdleDisconnect();
|
||||
this.cancelAloneDisconnect();
|
||||
this.cancelConnectRetry();
|
||||
clearTimeout(this.saveTimeout);
|
||||
this.client.off(Events.VoiceStateUpdate, this.voiceStateListener);
|
||||
|
||||
if (this.persistence) {
|
||||
this.destroyConnection("shutdown", { requeue: true });
|
||||
this.save();
|
||||
return;
|
||||
}
|
||||
|
||||
this.queue.forEach((track) => deleteTrackFile(track));
|
||||
this.queue = [];
|
||||
this.destroyConnection("shutdown");
|
||||
}
|
||||
|
||||
persistedState() {
|
||||
return {
|
||||
// Le morceau en cours reprendra du début, en tête de file.
|
||||
queue: [this.currentTrack, ...this.queue]
|
||||
.filter(Boolean)
|
||||
.map(({ startedAt: _startedAt, ...track }) => track),
|
||||
loop: this.loop,
|
||||
};
|
||||
}
|
||||
|
||||
scheduleSave() {
|
||||
if (!this.persistence || this.saveTimeout || this.shuttingDown) {
|
||||
return;
|
||||
}
|
||||
this.saveTimeout = setTimeout(() => {
|
||||
this.saveTimeout = null;
|
||||
this.save();
|
||||
}, 500);
|
||||
this.saveTimeout.unref?.();
|
||||
}
|
||||
|
||||
save() {
|
||||
if (!this.persistence) return;
|
||||
try {
|
||||
this.persistence.save(this.persistedState());
|
||||
} catch (error) {
|
||||
console.error("Unable to save the music queue", error);
|
||||
}
|
||||
}
|
||||
|
||||
// Recharge la file enregistrée. Elle reste en attente (comme quand le bot est parti faute
|
||||
// d'auditeurs) : la lecture reprend dès qu'il y a quelqu'un dans le salon, avec un ajout
|
||||
// ou avec le bouton Play.
|
||||
restore() {
|
||||
if (!this.persistence) return;
|
||||
let state;
|
||||
try {
|
||||
state = this.persistence.load();
|
||||
} catch (error) {
|
||||
console.error("Unable to restore the music queue", error);
|
||||
return;
|
||||
}
|
||||
if (!state) return;
|
||||
|
||||
this.queue = (Array.isArray(state.queue) ? state.queue : []).filter(
|
||||
(track) => track && typeof track.id === "string" && typeof track.path === "string"
|
||||
);
|
||||
this.loop = Boolean(state.loop);
|
||||
if (this.queue.length > 0) {
|
||||
this.suspendedForAlone = true;
|
||||
console.log(
|
||||
`[${new Date().toLocaleString()}] MusicQueue restored ${this.queue.length} track(s)`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { MusicQueue };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue