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:
Shinuwa 2026-11-29 11:59:58 +01:00
parent 6ca17264e0
commit a1cefe6da5
7 changed files with 363 additions and 77 deletions

View file

@ -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) {
// 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;
}
refreshPromise = performRefresh(options).finally(() => {
refreshPromise = null;
if (background) {
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 } = {}) {
@ -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,13 +219,12 @@ 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);
});
});
elements.libraryList.appendChild(li);
elements.libraryList.appendChild(li);
});
}
@ -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`, {
method: "PATCH",
body: { position: newPosition },
});
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`, {
method: "POST",
body: { requestedBy: state.displayName || "web-ui" },
});
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");