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,14 +1,17 @@
|
|||
import { Events } from "discord.js";
|
||||
import { showGameServers } from "../features/showGameServers.js";
|
||||
|
||||
const event = {
|
||||
name: Events.ClientReady,
|
||||
once: true,
|
||||
|
||||
const event = {
|
||||
name: Events.ClientReady,
|
||||
once: true,
|
||||
async execute(client) {
|
||||
console.log(
|
||||
`[${new Date().toLocaleString()}] Logged in as ${client.user.tag}`
|
||||
);
|
||||
|
||||
console.log(
|
||||
`[${new Date().toLocaleString()}] Logged in as ${client.user.tag}`
|
||||
);
|
||||
|
||||
// File rechargée au démarrage : reprendre si quelqu'un est déjà dans le salon vocal.
|
||||
client.musicQueue?.evaluateAloneStatus();
|
||||
|
||||
try {
|
||||
await showGameServers(client);
|
||||
} catch (error) {
|
||||
|
|
@ -16,5 +19,5 @@ const event = {
|
|||
}
|
||||
},
|
||||
};
|
||||
|
||||
export { event };
|
||||
|
||||
export { event };
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
|
|
|
|||
27
src/music/queuePersistence.js
Normal file
27
src/music/queuePersistence.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
// Enregistre la file dans un fichier JSON (écriture atomique) et ne recharge que les morceaux
|
||||
// dont le fichier existe encore.
|
||||
function createQueuePersistence(filePath) {
|
||||
return {
|
||||
load() {
|
||||
if (!fs.existsSync(filePath)) return null;
|
||||
const state = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
||||
return {
|
||||
...state,
|
||||
queue: (state.queue || []).filter(
|
||||
(track) => typeof track?.path === "string" && fs.existsSync(track.path)
|
||||
),
|
||||
};
|
||||
},
|
||||
save(state) {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
const temporaryFile = `${filePath}.${process.pid}.tmp`;
|
||||
fs.writeFileSync(temporaryFile, JSON.stringify(state, null, 2));
|
||||
fs.renameSync(temporaryFile, filePath);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export { createQueuePersistence };
|
||||
40
src/web/routes/events.js
Normal file
40
src/web/routes/events.js
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import { Router } from "express";
|
||||
|
||||
const HEARTBEAT_INTERVAL = 25_000;
|
||||
|
||||
// Flux d'événements (Server-Sent Events) : « queue » envoie l'état de la file à chaque
|
||||
// changement, « library » signale que la bibliothèque a changé. La page s'en sert à la place
|
||||
// d'un rafraîchissement périodique.
|
||||
function eventsRouter({ queue }) {
|
||||
const router = Router();
|
||||
|
||||
router.get("/", (req, res) => {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "text/event-stream; charset=utf-8",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
Connection: "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
});
|
||||
|
||||
const send = (event, data) => {
|
||||
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
||||
};
|
||||
const onQueueUpdate = (snapshot) => send("queue", snapshot);
|
||||
const onLibraryUpdate = () => send("library", {});
|
||||
|
||||
send("queue", queue.snapshot());
|
||||
queue.on("queueUpdate", onQueueUpdate);
|
||||
queue.on("libraryUpdate", onLibraryUpdate);
|
||||
const heartbeat = setInterval(() => res.write(": ping\n\n"), HEARTBEAT_INTERVAL);
|
||||
|
||||
req.on("close", () => {
|
||||
clearInterval(heartbeat);
|
||||
queue.off("queueUpdate", onQueueUpdate);
|
||||
queue.off("libraryUpdate", onLibraryUpdate);
|
||||
});
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
export { eventsRouter };
|
||||
|
|
@ -4,6 +4,7 @@ import {
|
|||
deletePermanentTrack,
|
||||
findPermanentTrack,
|
||||
getPermanentLibrary,
|
||||
updatePermanentTracks,
|
||||
} from "../storage/storageManager.js";
|
||||
import { serializeTrack, serializeTracks } from "../serializers.js";
|
||||
|
||||
|
|
@ -22,9 +23,45 @@ function libraryRouter({ queue }) {
|
|||
}
|
||||
|
||||
queue.removeByLibraryId(track.id);
|
||||
queue.emit("libraryUpdate");
|
||||
res.json({ removed: serializeTrack(track) });
|
||||
});
|
||||
|
||||
router.patch("/:libraryId", (req, res) => {
|
||||
const title = String(req.body?.title ?? "")
|
||||
.replace(/[\u0000-\u001f]/g, "")
|
||||
.trim()
|
||||
.slice(0, 200);
|
||||
if (!title) {
|
||||
return res.status(400).json({ error: "Titre manquant" });
|
||||
}
|
||||
|
||||
const [track] = updatePermanentTracks(new Map([[req.params.libraryId, { title }]]));
|
||||
if (!track) {
|
||||
return res.status(404).json({ error: "Fichier permanent introuvable" });
|
||||
}
|
||||
|
||||
queue.renameLibraryTrack(track.id, title);
|
||||
queue.emit("libraryUpdate");
|
||||
res.json({ track: serializeTrack(track) });
|
||||
});
|
||||
|
||||
// Ajoute toute la bibliothèque à la file, mélangée si shuffle vaut true.
|
||||
router.post("/enqueue-all", (req, res) => {
|
||||
const entries = getPermanentLibrary();
|
||||
if (req.body?.shuffle === true) {
|
||||
for (let index = entries.length - 1; index > 0; index--) {
|
||||
const randomIndex = Math.floor(Math.random() * (index + 1));
|
||||
[entries[index], entries[randomIndex]] = [entries[randomIndex], entries[index]];
|
||||
}
|
||||
}
|
||||
|
||||
const tracks = entries.map((entry) =>
|
||||
queue.enqueue(createQueueTrackFromLibrary(entry, req.body?.requestedBy))
|
||||
);
|
||||
res.status(201).json({ tracks: serializeTracks(tracks) });
|
||||
});
|
||||
|
||||
router.post("/:libraryId/enqueue", (req, res) => {
|
||||
const baseTrack = findPermanentTrack(req.params.libraryId);
|
||||
if (!baseTrack) {
|
||||
|
|
|
|||
|
|
@ -28,6 +28,17 @@ function playerRouter({ queue }) {
|
|||
res.json(queue.snapshot());
|
||||
});
|
||||
|
||||
router.post("/shuffle", (req, res) => {
|
||||
res.json(queue.shuffle());
|
||||
});
|
||||
|
||||
router.post("/loop", (req, res) => {
|
||||
if (typeof req.body?.enabled !== "boolean") {
|
||||
return res.status(400).json({ error: "enabled doit être un booléen" });
|
||||
}
|
||||
res.json(queue.setLoop(req.body.enabled));
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
createBearerAuth,
|
||||
localOnly,
|
||||
} from "./middlewares/auth.js";
|
||||
import { eventsRouter } from "./routes/events.js";
|
||||
import { libraryRouter } from "./routes/library.js";
|
||||
import { notificationsRouter } from "./routes/notifications.js";
|
||||
import { playerRouter } from "./routes/player.js";
|
||||
|
|
@ -86,6 +87,7 @@ function createApp(
|
|||
apiRouter.use("/queue", queueRouter(dependencies));
|
||||
apiRouter.use("/library", libraryRouter(dependencies));
|
||||
apiRouter.use("/player", playerRouter(dependencies));
|
||||
apiRouter.use("/events", eventsRouter(dependencies));
|
||||
|
||||
app.use("/api", apiRouter);
|
||||
app.get(["/jukebox", "/jukebox/"], (_req, res) =>
|
||||
|
|
|
|||
|
|
@ -179,7 +179,11 @@ function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") {
|
|||
duration: libraryTrack.duration ?? null,
|
||||
artist: libraryTrack.artist ?? null,
|
||||
permanent: true,
|
||||
uploader: requestedBy,
|
||||
uploader:
|
||||
String(requestedBy ?? "")
|
||||
.replace(/[\u0000-\u001f]/g, "")
|
||||
.trim()
|
||||
.slice(0, 80) || "library",
|
||||
libraryTrackId: libraryTrack.id,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue