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
|
|
@ -45,7 +45,7 @@ npm run check
|
||||||
Le dossier `storage/` est une donnée applicative et ne doit pas être remplacé
|
Le dossier `storage/` est une donnée applicative et ne doit pas être remplacé
|
||||||
pendant un déploiement. Sauvegarder régulièrement :
|
pendant un déploiement. Sauvegarder régulièrement :
|
||||||
|
|
||||||
- `storage/runtime/library.json` ;
|
- `storage/runtime/library.json` (et `storage/runtime/queue.json`, la file en cours) ;
|
||||||
- `storage/permanent/`.
|
- `storage/permanent/`.
|
||||||
|
|
||||||
Les fichiers placés dans `storage/temp/` sont temporaires et nettoyés après
|
Les fichiers placés dans `storage/temp/` sont temporaires et nettoyés après
|
||||||
|
|
@ -93,6 +93,11 @@ file d'attente.
|
||||||
- Chaque morceau passe par `ffmpeg`, qui normalise le volume (EBU R128) et
|
- Chaque morceau passe par `ffmpeg`, qui normalise le volume (EBU R128) et
|
||||||
encode en Opus : Discord reçoit l'audio sans réencodage.
|
encode en Opus : Discord reçoit l'audio sans réencodage.
|
||||||
|
|
||||||
|
- La file est enregistrée dans `storage/runtime/queue.json` : après un
|
||||||
|
redémarrage, elle reprend dès que quelqu'un est dans le salon vocal.
|
||||||
|
- La page web reçoit les changements en direct par `GET /api/events`
|
||||||
|
(Server-Sent Events, même clé que le reste de l'API).
|
||||||
|
|
||||||
Après l'ajout ou la modification d'une commande, relancer `npm run deploy` pour
|
Après l'ajout ou la modification d'une commande, relancer `npm run deploy` pour
|
||||||
les enregistrer auprès de Discord.
|
les enregistrer auprès de Discord.
|
||||||
|
|
||||||
|
|
|
||||||
7
index.js
7
index.js
|
|
@ -4,6 +4,7 @@ import path from "path";
|
||||||
import { fileURLToPath } from "url";
|
import { fileURLToPath } from "url";
|
||||||
import { config } from "./src/config.js";
|
import { config } from "./src/config.js";
|
||||||
import { MusicQueue } from "./src/music/queue.js";
|
import { MusicQueue } from "./src/music/queue.js";
|
||||||
|
import { createQueuePersistence } from "./src/music/queuePersistence.js";
|
||||||
import { startWebServer } from "./src/web/server.js";
|
import { startWebServer } from "./src/web/server.js";
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
|
|
@ -56,7 +57,11 @@ for (const file of eventFiles) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const musicQueue = new MusicQueue(client);
|
const musicQueue = new MusicQueue(client, {
|
||||||
|
persistence: createQueuePersistence(
|
||||||
|
path.join(process.cwd(), "storage", "runtime", "queue.json")
|
||||||
|
),
|
||||||
|
});
|
||||||
// Les commandes du jukebox (/play, /skip, /queue) y accèdent par interaction.client.
|
// Les commandes du jukebox (/play, /skip, /queue) y accèdent par interaction.client.
|
||||||
client.musicQueue = musicQueue;
|
client.musicQueue = musicQueue;
|
||||||
await client.login(config.token);
|
await client.login(config.token);
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,17 @@
|
||||||
import { Events } from "discord.js";
|
import { Events } from "discord.js";
|
||||||
import { showGameServers } from "../features/showGameServers.js";
|
import { showGameServers } from "../features/showGameServers.js";
|
||||||
|
|
||||||
const event = {
|
const event = {
|
||||||
name: Events.ClientReady,
|
name: Events.ClientReady,
|
||||||
once: true,
|
once: true,
|
||||||
async execute(client) {
|
async execute(client) {
|
||||||
console.log(
|
console.log(
|
||||||
`[${new Date().toLocaleString()}] Logged in as ${client.user.tag}`
|
`[${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 {
|
try {
|
||||||
await showGameServers(client);
|
await showGameServers(client);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
@ -16,5 +19,5 @@ const event = {
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export { event };
|
export { event };
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import { EventEmitter } from "events";
|
import { EventEmitter } from "events";
|
||||||
|
import { randomUUID } from "node:crypto";
|
||||||
import {
|
import {
|
||||||
AudioPlayerStatus,
|
AudioPlayerStatus,
|
||||||
NoSubscriberBehavior,
|
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];
|
const CONNECT_RETRY_DELAYS = [5_000, 15_000, 30_000, 60_000, 60_000];
|
||||||
|
|
||||||
class MusicQueue extends EventEmitter {
|
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();
|
super();
|
||||||
|
this.setMaxListeners(50); // une écoute par page web ouverte (flux d'événements)
|
||||||
this.client = client;
|
this.client = client;
|
||||||
this.queue = [];
|
this.queue = [];
|
||||||
this.currentTrack = null;
|
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.connection = null;
|
||||||
this.playbackStatus = AudioPlayerStatus.Idle;
|
this.playbackStatus = AudioPlayerStatus.Idle;
|
||||||
this.idleDisconnectTimeout = null;
|
this.idleDisconnectTimeout = null;
|
||||||
|
|
@ -55,21 +68,33 @@ class MusicQueue extends EventEmitter {
|
||||||
this.client.on(Events.VoiceStateUpdate, this.voiceStateListener);
|
this.client.on(Events.VoiceStateUpdate, this.voiceStateListener);
|
||||||
|
|
||||||
this.audioPlayer.on(AudioPlayerStatus.Idle, () => {
|
this.audioPlayer.on(AudioPlayerStatus.Idle, () => {
|
||||||
if (this.currentTrack) {
|
const finished = this.currentTrack;
|
||||||
handleTrackCompletion(this.currentTrack);
|
|
||||||
}
|
|
||||||
this.currentTrack = null;
|
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) {
|
if (!this.shuttingDown) {
|
||||||
void this.playNext();
|
void this.playNext();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Après une erreur, le player passe toujours en Idle : le gestionnaire ci-dessus
|
// 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) => {
|
this.audioPlayer.on("error", (error) => {
|
||||||
console.error("Audio player encountered an 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.audioPlayer.on("stateChange", (oldState, newState) => {
|
||||||
this.playbackStatus = newState.status;
|
this.playbackStatus = newState.status;
|
||||||
this.emit("queueUpdate", this.snapshot());
|
this.emit("queueUpdate", this.snapshot());
|
||||||
|
|
@ -81,6 +106,7 @@ class MusicQueue extends EventEmitter {
|
||||||
current: serializeTrack(this.currentTrack),
|
current: serializeTrack(this.currentTrack),
|
||||||
upcoming: serializeTracks(this.queue),
|
upcoming: serializeTracks(this.queue),
|
||||||
status: this.playbackStatus,
|
status: this.playbackStatus,
|
||||||
|
loop: this.loop,
|
||||||
// Millisecondes déjà jouées du morceau en cours (pauses exclues).
|
// Millisecondes déjà jouées du morceau en cours (pauses exclues).
|
||||||
position: this.audioPlayer?.state?.resource?.playbackDuration ?? 0,
|
position: this.audioPlayer?.state?.resource?.playbackDuration ?? 0,
|
||||||
};
|
};
|
||||||
|
|
@ -286,6 +312,7 @@ class MusicQueue extends EventEmitter {
|
||||||
if (this.currentTrack && this.currentTrack.id === trackId) {
|
if (this.currentTrack && this.currentTrack.id === trackId) {
|
||||||
// skip() repasse le player en Idle tout de suite, ce qui efface currentTrack.
|
// skip() repasse le player en Idle tout de suite, ce qui efface currentTrack.
|
||||||
const removed = this.currentTrack;
|
const removed = this.currentTrack;
|
||||||
|
this.discardCurrent = true;
|
||||||
this.skip();
|
this.skip();
|
||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
|
|
@ -322,10 +349,40 @@ class MusicQueue extends EventEmitter {
|
||||||
this.cancelConnectRetry();
|
this.cancelConnectRetry();
|
||||||
this.queue.forEach((track) => deleteTrackFile(track));
|
this.queue.forEach((track) => deleteTrackFile(track));
|
||||||
this.queue = [];
|
this.queue = [];
|
||||||
|
this.discardCurrent = Boolean(this.currentTrack);
|
||||||
this.audioPlayer.stop(true);
|
this.audioPlayer.stop(true);
|
||||||
this.emit("queueUpdate", this.snapshot());
|
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() {
|
pause() {
|
||||||
this.audioPlayer.pause(true);
|
this.audioPlayer.pause(true);
|
||||||
}
|
}
|
||||||
|
|
@ -363,6 +420,7 @@ class MusicQueue extends EventEmitter {
|
||||||
this.currentTrack &&
|
this.currentTrack &&
|
||||||
this.currentTrack.libraryTrackId === libraryTrackId
|
this.currentTrack.libraryTrackId === libraryTrackId
|
||||||
) {
|
) {
|
||||||
|
this.discardCurrent = true;
|
||||||
this.skip();
|
this.skip();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -514,17 +572,82 @@ class MusicQueue extends EventEmitter {
|
||||||
return this.listeners().length === 0;
|
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() {
|
shutdown() {
|
||||||
this.shuttingDown = true;
|
this.shuttingDown = true;
|
||||||
this.cancelIdleDisconnect();
|
this.cancelIdleDisconnect();
|
||||||
this.cancelAloneDisconnect();
|
this.cancelAloneDisconnect();
|
||||||
this.cancelConnectRetry();
|
this.cancelConnectRetry();
|
||||||
|
clearTimeout(this.saveTimeout);
|
||||||
this.client.off(Events.VoiceStateUpdate, this.voiceStateListener);
|
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.forEach((track) => deleteTrackFile(track));
|
||||||
this.queue = [];
|
this.queue = [];
|
||||||
this.destroyConnection("shutdown");
|
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 };
|
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,
|
deletePermanentTrack,
|
||||||
findPermanentTrack,
|
findPermanentTrack,
|
||||||
getPermanentLibrary,
|
getPermanentLibrary,
|
||||||
|
updatePermanentTracks,
|
||||||
} from "../storage/storageManager.js";
|
} from "../storage/storageManager.js";
|
||||||
import { serializeTrack, serializeTracks } from "../serializers.js";
|
import { serializeTrack, serializeTracks } from "../serializers.js";
|
||||||
|
|
||||||
|
|
@ -22,9 +23,45 @@ function libraryRouter({ queue }) {
|
||||||
}
|
}
|
||||||
|
|
||||||
queue.removeByLibraryId(track.id);
|
queue.removeByLibraryId(track.id);
|
||||||
|
queue.emit("libraryUpdate");
|
||||||
res.json({ removed: serializeTrack(track) });
|
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) => {
|
router.post("/:libraryId/enqueue", (req, res) => {
|
||||||
const baseTrack = findPermanentTrack(req.params.libraryId);
|
const baseTrack = findPermanentTrack(req.params.libraryId);
|
||||||
if (!baseTrack) {
|
if (!baseTrack) {
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,17 @@ function playerRouter({ queue }) {
|
||||||
res.json(queue.snapshot());
|
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;
|
return router;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ import {
|
||||||
createBearerAuth,
|
createBearerAuth,
|
||||||
localOnly,
|
localOnly,
|
||||||
} from "./middlewares/auth.js";
|
} from "./middlewares/auth.js";
|
||||||
|
import { eventsRouter } from "./routes/events.js";
|
||||||
import { libraryRouter } from "./routes/library.js";
|
import { libraryRouter } from "./routes/library.js";
|
||||||
import { notificationsRouter } from "./routes/notifications.js";
|
import { notificationsRouter } from "./routes/notifications.js";
|
||||||
import { playerRouter } from "./routes/player.js";
|
import { playerRouter } from "./routes/player.js";
|
||||||
|
|
@ -86,6 +87,7 @@ function createApp(
|
||||||
apiRouter.use("/queue", queueRouter(dependencies));
|
apiRouter.use("/queue", queueRouter(dependencies));
|
||||||
apiRouter.use("/library", libraryRouter(dependencies));
|
apiRouter.use("/library", libraryRouter(dependencies));
|
||||||
apiRouter.use("/player", playerRouter(dependencies));
|
apiRouter.use("/player", playerRouter(dependencies));
|
||||||
|
apiRouter.use("/events", eventsRouter(dependencies));
|
||||||
|
|
||||||
app.use("/api", apiRouter);
|
app.use("/api", apiRouter);
|
||||||
app.get(["/jukebox", "/jukebox/"], (_req, res) =>
|
app.get(["/jukebox", "/jukebox/"], (_req, res) =>
|
||||||
|
|
|
||||||
|
|
@ -179,7 +179,11 @@ function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") {
|
||||||
duration: libraryTrack.duration ?? null,
|
duration: libraryTrack.duration ?? null,
|
||||||
artist: libraryTrack.artist ?? null,
|
artist: libraryTrack.artist ?? null,
|
||||||
permanent: true,
|
permanent: true,
|
||||||
uploader: requestedBy,
|
uploader:
|
||||||
|
String(requestedBy ?? "")
|
||||||
|
.replace(/[\u0000-\u001f]/g, "")
|
||||||
|
.trim()
|
||||||
|
.slice(0, 80) || "library",
|
||||||
libraryTrackId: libraryTrack.id,
|
libraryTrackId: libraryTrack.id,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -44,11 +44,13 @@ test("queue snapshots do not expose filesystem paths", () => {
|
||||||
queue.currentTrack = { id: "current", path: "/private/current.mp3" };
|
queue.currentTrack = { id: "current", path: "/private/current.mp3" };
|
||||||
queue.queue = [{ id: "next", path: "/private/next.mp3" }];
|
queue.queue = [{ id: "next", path: "/private/next.mp3" }];
|
||||||
queue.playbackStatus = "playing";
|
queue.playbackStatus = "playing";
|
||||||
|
queue.loop = false;
|
||||||
|
|
||||||
assert.deepEqual(queue.snapshot(), {
|
assert.deepEqual(queue.snapshot(), {
|
||||||
current: { id: "current" },
|
current: { id: "current" },
|
||||||
upcoming: [{ id: "next" }],
|
upcoming: [{ id: "next" }],
|
||||||
status: "playing",
|
status: "playing",
|
||||||
|
loop: false,
|
||||||
position: 0,
|
position: 0,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
@ -195,3 +197,53 @@ test("other bots do not count as listeners", () => {
|
||||||
assert.equal(queue.isBotAlone(), false);
|
assert.equal(queue.isBotAlone(), false);
|
||||||
queue.shutdown();
|
queue.shutdown();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("in loop mode a finished track goes back to the end of the queue", () => {
|
||||||
|
const { client } = fakeClient();
|
||||||
|
const { queue } = fakeQueue(client);
|
||||||
|
queue.setLoop(true);
|
||||||
|
queue.currentTrack = track("a");
|
||||||
|
queue.queue.push(track("b"));
|
||||||
|
queue.playNext = () => {};
|
||||||
|
|
||||||
|
queue.audioPlayer.emit("idle");
|
||||||
|
assert.deepEqual(queue.queue.map(({ path }) => path), ["/nonexistent/b", "/nonexistent/a"]);
|
||||||
|
|
||||||
|
// Un morceau retiré ou en erreur ne revient pas.
|
||||||
|
queue.currentTrack = track("c");
|
||||||
|
queue.audioPlayer.emit("error", new Error("bad file"));
|
||||||
|
queue.audioPlayer.emit("idle");
|
||||||
|
assert.equal(queue.queue.some(({ path }) => path === "/nonexistent/c"), false);
|
||||||
|
queue.shutdown();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("shuffle keeps every upcoming track", () => {
|
||||||
|
const { client } = fakeClient();
|
||||||
|
const { queue } = fakeQueue(client);
|
||||||
|
queue.queue.push(...["a", "b", "c", "d", "e"].map(track));
|
||||||
|
queue.shuffle();
|
||||||
|
assert.deepEqual(queue.queue.map(({ id }) => id).sort(), ["a", "b", "c", "d", "e"]);
|
||||||
|
queue.shutdown();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the queue survives a restart and waits for listeners", () => {
|
||||||
|
let saved = null;
|
||||||
|
const persistence = { load: () => saved, save: (state) => (saved = state) };
|
||||||
|
const { client } = fakeClient();
|
||||||
|
|
||||||
|
const first = new MusicQueue(client, { persistence });
|
||||||
|
first.queue.push(track("b"));
|
||||||
|
first.currentTrack = { ...track("a"), startedAt: "2026-01-01T00:00:00.000Z" };
|
||||||
|
first.connection = { destroy() {} };
|
||||||
|
first.setLoop(true);
|
||||||
|
first.shutdown();
|
||||||
|
|
||||||
|
assert.deepEqual(saved.queue.map(({ id }) => id), ["a", "b"]);
|
||||||
|
assert.equal("startedAt" in saved.queue[0], false);
|
||||||
|
|
||||||
|
const second = new MusicQueue(client, { persistence });
|
||||||
|
assert.deepEqual(second.queue.map(({ id }) => id), ["a", "b"]);
|
||||||
|
assert.equal(second.loop, true);
|
||||||
|
assert.equal(second.suspendedForAlone, true);
|
||||||
|
second.shutdown();
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -127,3 +127,66 @@ test("/readyz reports whether the bot is connected to Discord", async () => {
|
||||||
await new Promise((resolve) => server.close(resolve));
|
await new Promise((resolve) => server.close(resolve));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("the events stream sends the queue state, then every update", async () => {
|
||||||
|
const { EventEmitter } = await import("node:events");
|
||||||
|
const queue = new EventEmitter();
|
||||||
|
let snapshot = { current: null, upcoming: [], status: "idle", loop: false, position: 0 };
|
||||||
|
queue.snapshot = () => snapshot;
|
||||||
|
queue.setLoop = (enabled) => {
|
||||||
|
snapshot = { ...snapshot, loop: enabled };
|
||||||
|
queue.emit("queueUpdate", snapshot);
|
||||||
|
return snapshot;
|
||||||
|
};
|
||||||
|
|
||||||
|
const app = createApp({ queue, client: fakeClient() });
|
||||||
|
const server = app.listen(0, "127.0.0.1");
|
||||||
|
await new Promise((resolve) => server.once("listening", resolve));
|
||||||
|
const base = `http://127.0.0.1:${server.address().port}`;
|
||||||
|
const controller = new AbortController();
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${base}/api/events`, {
|
||||||
|
headers: { authorization: "Bearer web-key" },
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
assert.equal(response.status, 200);
|
||||||
|
assert.match(response.headers.get("content-type"), /text\/event-stream/);
|
||||||
|
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
||||||
|
|
||||||
|
let received = "";
|
||||||
|
const readUntil = async (pattern) => {
|
||||||
|
while (!pattern.test(received)) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
received += value;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
await readUntil(/event: queue\ndata: .*"loop":false/);
|
||||||
|
const loopResponse = await fetch(`${base}/api/player/loop`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { authorization: "Bearer web-key", "content-type": "application/json" },
|
||||||
|
body: JSON.stringify({ enabled: true }),
|
||||||
|
});
|
||||||
|
assert.equal(loopResponse.status, 200);
|
||||||
|
await readUntil(/"loop":true/);
|
||||||
|
assert.match(received, /"loop":true/);
|
||||||
|
|
||||||
|
const invalid = await fetch(`${base}/api/player/loop`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { authorization: "Bearer web-key", "content-type": "application/json" },
|
||||||
|
body: JSON.stringify({ enabled: "yes" }),
|
||||||
|
});
|
||||||
|
assert.equal(invalid.status, 400);
|
||||||
|
} finally {
|
||||||
|
controller.abort();
|
||||||
|
server.closeAllConnections();
|
||||||
|
await new Promise((resolve) => server.close(resolve));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the events stream requires the jukebox key", async () => {
|
||||||
|
await withServer({}, async ({ base }) => {
|
||||||
|
assert.equal((await fetch(`${base}/api/events`)).status, 401);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue