Fix jukebox playback getting stuck and make the web page reflect actions
- Adding a track or someone joining the voice channel now resumes a queue suspended because the bot was alone; before, only the Play button did. - Retry the voice connection with backoff instead of giving up after one failed attempt. - Keep playing when the head of the queue changes while connecting. - Requeue the interrupted track when the bot leaves an empty channel or loses its voice connection. - Removing the current track no longer answers 404; other bots no longer count as listeners. - Accept uploads whatever MIME type the browser sends (ffprobe validates the content) and clean temporary files hourly, sparing queued ones. - Web page: refresh again after an action instead of reusing a stale request, disable buttons while a request runs, show the real start time and custom titles, and support drag and drop. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
6ca17264e0
commit
a1cefe6da5
7 changed files with 363 additions and 77 deletions
|
|
@ -25,6 +25,7 @@ const elements = {
|
|||
displayNameInput: document.getElementById("displayName"),
|
||||
settingsForm: document.getElementById("settingsForm"),
|
||||
uploadForm: document.getElementById("uploadForm"),
|
||||
uploadSubmitBtn: document.querySelector("#uploadForm button[type='submit']"),
|
||||
fileInput: document.getElementById("musicFile"),
|
||||
notesInput: document.getElementById("uploadNotes"),
|
||||
permanentCheckbox: document.getElementById("permanentFile"),
|
||||
|
|
@ -46,6 +47,7 @@ const elements = {
|
|||
|
||||
let pollIntervalId = null;
|
||||
let refreshPromise = null;
|
||||
let followUpRefresh = null;
|
||||
|
||||
const { setStatus, clearStatus } = createStatusManager(elements.status);
|
||||
const apiFetch = createApiClient({
|
||||
|
|
@ -53,15 +55,36 @@ const apiFetch = createApiClient({
|
|||
getApiKey: () => state.apiKey,
|
||||
});
|
||||
|
||||
function refreshAll(options = {}) {
|
||||
if (refreshPromise) {
|
||||
return refreshPromise;
|
||||
}
|
||||
|
||||
// background : rafraîchissement périodique, qui peut réutiliser une requête en cours.
|
||||
// Sinon (après une action), une requête partie avant l'action renverrait l'ancien état :
|
||||
// on en relance une juste après, pour ne pas faire croire que l'action a échoué.
|
||||
function refreshAll({ background = false, ...options } = {}) {
|
||||
if (!refreshPromise) {
|
||||
refreshPromise = performRefresh(options).finally(() => {
|
||||
refreshPromise = null;
|
||||
});
|
||||
return refreshPromise;
|
||||
}
|
||||
|
||||
if (background) {
|
||||
return refreshPromise;
|
||||
}
|
||||
|
||||
followUpRefresh ??= refreshPromise.then(() => {
|
||||
followUpRefresh = null;
|
||||
return refreshAll(options);
|
||||
});
|
||||
return followUpRefresh;
|
||||
}
|
||||
|
||||
// Désactive le bouton pendant la requête, pour éviter les doubles clics (et les doublons).
|
||||
async function withBusyButton(button, action) {
|
||||
if (button) button.disabled = true;
|
||||
try {
|
||||
return await action();
|
||||
} finally {
|
||||
if (button) button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function performRefresh({ silent = false } = {}) {
|
||||
|
|
@ -119,7 +142,7 @@ function renderCurrentTrack() {
|
|||
track.uploader || "inconnu"
|
||||
)}
|
||||
</div>
|
||||
<div class="media-item__meta">Commencé à ${formatDate(track.createdAt)}</div>
|
||||
<div class="media-item__meta">Commencé à ${formatDate(track.startedAt || track.createdAt)}</div>
|
||||
`;
|
||||
}
|
||||
|
||||
|
|
@ -156,9 +179,8 @@ function renderQueue() {
|
|||
|
||||
li.querySelectorAll("button").forEach((btn) => {
|
||||
btn.addEventListener("click", (event) => {
|
||||
const action = event.currentTarget.dataset.action;
|
||||
const trackId = event.currentTarget.dataset.track;
|
||||
handleQueueAction(action, trackId, index);
|
||||
const button = event.currentTarget;
|
||||
handleQueueAction(button.dataset.action, button.dataset.track, index, button);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -182,7 +204,7 @@ function renderLibrary() {
|
|||
li.className = "media-item media-item--library";
|
||||
li.innerHTML = `
|
||||
<div class="media-item__info">
|
||||
<div class="media-item__title">${escapeHtml(track.originalName)}</div>
|
||||
<div class="media-item__title">${escapeHtml(track.title || track.originalName)}</div>
|
||||
<div class="media-item__meta">
|
||||
${formatBytes(track.size)} • Ajouté le ${formatDate(track.createdAt)}
|
||||
</div>
|
||||
|
|
@ -197,9 +219,8 @@ function renderLibrary() {
|
|||
|
||||
li.querySelectorAll("button").forEach((btn) => {
|
||||
btn.addEventListener("click", (event) => {
|
||||
const action = event.currentTarget.dataset.libraryAction;
|
||||
const libraryId = event.currentTarget.dataset.libraryId;
|
||||
handleLibraryAction(action, libraryId);
|
||||
const button = event.currentTarget;
|
||||
handleLibraryAction(button.dataset.libraryAction, button.dataset.libraryId, button);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -226,18 +247,22 @@ function updatePauseResumeButton() {
|
|||
elements.pauseResumeBtn.disabled = !actionable;
|
||||
}
|
||||
|
||||
async function handleQueueAction(action, trackId, index) {
|
||||
async function handleQueueAction(action, trackId, index, button) {
|
||||
try {
|
||||
if (action === "remove") {
|
||||
await apiFetch(`/queue/${trackId}`, { method: "DELETE" });
|
||||
await withBusyButton(button, () =>
|
||||
apiFetch(`/queue/${trackId}`, { method: "DELETE" })
|
||||
);
|
||||
} else if (action === "up" || action === "down") {
|
||||
const delta = action === "up" ? -1 : 1;
|
||||
const newPosition = Math.max(0, Math.min(index + delta, state.queue.length - 1));
|
||||
if (newPosition === index) return;
|
||||
await apiFetch(`/queue/${trackId}/move`, {
|
||||
await withBusyButton(button, () =>
|
||||
apiFetch(`/queue/${trackId}/move`, {
|
||||
method: "PATCH",
|
||||
body: { position: newPosition },
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
await refreshAll({ silent: true });
|
||||
} catch (error) {
|
||||
|
|
@ -245,18 +270,23 @@ async function handleQueueAction(action, trackId, index) {
|
|||
}
|
||||
}
|
||||
|
||||
async function handleLibraryAction(action, libraryId) {
|
||||
async function handleLibraryAction(action, libraryId, button) {
|
||||
try {
|
||||
if (action === "enqueue") {
|
||||
await apiFetch(`/library/${libraryId}/enqueue`, {
|
||||
await withBusyButton(button, () =>
|
||||
apiFetch(`/library/${libraryId}/enqueue`, {
|
||||
method: "POST",
|
||||
body: { requestedBy: state.displayName || "web-ui" },
|
||||
});
|
||||
})
|
||||
);
|
||||
setStatus("Morceau ajouté à la file", "success");
|
||||
} else if (action === "delete") {
|
||||
if (!confirm("Supprimer ce fichier permanent ?")) {
|
||||
return;
|
||||
}
|
||||
await apiFetch(`/library/${libraryId}`, { method: "DELETE" });
|
||||
await withBusyButton(button, () =>
|
||||
apiFetch(`/library/${libraryId}`, { method: "DELETE" })
|
||||
);
|
||||
}
|
||||
await refreshAll({ silent: true });
|
||||
} catch (error) {
|
||||
|
|
@ -266,7 +296,10 @@ async function handleLibraryAction(action, libraryId) {
|
|||
|
||||
function startPolling() {
|
||||
stopPolling();
|
||||
pollIntervalId = setInterval(() => refreshAll({ silent: true }), 5000);
|
||||
pollIntervalId = setInterval(
|
||||
() => refreshAll({ silent: true, background: true }),
|
||||
5000
|
||||
);
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
|
|
@ -309,7 +342,9 @@ function bindEvents() {
|
|||
}
|
||||
|
||||
setStatus("Upload en cours...", "info", false);
|
||||
await apiFetch("/uploads", { method: "POST", body: data });
|
||||
await withBusyButton(elements.uploadSubmitBtn, () =>
|
||||
apiFetch("/uploads", { method: "POST", body: data })
|
||||
);
|
||||
elements.uploadForm.reset();
|
||||
elements.enqueueCheckbox.checked = true;
|
||||
setStatus("Fichier envoyé avec succès", "success");
|
||||
|
|
@ -319,6 +354,26 @@ function bindEvents() {
|
|||
}
|
||||
});
|
||||
|
||||
// Glisser-déposer un fichier sur la section d'upload le sélectionne dans le formulaire.
|
||||
elements.uploadSection?.addEventListener("dragover", (event) => {
|
||||
event.preventDefault();
|
||||
elements.uploadSection.classList.add("panel--dragover");
|
||||
});
|
||||
elements.uploadSection?.addEventListener("dragleave", (event) => {
|
||||
if (!elements.uploadSection.contains(event.relatedTarget)) {
|
||||
elements.uploadSection.classList.remove("panel--dragover");
|
||||
}
|
||||
});
|
||||
elements.uploadSection?.addEventListener("drop", (event) => {
|
||||
event.preventDefault();
|
||||
elements.uploadSection.classList.remove("panel--dragover");
|
||||
const files = event.dataTransfer?.files;
|
||||
if (files?.length) {
|
||||
elements.fileInput.files = files;
|
||||
setStatus(`Fichier prêt : ${files[0].name}`, "info");
|
||||
}
|
||||
});
|
||||
|
||||
elements.refreshBtn?.addEventListener("click", () => refreshAll());
|
||||
elements.heroUploadBtn?.addEventListener("click", () =>
|
||||
elements.uploadSection?.scrollIntoView({ behavior: "smooth" })
|
||||
|
|
@ -334,7 +389,9 @@ function bindEvents() {
|
|||
button.addEventListener("click", async () => {
|
||||
const action = button.dataset.playerAction;
|
||||
try {
|
||||
await apiFetch(`/player/${action}`, { method: "POST" });
|
||||
await withBusyButton(button, () =>
|
||||
apiFetch(`/player/${action}`, { method: "POST" })
|
||||
);
|
||||
await refreshAll({ silent: true });
|
||||
} catch (error) {
|
||||
setStatus(`Action player impossible: ${error.message}`, "error");
|
||||
|
|
|
|||
|
|
@ -146,6 +146,11 @@ p {
|
|||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
.panel--dragover {
|
||||
border-color: var(--accent);
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
.panel__subtitle {
|
||||
color: var(--muted);
|
||||
margin-top: 0.35rem;
|
||||
|
|
|
|||
|
|
@ -18,9 +18,12 @@ import {
|
|||
} from "../web/storage/storageManager.js";
|
||||
|
||||
const AUTO_DISCONNECT_DELAY = 5 * 60 * 1000;
|
||||
// Délais entre les nouvelles tentatives quand le salon vocal est injoignable. Au-delà, la
|
||||
// file attend une action (ajout d'un morceau, bouton Play).
|
||||
const CONNECT_RETRY_DELAYS = [5_000, 15_000, 30_000, 60_000, 60_000];
|
||||
|
||||
class MusicQueue extends EventEmitter {
|
||||
constructor(client) {
|
||||
constructor(client, { retryDelays = CONNECT_RETRY_DELAYS } = {}) {
|
||||
super();
|
||||
this.client = client;
|
||||
this.queue = [];
|
||||
|
|
@ -29,6 +32,9 @@ class MusicQueue extends EventEmitter {
|
|||
this.playbackStatus = AudioPlayerStatus.Idle;
|
||||
this.idleDisconnectTimeout = null;
|
||||
this.aloneDisconnectTimeout = null;
|
||||
this.connectRetryTimeout = null;
|
||||
this.connectFailures = 0;
|
||||
this.retryDelays = retryDelays;
|
||||
this.suspendedForAlone = false;
|
||||
this.playNextPromise = null;
|
||||
this.shuttingDown = false;
|
||||
|
|
@ -57,13 +63,10 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
});
|
||||
|
||||
// Après une erreur, le player passe toujours en Idle : le gestionnaire ci-dessus
|
||||
// termine le morceau et lance le suivant.
|
||||
this.audioPlayer.on("error", (error) => {
|
||||
console.error("Audio player encountered an error", error);
|
||||
handleTrackCompletion(this.currentTrack);
|
||||
this.currentTrack = null;
|
||||
if (!this.shuttingDown) {
|
||||
void this.playNext();
|
||||
}
|
||||
});
|
||||
|
||||
this.audioPlayer.on("stateChange", (oldState, newState) => {
|
||||
|
|
@ -80,6 +83,15 @@ class MusicQueue extends EventEmitter {
|
|||
};
|
||||
}
|
||||
|
||||
// Fichiers encore utiles (file d'attente et morceau en cours), à ne pas nettoyer.
|
||||
inUsePaths() {
|
||||
return new Set(
|
||||
[this.currentTrack, ...this.queue]
|
||||
.map((track) => track?.path)
|
||||
.filter(Boolean)
|
||||
);
|
||||
}
|
||||
|
||||
async ensureConnection() {
|
||||
if (this.connection) {
|
||||
if (
|
||||
|
|
@ -129,7 +141,7 @@ class MusicQueue extends EventEmitter {
|
|||
]);
|
||||
} catch {
|
||||
if (this.connection === connection) {
|
||||
this.destroyConnection("voice connection lost");
|
||||
this.destroyConnection("voice connection lost", { requeue: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
@ -153,6 +165,10 @@ class MusicQueue extends EventEmitter {
|
|||
|
||||
enqueue(track) {
|
||||
this.queue.push(track);
|
||||
// Ajouter un morceau est une demande de lecture explicite : elle lève la suspension
|
||||
// (bot parti faute d'auditeurs) et relance les tentatives de connexion.
|
||||
this.suspendedForAlone = false;
|
||||
this.connectFailures = 0;
|
||||
this.cancelIdleDisconnect();
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
if (!this.currentTrack) {
|
||||
|
|
@ -174,7 +190,9 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
|
||||
async runPlayNext() {
|
||||
if (this.suspendedForAlone) {
|
||||
this.cancelConnectRetry();
|
||||
|
||||
if (this.shuttingDown || this.suspendedForAlone) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -189,26 +207,27 @@ class MusicQueue extends EventEmitter {
|
|||
|
||||
try {
|
||||
await this.ensureConnection();
|
||||
this.connectFailures = 0;
|
||||
} catch (error) {
|
||||
console.error("Unable to connect to the configured voice channel", error);
|
||||
this.currentTrack = null;
|
||||
this.scheduleConnectRetry();
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
this.shuttingDown ||
|
||||
this.suspendedForAlone ||
|
||||
this.queue[0]?.id !== nextTrack.id
|
||||
) {
|
||||
if (this.shuttingDown || this.suspendedForAlone) {
|
||||
return;
|
||||
}
|
||||
|
||||
// La file a pu changer pendant la connexion (morceau retiré ou déplacé) : on repart
|
||||
// de la nouvelle tête de file au lieu d'abandonner.
|
||||
if (this.queue[0]?.id !== nextTrack.id) {
|
||||
return this.runPlayNext();
|
||||
}
|
||||
|
||||
try {
|
||||
this.queue.shift();
|
||||
const stream = fs.createReadStream(nextTrack.path);
|
||||
const resource = createAudioResource(stream, {
|
||||
inlineVolume: true,
|
||||
});
|
||||
const resource = this.createResource(nextTrack);
|
||||
|
||||
this.currentTrack = {
|
||||
...nextTrack,
|
||||
|
|
@ -225,12 +244,45 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
createResource(track) {
|
||||
return createAudioResource(fs.createReadStream(track.path));
|
||||
}
|
||||
|
||||
scheduleConnectRetry() {
|
||||
if (this.shuttingDown || this.queue.length === 0 || this.connectRetryTimeout) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.connectFailures >= this.retryDelays.length) {
|
||||
console.error(
|
||||
`[${new Date().toLocaleString()}] MusicQueue gave up connecting after ${this.connectFailures} retries; the next enqueue or Play will try again`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const delay = this.retryDelays[this.connectFailures];
|
||||
this.connectFailures += 1;
|
||||
this.connectRetryTimeout = setTimeout(() => {
|
||||
this.connectRetryTimeout = null;
|
||||
void this.playNext();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
cancelConnectRetry() {
|
||||
if (this.connectRetryTimeout) {
|
||||
clearTimeout(this.connectRetryTimeout);
|
||||
this.connectRetryTimeout = null;
|
||||
}
|
||||
}
|
||||
|
||||
async remove(trackId) {
|
||||
const index = this.queue.findIndex((track) => track.id === trackId);
|
||||
if (index === -1) {
|
||||
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.skip();
|
||||
return this.currentTrack;
|
||||
return removed;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -262,6 +314,7 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
|
||||
stop() {
|
||||
this.cancelConnectRetry();
|
||||
this.queue.forEach((track) => deleteTrackFile(track));
|
||||
this.queue = [];
|
||||
this.audioPlayer.stop(true);
|
||||
|
|
@ -278,6 +331,7 @@ class MusicQueue extends EventEmitter {
|
|||
|
||||
start() {
|
||||
this.suspendedForAlone = false;
|
||||
this.connectFailures = 0;
|
||||
this.cancelIdleDisconnect();
|
||||
if (!this.currentTrack) {
|
||||
return this.playNext();
|
||||
|
|
@ -314,7 +368,9 @@ class MusicQueue extends EventEmitter {
|
|||
return removed;
|
||||
}
|
||||
|
||||
destroyConnection(reason, { suspend = false } = {}) {
|
||||
// requeue : remet le morceau interrompu en tête de file (il reprendra du début) au lieu
|
||||
// de le perdre, quand la coupure ne vient pas d'une demande d'arrêt.
|
||||
destroyConnection(reason, { suspend = false, requeue = false } = {}) {
|
||||
if (!this.connection && this.playbackStatus === AudioPlayerStatus.Idle) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -328,6 +384,11 @@ class MusicQueue extends EventEmitter {
|
|||
|
||||
const interruptedTrack = this.currentTrack;
|
||||
this.currentTrack = null;
|
||||
const requeued = Boolean(requeue && interruptedTrack);
|
||||
if (requeued) {
|
||||
const { startedAt: _startedAt, ...track } = interruptedTrack;
|
||||
this.queue.unshift(track);
|
||||
}
|
||||
|
||||
if (this.connection) {
|
||||
try {
|
||||
|
|
@ -344,7 +405,9 @@ class MusicQueue extends EventEmitter {
|
|||
console.error("Failed to stop audio player", error);
|
||||
}
|
||||
|
||||
if (!requeued) {
|
||||
handleTrackCompletion(interruptedTrack);
|
||||
}
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
console.log(
|
||||
`[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})`
|
||||
|
|
@ -384,7 +447,7 @@ class MusicQueue extends EventEmitter {
|
|||
this.aloneDisconnectTimeout = setTimeout(() => {
|
||||
this.aloneDisconnectTimeout = null;
|
||||
if (this.connection && this.isBotAlone()) {
|
||||
this.destroyConnection("alone timeout", { suspend: true });
|
||||
this.destroyConnection("alone timeout", { suspend: true, requeue: true });
|
||||
}
|
||||
}, AUTO_DISCONNECT_DELAY);
|
||||
}
|
||||
|
|
@ -399,6 +462,11 @@ class MusicQueue extends EventEmitter {
|
|||
evaluateAloneStatus() {
|
||||
if (!this.connection) {
|
||||
this.cancelAloneDisconnect();
|
||||
// Parti faute d'auditeurs : revenir dès que quelqu'un rejoint le salon.
|
||||
if (this.suspendedForAlone && this.queue.length > 0 && this.hasListeners()) {
|
||||
this.suspendedForAlone = false;
|
||||
void this.playNext();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -414,29 +482,38 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
// Membres humains du salon configuré, sans le bot lui-même ni les autres bots.
|
||||
listeners() {
|
||||
const channel = this.client.channels.cache.get(config.voiceChannelId);
|
||||
const clientId = this.client.user?.id;
|
||||
if (!channel || !clientId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [...channel.members.values()].filter(
|
||||
(member) => member.id !== clientId && !member.user?.bot
|
||||
);
|
||||
}
|
||||
|
||||
hasListeners() {
|
||||
return (this.listeners()?.length ?? 0) > 0;
|
||||
}
|
||||
|
||||
isBotAlone() {
|
||||
const channel = this.client.channels.cache.get(config.voiceChannelId);
|
||||
if (!channel) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const clientId = this.client.user?.id;
|
||||
if (!clientId) {
|
||||
if (!channel || !clientId || !channel.members.has(clientId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!channel.members.has(clientId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const others = channel.members.filter((member) => member.id !== clientId);
|
||||
return others.size === 0;
|
||||
return this.listeners().length === 0;
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
this.shuttingDown = true;
|
||||
this.cancelIdleDisconnect();
|
||||
this.cancelAloneDisconnect();
|
||||
this.cancelConnectRetry();
|
||||
this.client.off(Events.VoiceStateUpdate, this.voiceStateListener);
|
||||
|
||||
this.queue.forEach((track) => deleteTrackFile(track));
|
||||
|
|
|
|||
|
|
@ -8,19 +8,9 @@ import {
|
|||
registerUploadedFile,
|
||||
} from "../storage/storageManager.js";
|
||||
|
||||
const ALLOWED_AUDIO_TYPES = new Set([
|
||||
"audio/aac",
|
||||
"audio/flac",
|
||||
"audio/mp4",
|
||||
"audio/mpeg",
|
||||
"audio/ogg",
|
||||
"audio/wav",
|
||||
"audio/webm",
|
||||
"audio/x-flac",
|
||||
"audio/x-m4a",
|
||||
"audio/x-wav",
|
||||
]);
|
||||
|
||||
// Pas de filtre sur le type MIME : il vient du navigateur et varie selon le système (un MP3
|
||||
// peut arriver en « audio/mp3 », un FLAC sans type). Les fichiers refusés disparaissaient sans
|
||||
// message clair ; ffprobe vérifie le contenu réel après l'envoi.
|
||||
const upload = multer({
|
||||
dest: TEMP_DIR,
|
||||
limits: {
|
||||
|
|
@ -35,7 +25,7 @@ const upload = multer({
|
|||
callback(error);
|
||||
return;
|
||||
}
|
||||
callback(null, ALLOWED_AUDIO_TYPES.has(file.mimetype));
|
||||
callback(null, true);
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -101,9 +101,17 @@ function createApp(
|
|||
return app;
|
||||
}
|
||||
|
||||
const TEMP_CLEANUP_INTERVAL = 60 * 60_000;
|
||||
|
||||
function startWebServer(dependencies) {
|
||||
ensureStorageLayout();
|
||||
cleanupTemporaryFiles();
|
||||
const cleanup = () =>
|
||||
cleanupTemporaryFiles(undefined, { keep: dependencies.queue.inUsePaths() });
|
||||
cleanup();
|
||||
// Les fichiers temporaires de plus de 24 h sont supprimés pendant que le bot tourne,
|
||||
// pas seulement à son démarrage.
|
||||
const cleanupInterval = setInterval(cleanup, TEMP_CLEANUP_INTERVAL);
|
||||
cleanupInterval.unref();
|
||||
|
||||
const app = createApp(dependencies);
|
||||
const port = Number(process.env.PORT || config.webServerPort || 3000);
|
||||
|
|
@ -113,6 +121,7 @@ function startWebServer(dependencies) {
|
|||
`[${new Date().toLocaleString()}] Web control server listening on port ${port}`
|
||||
);
|
||||
});
|
||||
server.on("close", () => clearInterval(cleanupInterval));
|
||||
|
||||
return { app, server };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -171,7 +171,8 @@ function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") {
|
|||
};
|
||||
}
|
||||
|
||||
function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE) {
|
||||
// keep : chemins encore utilisés (file d'attente, morceau en cours), jamais supprimés.
|
||||
function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE, { keep = new Set() } = {}) {
|
||||
ensureStorageLayout();
|
||||
const cutoff = Date.now() - maxAge;
|
||||
|
||||
|
|
@ -181,6 +182,9 @@ function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE) {
|
|||
}
|
||||
|
||||
const filePath = path.join(TEMP_DIR, entry.name);
|
||||
if (keep.has(filePath)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
if (fs.statSync(filePath).mtimeMs < cutoff) {
|
||||
fs.unlinkSync(filePath);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { EventEmitter } from "node:events";
|
||||
|
||||
Object.assign(process.env, {
|
||||
NODE_ENV: "test",
|
||||
|
|
@ -50,3 +51,146 @@ test("queue snapshots do not expose filesystem paths", () => {
|
|||
status: "playing",
|
||||
});
|
||||
});
|
||||
|
||||
const BOT_ID = "bot";
|
||||
|
||||
// Faux client Discord : un salon vocal (identifiant « 1 », comme VOICE_CHANNEL_ID) dont on
|
||||
// choisit les membres.
|
||||
function fakeClient(memberIds = []) {
|
||||
const client = new EventEmitter();
|
||||
const members = new Map(
|
||||
memberIds.map((id) => [id, { id, user: { bot: id === BOT_ID || id.startsWith("otherbot") } }])
|
||||
);
|
||||
client.user = { id: BOT_ID };
|
||||
client.channels = { cache: new Map([["1", { id: "1", members }]]) };
|
||||
return { client, members };
|
||||
}
|
||||
|
||||
// File dont la connexion vocale et la lecture sont simulées.
|
||||
function fakeQueue(client, { connect = async () => {}, retryDelays } = {}) {
|
||||
const queue = new MusicQueue(client, retryDelays ? { retryDelays } : undefined);
|
||||
const played = [];
|
||||
queue.connectAttempts = 0;
|
||||
queue.ensureConnection = async () => {
|
||||
if (queue.connection) return;
|
||||
queue.connectAttempts += 1;
|
||||
await connect();
|
||||
queue.connection = { destroy() {} };
|
||||
};
|
||||
queue.createResource = (track) => track;
|
||||
queue.audioPlayer.play = (resource) => played.push(resource.id);
|
||||
return { queue, played };
|
||||
}
|
||||
|
||||
const track = (id) => ({ id, path: `/nonexistent/${id}`, permanent: true });
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 20));
|
||||
|
||||
test("adding a track resumes a queue suspended because the bot was alone", async () => {
|
||||
const { client } = fakeClient();
|
||||
const { queue, played } = fakeQueue(client);
|
||||
queue.suspendedForAlone = true;
|
||||
|
||||
queue.enqueue(track("a"));
|
||||
await settle();
|
||||
|
||||
assert.deepEqual(played, ["a"]);
|
||||
assert.equal(queue.suspendedForAlone, false);
|
||||
queue.shutdown();
|
||||
});
|
||||
|
||||
test("someone joining the voice channel resumes a suspended queue", async () => {
|
||||
const { client, members } = fakeClient();
|
||||
const { queue, played } = fakeQueue(client);
|
||||
queue.queue.push(track("a"));
|
||||
queue.suspendedForAlone = true;
|
||||
|
||||
members.set("otherbot-1", { id: "otherbot-1", user: { bot: true } });
|
||||
client.emit("voiceStateUpdate", { channelId: null }, { channelId: "1" });
|
||||
await settle();
|
||||
assert.deepEqual(played, [], "another bot joining is not a listener");
|
||||
|
||||
members.set("user-1", { id: "user-1", user: { bot: false } });
|
||||
client.emit("voiceStateUpdate", { channelId: null }, { channelId: "1" });
|
||||
await settle();
|
||||
assert.deepEqual(played, ["a"]);
|
||||
queue.shutdown();
|
||||
});
|
||||
|
||||
test("a failed voice connection is retried", async () => {
|
||||
const { client } = fakeClient();
|
||||
let failures = 1;
|
||||
const { queue, played } = fakeQueue(client, {
|
||||
retryDelays: [10],
|
||||
connect: async () => {
|
||||
if (failures-- > 0) throw new Error("Ready timeout");
|
||||
},
|
||||
});
|
||||
const originalConsoleError = console.error;
|
||||
console.error = () => {};
|
||||
try {
|
||||
queue.enqueue(track("a"));
|
||||
await settle();
|
||||
await settle();
|
||||
} finally {
|
||||
console.error = originalConsoleError;
|
||||
}
|
||||
|
||||
assert.equal(queue.connectAttempts, 2);
|
||||
assert.deepEqual(played, ["a"]);
|
||||
queue.shutdown();
|
||||
});
|
||||
|
||||
test("removing the head of the queue while connecting plays the next track", async () => {
|
||||
const { client } = fakeClient();
|
||||
let release;
|
||||
const { queue, played } = fakeQueue(client, {
|
||||
connect: () => new Promise((resolve) => (release = resolve)),
|
||||
});
|
||||
|
||||
queue.enqueue(track("a"));
|
||||
queue.enqueue(track("b"));
|
||||
await queue.remove("a");
|
||||
release();
|
||||
await settle();
|
||||
|
||||
assert.deepEqual(played, ["b"]);
|
||||
queue.shutdown();
|
||||
});
|
||||
|
||||
test("removing the current track returns it", async () => {
|
||||
const { client } = fakeClient();
|
||||
const { queue } = fakeQueue(client);
|
||||
queue.currentTrack = track("a");
|
||||
queue.audioPlayer.stop = () => {
|
||||
queue.currentTrack = null;
|
||||
return true;
|
||||
};
|
||||
|
||||
assert.equal((await queue.remove("a"))?.id, "a");
|
||||
queue.shutdown();
|
||||
});
|
||||
|
||||
test("leaving an empty channel keeps the interrupted track at the head of the queue", () => {
|
||||
const { client } = fakeClient([BOT_ID]);
|
||||
const { queue } = fakeQueue(client);
|
||||
queue.connection = { destroy() {} };
|
||||
queue.currentTrack = { ...track("a"), startedAt: "2026-01-01T00:00:00.000Z" };
|
||||
queue.queue.push(track("b"));
|
||||
|
||||
queue.destroyConnection("alone timeout", { suspend: true, requeue: true });
|
||||
|
||||
assert.deepEqual(queue.queue.map(({ id }) => id), ["a", "b"]);
|
||||
assert.equal("startedAt" in queue.queue[0], false);
|
||||
assert.equal(queue.suspendedForAlone, true);
|
||||
queue.shutdown();
|
||||
});
|
||||
|
||||
test("other bots do not count as listeners", () => {
|
||||
const { client, members } = fakeClient([BOT_ID, "otherbot-1"]);
|
||||
const { queue } = fakeQueue(client);
|
||||
assert.equal(queue.isBotAlone(), true);
|
||||
|
||||
members.set("user-1", { id: "user-1", user: { bot: false } });
|
||||
assert.equal(queue.isBotAlone(), false);
|
||||
queue.shutdown();
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue