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"),
|
displayNameInput: document.getElementById("displayName"),
|
||||||
settingsForm: document.getElementById("settingsForm"),
|
settingsForm: document.getElementById("settingsForm"),
|
||||||
uploadForm: document.getElementById("uploadForm"),
|
uploadForm: document.getElementById("uploadForm"),
|
||||||
|
uploadSubmitBtn: document.querySelector("#uploadForm button[type='submit']"),
|
||||||
fileInput: document.getElementById("musicFile"),
|
fileInput: document.getElementById("musicFile"),
|
||||||
notesInput: document.getElementById("uploadNotes"),
|
notesInput: document.getElementById("uploadNotes"),
|
||||||
permanentCheckbox: document.getElementById("permanentFile"),
|
permanentCheckbox: document.getElementById("permanentFile"),
|
||||||
|
|
@ -46,6 +47,7 @@ const elements = {
|
||||||
|
|
||||||
let pollIntervalId = null;
|
let pollIntervalId = null;
|
||||||
let refreshPromise = null;
|
let refreshPromise = null;
|
||||||
|
let followUpRefresh = null;
|
||||||
|
|
||||||
const { setStatus, clearStatus } = createStatusManager(elements.status);
|
const { setStatus, clearStatus } = createStatusManager(elements.status);
|
||||||
const apiFetch = createApiClient({
|
const apiFetch = createApiClient({
|
||||||
|
|
@ -53,15 +55,36 @@ const apiFetch = createApiClient({
|
||||||
getApiKey: () => state.apiKey,
|
getApiKey: () => state.apiKey,
|
||||||
});
|
});
|
||||||
|
|
||||||
function refreshAll(options = {}) {
|
// background : rafraîchissement périodique, qui peut réutiliser une requête en cours.
|
||||||
if (refreshPromise) {
|
// 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;
|
return refreshPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
refreshPromise = performRefresh(options).finally(() => {
|
if (background) {
|
||||||
refreshPromise = null;
|
return refreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
followUpRefresh ??= refreshPromise.then(() => {
|
||||||
|
followUpRefresh = null;
|
||||||
|
return refreshAll(options);
|
||||||
});
|
});
|
||||||
return refreshPromise;
|
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 } = {}) {
|
async function performRefresh({ silent = false } = {}) {
|
||||||
|
|
@ -119,7 +142,7 @@ function renderCurrentTrack() {
|
||||||
track.uploader || "inconnu"
|
track.uploader || "inconnu"
|
||||||
)}
|
)}
|
||||||
</div>
|
</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) => {
|
li.querySelectorAll("button").forEach((btn) => {
|
||||||
btn.addEventListener("click", (event) => {
|
btn.addEventListener("click", (event) => {
|
||||||
const action = event.currentTarget.dataset.action;
|
const button = event.currentTarget;
|
||||||
const trackId = event.currentTarget.dataset.track;
|
handleQueueAction(button.dataset.action, button.dataset.track, index, button);
|
||||||
handleQueueAction(action, trackId, index);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -182,7 +204,7 @@ function renderLibrary() {
|
||||||
li.className = "media-item media-item--library";
|
li.className = "media-item media-item--library";
|
||||||
li.innerHTML = `
|
li.innerHTML = `
|
||||||
<div class="media-item__info">
|
<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">
|
<div class="media-item__meta">
|
||||||
${formatBytes(track.size)} • Ajouté le ${formatDate(track.createdAt)}
|
${formatBytes(track.size)} • Ajouté le ${formatDate(track.createdAt)}
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -197,13 +219,12 @@ function renderLibrary() {
|
||||||
|
|
||||||
li.querySelectorAll("button").forEach((btn) => {
|
li.querySelectorAll("button").forEach((btn) => {
|
||||||
btn.addEventListener("click", (event) => {
|
btn.addEventListener("click", (event) => {
|
||||||
const action = event.currentTarget.dataset.libraryAction;
|
const button = event.currentTarget;
|
||||||
const libraryId = event.currentTarget.dataset.libraryId;
|
handleLibraryAction(button.dataset.libraryAction, button.dataset.libraryId, button);
|
||||||
handleLibraryAction(action, libraryId);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
elements.libraryList.appendChild(li);
|
elements.libraryList.appendChild(li);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -226,18 +247,22 @@ function updatePauseResumeButton() {
|
||||||
elements.pauseResumeBtn.disabled = !actionable;
|
elements.pauseResumeBtn.disabled = !actionable;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleQueueAction(action, trackId, index) {
|
async function handleQueueAction(action, trackId, index, button) {
|
||||||
try {
|
try {
|
||||||
if (action === "remove") {
|
if (action === "remove") {
|
||||||
await apiFetch(`/queue/${trackId}`, { method: "DELETE" });
|
await withBusyButton(button, () =>
|
||||||
|
apiFetch(`/queue/${trackId}`, { method: "DELETE" })
|
||||||
|
);
|
||||||
} else if (action === "up" || action === "down") {
|
} else if (action === "up" || action === "down") {
|
||||||
const delta = action === "up" ? -1 : 1;
|
const delta = action === "up" ? -1 : 1;
|
||||||
const newPosition = Math.max(0, Math.min(index + delta, state.queue.length - 1));
|
const newPosition = Math.max(0, Math.min(index + delta, state.queue.length - 1));
|
||||||
if (newPosition === index) return;
|
if (newPosition === index) return;
|
||||||
await apiFetch(`/queue/${trackId}/move`, {
|
await withBusyButton(button, () =>
|
||||||
method: "PATCH",
|
apiFetch(`/queue/${trackId}/move`, {
|
||||||
body: { position: newPosition },
|
method: "PATCH",
|
||||||
});
|
body: { position: newPosition },
|
||||||
|
})
|
||||||
|
);
|
||||||
}
|
}
|
||||||
await refreshAll({ silent: true });
|
await refreshAll({ silent: true });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
@ -245,18 +270,23 @@ async function handleQueueAction(action, trackId, index) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleLibraryAction(action, libraryId) {
|
async function handleLibraryAction(action, libraryId, button) {
|
||||||
try {
|
try {
|
||||||
if (action === "enqueue") {
|
if (action === "enqueue") {
|
||||||
await apiFetch(`/library/${libraryId}/enqueue`, {
|
await withBusyButton(button, () =>
|
||||||
method: "POST",
|
apiFetch(`/library/${libraryId}/enqueue`, {
|
||||||
body: { requestedBy: state.displayName || "web-ui" },
|
method: "POST",
|
||||||
});
|
body: { requestedBy: state.displayName || "web-ui" },
|
||||||
|
})
|
||||||
|
);
|
||||||
|
setStatus("Morceau ajouté à la file", "success");
|
||||||
} else if (action === "delete") {
|
} else if (action === "delete") {
|
||||||
if (!confirm("Supprimer ce fichier permanent ?")) {
|
if (!confirm("Supprimer ce fichier permanent ?")) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await apiFetch(`/library/${libraryId}`, { method: "DELETE" });
|
await withBusyButton(button, () =>
|
||||||
|
apiFetch(`/library/${libraryId}`, { method: "DELETE" })
|
||||||
|
);
|
||||||
}
|
}
|
||||||
await refreshAll({ silent: true });
|
await refreshAll({ silent: true });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
@ -266,7 +296,10 @@ async function handleLibraryAction(action, libraryId) {
|
||||||
|
|
||||||
function startPolling() {
|
function startPolling() {
|
||||||
stopPolling();
|
stopPolling();
|
||||||
pollIntervalId = setInterval(() => refreshAll({ silent: true }), 5000);
|
pollIntervalId = setInterval(
|
||||||
|
() => refreshAll({ silent: true, background: true }),
|
||||||
|
5000
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function stopPolling() {
|
function stopPolling() {
|
||||||
|
|
@ -309,7 +342,9 @@ function bindEvents() {
|
||||||
}
|
}
|
||||||
|
|
||||||
setStatus("Upload en cours...", "info", false);
|
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.uploadForm.reset();
|
||||||
elements.enqueueCheckbox.checked = true;
|
elements.enqueueCheckbox.checked = true;
|
||||||
setStatus("Fichier envoyé avec succès", "success");
|
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.refreshBtn?.addEventListener("click", () => refreshAll());
|
||||||
elements.heroUploadBtn?.addEventListener("click", () =>
|
elements.heroUploadBtn?.addEventListener("click", () =>
|
||||||
elements.uploadSection?.scrollIntoView({ behavior: "smooth" })
|
elements.uploadSection?.scrollIntoView({ behavior: "smooth" })
|
||||||
|
|
@ -334,7 +389,9 @@ function bindEvents() {
|
||||||
button.addEventListener("click", async () => {
|
button.addEventListener("click", async () => {
|
||||||
const action = button.dataset.playerAction;
|
const action = button.dataset.playerAction;
|
||||||
try {
|
try {
|
||||||
await apiFetch(`/player/${action}`, { method: "POST" });
|
await withBusyButton(button, () =>
|
||||||
|
apiFetch(`/player/${action}`, { method: "POST" })
|
||||||
|
);
|
||||||
await refreshAll({ silent: true });
|
await refreshAll({ silent: true });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setStatus(`Action player impossible: ${error.message}`, "error");
|
setStatus(`Action player impossible: ${error.message}`, "error");
|
||||||
|
|
|
||||||
|
|
@ -146,6 +146,11 @@ p {
|
||||||
backdrop-filter: blur(18px);
|
backdrop-filter: blur(18px);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.panel--dragover {
|
||||||
|
border-color: var(--accent);
|
||||||
|
border-style: dashed;
|
||||||
|
}
|
||||||
|
|
||||||
.panel__subtitle {
|
.panel__subtitle {
|
||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
margin-top: 0.35rem;
|
margin-top: 0.35rem;
|
||||||
|
|
|
||||||
|
|
@ -18,9 +18,12 @@ import {
|
||||||
} from "../web/storage/storageManager.js";
|
} from "../web/storage/storageManager.js";
|
||||||
|
|
||||||
const AUTO_DISCONNECT_DELAY = 5 * 60 * 1000;
|
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 {
|
class MusicQueue extends EventEmitter {
|
||||||
constructor(client) {
|
constructor(client, { retryDelays = CONNECT_RETRY_DELAYS } = {}) {
|
||||||
super();
|
super();
|
||||||
this.client = client;
|
this.client = client;
|
||||||
this.queue = [];
|
this.queue = [];
|
||||||
|
|
@ -29,6 +32,9 @@ class MusicQueue extends EventEmitter {
|
||||||
this.playbackStatus = AudioPlayerStatus.Idle;
|
this.playbackStatus = AudioPlayerStatus.Idle;
|
||||||
this.idleDisconnectTimeout = null;
|
this.idleDisconnectTimeout = null;
|
||||||
this.aloneDisconnectTimeout = null;
|
this.aloneDisconnectTimeout = null;
|
||||||
|
this.connectRetryTimeout = null;
|
||||||
|
this.connectFailures = 0;
|
||||||
|
this.retryDelays = retryDelays;
|
||||||
this.suspendedForAlone = false;
|
this.suspendedForAlone = false;
|
||||||
this.playNextPromise = null;
|
this.playNextPromise = null;
|
||||||
this.shuttingDown = false;
|
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) => {
|
this.audioPlayer.on("error", (error) => {
|
||||||
console.error("Audio player encountered an 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) => {
|
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() {
|
async ensureConnection() {
|
||||||
if (this.connection) {
|
if (this.connection) {
|
||||||
if (
|
if (
|
||||||
|
|
@ -129,7 +141,7 @@ class MusicQueue extends EventEmitter {
|
||||||
]);
|
]);
|
||||||
} catch {
|
} catch {
|
||||||
if (this.connection === connection) {
|
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) {
|
enqueue(track) {
|
||||||
this.queue.push(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.cancelIdleDisconnect();
|
||||||
this.emit("queueUpdate", this.snapshot());
|
this.emit("queueUpdate", this.snapshot());
|
||||||
if (!this.currentTrack) {
|
if (!this.currentTrack) {
|
||||||
|
|
@ -174,7 +190,9 @@ class MusicQueue extends EventEmitter {
|
||||||
}
|
}
|
||||||
|
|
||||||
async runPlayNext() {
|
async runPlayNext() {
|
||||||
if (this.suspendedForAlone) {
|
this.cancelConnectRetry();
|
||||||
|
|
||||||
|
if (this.shuttingDown || this.suspendedForAlone) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -189,26 +207,27 @@ class MusicQueue extends EventEmitter {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.ensureConnection();
|
await this.ensureConnection();
|
||||||
|
this.connectFailures = 0;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Unable to connect to the configured voice channel", error);
|
console.error("Unable to connect to the configured voice channel", error);
|
||||||
this.currentTrack = null;
|
this.currentTrack = null;
|
||||||
|
this.scheduleConnectRetry();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (this.shuttingDown || this.suspendedForAlone) {
|
||||||
this.shuttingDown ||
|
|
||||||
this.suspendedForAlone ||
|
|
||||||
this.queue[0]?.id !== nextTrack.id
|
|
||||||
) {
|
|
||||||
return;
|
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 {
|
try {
|
||||||
this.queue.shift();
|
this.queue.shift();
|
||||||
const stream = fs.createReadStream(nextTrack.path);
|
const resource = this.createResource(nextTrack);
|
||||||
const resource = createAudioResource(stream, {
|
|
||||||
inlineVolume: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
this.currentTrack = {
|
this.currentTrack = {
|
||||||
...nextTrack,
|
...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) {
|
async remove(trackId) {
|
||||||
const index = this.queue.findIndex((track) => track.id === trackId);
|
const index = this.queue.findIndex((track) => track.id === trackId);
|
||||||
if (index === -1) {
|
if (index === -1) {
|
||||||
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.
|
||||||
|
const removed = this.currentTrack;
|
||||||
this.skip();
|
this.skip();
|
||||||
return this.currentTrack;
|
return removed;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
@ -262,6 +314,7 @@ class MusicQueue extends EventEmitter {
|
||||||
}
|
}
|
||||||
|
|
||||||
stop() {
|
stop() {
|
||||||
|
this.cancelConnectRetry();
|
||||||
this.queue.forEach((track) => deleteTrackFile(track));
|
this.queue.forEach((track) => deleteTrackFile(track));
|
||||||
this.queue = [];
|
this.queue = [];
|
||||||
this.audioPlayer.stop(true);
|
this.audioPlayer.stop(true);
|
||||||
|
|
@ -278,6 +331,7 @@ class MusicQueue extends EventEmitter {
|
||||||
|
|
||||||
start() {
|
start() {
|
||||||
this.suspendedForAlone = false;
|
this.suspendedForAlone = false;
|
||||||
|
this.connectFailures = 0;
|
||||||
this.cancelIdleDisconnect();
|
this.cancelIdleDisconnect();
|
||||||
if (!this.currentTrack) {
|
if (!this.currentTrack) {
|
||||||
return this.playNext();
|
return this.playNext();
|
||||||
|
|
@ -314,7 +368,9 @@ class MusicQueue extends EventEmitter {
|
||||||
return removed;
|
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) {
|
if (!this.connection && this.playbackStatus === AudioPlayerStatus.Idle) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -328,6 +384,11 @@ class MusicQueue extends EventEmitter {
|
||||||
|
|
||||||
const interruptedTrack = this.currentTrack;
|
const interruptedTrack = this.currentTrack;
|
||||||
this.currentTrack = null;
|
this.currentTrack = null;
|
||||||
|
const requeued = Boolean(requeue && interruptedTrack);
|
||||||
|
if (requeued) {
|
||||||
|
const { startedAt: _startedAt, ...track } = interruptedTrack;
|
||||||
|
this.queue.unshift(track);
|
||||||
|
}
|
||||||
|
|
||||||
if (this.connection) {
|
if (this.connection) {
|
||||||
try {
|
try {
|
||||||
|
|
@ -344,7 +405,9 @@ class MusicQueue extends EventEmitter {
|
||||||
console.error("Failed to stop audio player", error);
|
console.error("Failed to stop audio player", error);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleTrackCompletion(interruptedTrack);
|
if (!requeued) {
|
||||||
|
handleTrackCompletion(interruptedTrack);
|
||||||
|
}
|
||||||
this.emit("queueUpdate", this.snapshot());
|
this.emit("queueUpdate", this.snapshot());
|
||||||
console.log(
|
console.log(
|
||||||
`[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})`
|
`[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})`
|
||||||
|
|
@ -384,7 +447,7 @@ class MusicQueue extends EventEmitter {
|
||||||
this.aloneDisconnectTimeout = setTimeout(() => {
|
this.aloneDisconnectTimeout = setTimeout(() => {
|
||||||
this.aloneDisconnectTimeout = null;
|
this.aloneDisconnectTimeout = null;
|
||||||
if (this.connection && this.isBotAlone()) {
|
if (this.connection && this.isBotAlone()) {
|
||||||
this.destroyConnection("alone timeout", { suspend: true });
|
this.destroyConnection("alone timeout", { suspend: true, requeue: true });
|
||||||
}
|
}
|
||||||
}, AUTO_DISCONNECT_DELAY);
|
}, AUTO_DISCONNECT_DELAY);
|
||||||
}
|
}
|
||||||
|
|
@ -399,6 +462,11 @@ class MusicQueue extends EventEmitter {
|
||||||
evaluateAloneStatus() {
|
evaluateAloneStatus() {
|
||||||
if (!this.connection) {
|
if (!this.connection) {
|
||||||
this.cancelAloneDisconnect();
|
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;
|
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() {
|
isBotAlone() {
|
||||||
const channel = this.client.channels.cache.get(config.voiceChannelId);
|
const channel = this.client.channels.cache.get(config.voiceChannelId);
|
||||||
if (!channel) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const clientId = this.client.user?.id;
|
const clientId = this.client.user?.id;
|
||||||
if (!clientId) {
|
if (!channel || !clientId || !channel.members.has(clientId)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!channel.members.has(clientId)) {
|
return this.listeners().length === 0;
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const others = channel.members.filter((member) => member.id !== clientId);
|
|
||||||
return others.size === 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
shutdown() {
|
shutdown() {
|
||||||
this.shuttingDown = true;
|
this.shuttingDown = true;
|
||||||
this.cancelIdleDisconnect();
|
this.cancelIdleDisconnect();
|
||||||
this.cancelAloneDisconnect();
|
this.cancelAloneDisconnect();
|
||||||
|
this.cancelConnectRetry();
|
||||||
this.client.off(Events.VoiceStateUpdate, this.voiceStateListener);
|
this.client.off(Events.VoiceStateUpdate, this.voiceStateListener);
|
||||||
|
|
||||||
this.queue.forEach((track) => deleteTrackFile(track));
|
this.queue.forEach((track) => deleteTrackFile(track));
|
||||||
|
|
|
||||||
|
|
@ -8,19 +8,9 @@ import {
|
||||||
registerUploadedFile,
|
registerUploadedFile,
|
||||||
} from "../storage/storageManager.js";
|
} from "../storage/storageManager.js";
|
||||||
|
|
||||||
const ALLOWED_AUDIO_TYPES = new Set([
|
// Pas de filtre sur le type MIME : il vient du navigateur et varie selon le système (un MP3
|
||||||
"audio/aac",
|
// peut arriver en « audio/mp3 », un FLAC sans type). Les fichiers refusés disparaissaient sans
|
||||||
"audio/flac",
|
// message clair ; ffprobe vérifie le contenu réel après l'envoi.
|
||||||
"audio/mp4",
|
|
||||||
"audio/mpeg",
|
|
||||||
"audio/ogg",
|
|
||||||
"audio/wav",
|
|
||||||
"audio/webm",
|
|
||||||
"audio/x-flac",
|
|
||||||
"audio/x-m4a",
|
|
||||||
"audio/x-wav",
|
|
||||||
]);
|
|
||||||
|
|
||||||
const upload = multer({
|
const upload = multer({
|
||||||
dest: TEMP_DIR,
|
dest: TEMP_DIR,
|
||||||
limits: {
|
limits: {
|
||||||
|
|
@ -35,7 +25,7 @@ const upload = multer({
|
||||||
callback(error);
|
callback(error);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
callback(null, ALLOWED_AUDIO_TYPES.has(file.mimetype));
|
callback(null, true);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -101,9 +101,17 @@ function createApp(
|
||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const TEMP_CLEANUP_INTERVAL = 60 * 60_000;
|
||||||
|
|
||||||
function startWebServer(dependencies) {
|
function startWebServer(dependencies) {
|
||||||
ensureStorageLayout();
|
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 app = createApp(dependencies);
|
||||||
const port = Number(process.env.PORT || config.webServerPort || 3000);
|
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}`
|
`[${new Date().toLocaleString()}] Web control server listening on port ${port}`
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
server.on("close", () => clearInterval(cleanupInterval));
|
||||||
|
|
||||||
return { app, server };
|
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();
|
ensureStorageLayout();
|
||||||
const cutoff = Date.now() - maxAge;
|
const cutoff = Date.now() - maxAge;
|
||||||
|
|
||||||
|
|
@ -181,6 +182,9 @@ function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const filePath = path.join(TEMP_DIR, entry.name);
|
const filePath = path.join(TEMP_DIR, entry.name);
|
||||||
|
if (keep.has(filePath)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
if (fs.statSync(filePath).mtimeMs < cutoff) {
|
if (fs.statSync(filePath).mtimeMs < cutoff) {
|
||||||
fs.unlinkSync(filePath);
|
fs.unlinkSync(filePath);
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
|
import { EventEmitter } from "node:events";
|
||||||
|
|
||||||
Object.assign(process.env, {
|
Object.assign(process.env, {
|
||||||
NODE_ENV: "test",
|
NODE_ENV: "test",
|
||||||
|
|
@ -50,3 +51,146 @@ test("queue snapshots do not expose filesystem paths", () => {
|
||||||
status: "playing",
|
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