Sections: - The library can be split into named, ordered sections, stored in storage/runtime/sections.json; each track keeps its sectionId. - Sections are created, renamed, reordered and deleted from the page (/api/library/sections). Deleting one keeps its tracks, without a section. - A section, or the tracks without one, can be queued in one go, shuffled or not (enqueue-all takes a sectionId). - The upload form (file or link) picks the section of a kept track. - Without any section, the library stays a plain list. Covers: - A kept track takes the cover embedded in its file (MP3, FLAC...), from the web page or /play garder:. Older tracks are looked at once on startup; a track without one keeps cover: null. - "Renommer" becomes "Modifier": a dialog to change the title, the section and the cover (upload with preview, or removal). - ffmpeg turns covers into JPEGs of at most 512 px, stored in storage/covers and deleted with their track. An uploaded image is only passed to ffmpeg after its signature is checked (PNG, JPEG, WebP, GIF), with that decoder forced, so ffmpeg never guesses the format of an unknown file. - Covers are served under /covers without authentication, since an <img> cannot send the key; their random names are only given by the API and never change content (one-year cache). - The current track and the queue show the cover of their library track. Docs: README lists the new data to back up; storage/covers is ignored. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1087 lines
38 KiB
JavaScript
1087 lines
38 KiB
JavaScript
/**
|
|
* @file Page du jukebox : connexion (Discord ou mot de passe), lecteur, file d'attente, bibliothèque
|
|
* (sections, pochettes) et ajout de morceaux.
|
|
*
|
|
* Contexte : servi tel quel au navigateur (module ES, sans compilation) ; ne parle qu'à l'API de
|
|
* src/web/.
|
|
* Points d'entrée : initialize (au chargement), connectEvents (flux en direct), refreshAll.
|
|
* Utilisé par : public/jukebox.html.
|
|
* Dépend de : common.js, et des identifiants des éléments de jukebox.html (objet `elements`).
|
|
* Attention :
|
|
* - L'état arrive par le flux /api/events ; tant qu'il est coupé, chaque action recharge tout.
|
|
* - Le flux est lu avec fetch, et non EventSource, qui ne permet pas d'envoyer la clé.
|
|
* - Connecté avec Discord, la session (cookie) remplace la clé : pas d'en-tête Authorization.
|
|
* - Tout texte venu de l'API passe par escapeHtml avant d'aller dans innerHTML.
|
|
* - Les morceaux de la file n'ont pas de pochette : elle est prise sur leur morceau de bibliothèque
|
|
* (libraryTrackId), d'où le nouvel affichage de la file à chaque changement de la bibliothèque.
|
|
* - L'aperçu d'une pochette choisie passe par une URL data: ; la politique de sécurité des contenus
|
|
* (helmet) refuse les URL blob:.
|
|
* @see README.md#jukebox
|
|
*/
|
|
|
|
import {
|
|
createApiClient,
|
|
createStatusManager,
|
|
escapeHtml,
|
|
formatBytes,
|
|
formatDate,
|
|
formatDuration,
|
|
getStoredApiKey,
|
|
getStoredDisplayName,
|
|
isApiKeyRemembered,
|
|
setStoredApiKey,
|
|
setStoredDisplayName,
|
|
} from "./common.js";
|
|
|
|
const LOGIN_ERRORS = {
|
|
denied: "Connexion annulée.",
|
|
state: "La connexion a expiré, réessaie.",
|
|
"not-member": "Ce compte Discord ne fait pas partie du serveur.",
|
|
failed: "La connexion avec Discord a échoué, réessaie.",
|
|
};
|
|
|
|
const state = {
|
|
apiKey: getStoredApiKey(),
|
|
displayName: getStoredDisplayName(),
|
|
oauthEnabled: false,
|
|
user: null,
|
|
queue: [],
|
|
current: null,
|
|
library: [],
|
|
libraryById: new Map(),
|
|
sections: [],
|
|
// Sections repliées par la personne ("" : les morceaux sans section).
|
|
collapsedSections: new Set(),
|
|
status: "idle",
|
|
loop: false,
|
|
// Position du morceau en cours (ms) au moment où l'état a été reçu.
|
|
position: 0,
|
|
positionReceivedAt: 0,
|
|
live: false,
|
|
};
|
|
|
|
const $ = (id) => document.getElementById(id);
|
|
const elements = {
|
|
status: $("status"),
|
|
loggedIn: $("loggedIn"),
|
|
userName: $("userName"),
|
|
logoutBtn: $("logoutBtn"),
|
|
discordLogin: $("discordLogin"),
|
|
keyLogin: $("keyLogin"),
|
|
keyLoginSummary: $("keyLoginSummary"),
|
|
apiKeyInput: $("apiKey"),
|
|
rememberKeyCheckbox: $("rememberKey"),
|
|
displayNameInput: $("displayName"),
|
|
settingsForm: $("settingsForm"),
|
|
liveIndicator: $("liveIndicator"),
|
|
currentTrack: $("currentTrack"),
|
|
progress: $("progress"),
|
|
progressTrack: $("progressTrack"),
|
|
progressBar: $("progressBar"),
|
|
progressElapsed: $("progressElapsed"),
|
|
progressTotal: $("progressTotal"),
|
|
pauseResumeBtn: $("pauseResumeBtn"),
|
|
loopBtn: $("loopBtn"),
|
|
playerButtons: document.querySelectorAll("[data-player-action]"),
|
|
queueList: $("queueList"),
|
|
queueEmpty: $("queueEmpty"),
|
|
queueSummary: $("queueSummary"),
|
|
libraryList: $("libraryList"),
|
|
libraryEmpty: $("libraryEmpty"),
|
|
librarySearch: $("librarySearch"),
|
|
newSectionBtn: $("newSectionBtn"),
|
|
enqueueAllBtn: $("enqueueAllBtn"),
|
|
enqueueAllShuffledBtn: $("enqueueAllShuffledBtn"),
|
|
uploadSection: $("uploadSection"),
|
|
uploadForm: $("uploadForm"),
|
|
uploadSubmitBtn: document.querySelector("#uploadForm button[type='submit']"),
|
|
fileInput: $("musicFile"),
|
|
notesInput: $("uploadNotes"),
|
|
permanentCheckbox: $("permanentFile"),
|
|
enqueueCheckbox: $("enqueueFile"),
|
|
uploadSectionField: $("uploadSectionField"),
|
|
uploadSectionSelect: $("uploadSectionSelect"),
|
|
uploadList: $("uploadList"),
|
|
urlForm: $("urlForm"),
|
|
urlInput: $("musicUrl"),
|
|
urlSubmitBtn: document.querySelector("#urlForm button[type='submit']"),
|
|
heroUploadBtn: $("heroUploadBtn"),
|
|
heroQueueBtn: $("heroQueueBtn"),
|
|
queueSection: $("queueSection"),
|
|
trackDialog: $("trackDialog"),
|
|
trackForm: $("trackForm"),
|
|
trackCoverPreview: $("trackCoverPreview"),
|
|
trackCoverInput: $("trackCoverInput"),
|
|
trackCoverRemoveBtn: $("trackCoverRemoveBtn"),
|
|
trackTitleInput: $("trackTitleInput"),
|
|
trackSectionSelect: $("trackSectionSelect"),
|
|
trackCancelBtn: $("trackCancelBtn"),
|
|
trackSaveBtn: $("trackSaveBtn"),
|
|
};
|
|
|
|
const { setStatus, clearStatus } = createStatusManager(elements.status);
|
|
|
|
// Connecté avec Discord, la session (cookie) suffit : pas d'en-tête de clé.
|
|
const apiKeyForRequests = () => (state.user ? null : state.apiKey);
|
|
const apiFetch = createApiClient({ basePath: "/api", getApiKey: apiKeyForRequests });
|
|
const canUseApi = () => Boolean(state.user || state.apiKey);
|
|
const requesterName = () => state.user?.name || state.displayName || "web-ui";
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Chargement de l'état
|
|
|
|
let refreshPromise = null;
|
|
let followUpRefresh = null;
|
|
|
|
// Si une requête est déjà partie, ses données peuvent précéder l'action qui demande ce
|
|
// rafraîchissement : on en relance une juste après au lieu de la réutiliser.
|
|
function refreshAll() {
|
|
if (!refreshPromise) {
|
|
refreshPromise = performRefresh().finally(() => {
|
|
refreshPromise = null;
|
|
});
|
|
return refreshPromise;
|
|
}
|
|
followUpRefresh ??= refreshPromise.then(() => {
|
|
followUpRefresh = null;
|
|
return refreshAll();
|
|
});
|
|
return followUpRefresh;
|
|
}
|
|
|
|
async function performRefresh() {
|
|
if (!canUseApi()) return;
|
|
try {
|
|
const [queueData, libraryData] = await Promise.all([
|
|
apiFetch("/queue"),
|
|
apiFetch("/library"),
|
|
]);
|
|
applySnapshot(queueData);
|
|
applyLibrary(libraryData);
|
|
} catch (error) {
|
|
handleApiError(error);
|
|
}
|
|
}
|
|
|
|
async function refreshLibrary() {
|
|
try {
|
|
applyLibrary(await apiFetch("/library"));
|
|
} catch (error) {
|
|
handleApiError(error);
|
|
}
|
|
}
|
|
|
|
// Après une action : le flux en direct apporte le nouvel état ; sans lui, on recharge.
|
|
function afterAction() {
|
|
if (!state.live) {
|
|
return refreshAll();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function handleApiError(error) {
|
|
if (error.status === 401) {
|
|
stopEvents();
|
|
if (state.user) {
|
|
state.user = null;
|
|
renderAuth();
|
|
setStatus("Session expirée, reconnecte-toi.", "error", false);
|
|
} else {
|
|
// Inutile d'insister : chaque échec compte dans la limite anti-force brute du serveur.
|
|
setStatus("Mot de passe refusé, vérifie-le puis sauvegarde.", "error", false);
|
|
}
|
|
return;
|
|
}
|
|
setStatus(`Erreur : ${error.message}`, "error", false);
|
|
}
|
|
|
|
function applySnapshot(snapshot) {
|
|
state.current = snapshot.current;
|
|
state.queue = snapshot.upcoming || [];
|
|
state.status = snapshot.status || "idle";
|
|
state.loop = Boolean(snapshot.loop);
|
|
state.position = Number(snapshot.position) || 0;
|
|
state.positionReceivedAt = performance.now();
|
|
renderCurrentTrack();
|
|
renderQueue();
|
|
renderControls();
|
|
renderProgress();
|
|
}
|
|
|
|
function applyLibrary({ tracks = [], sections = [] }) {
|
|
state.library = tracks;
|
|
state.libraryById = new Map(tracks.map((track) => [track.id, track]));
|
|
state.sections = sections;
|
|
renderLibrary();
|
|
renderSectionChoices();
|
|
renderCurrentTrack();
|
|
renderQueue();
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Flux d'événements en direct (Server-Sent Events lus avec fetch, pour pouvoir envoyer la clé)
|
|
|
|
let eventsController = null;
|
|
let eventsRetryDelay = 1_000;
|
|
let eventsRetryTimeout = null;
|
|
|
|
function setLive(live) {
|
|
state.live = live;
|
|
elements.liveIndicator.dataset.live = String(live);
|
|
elements.liveIndicator.textContent = live ? "En direct" : "Hors ligne";
|
|
}
|
|
|
|
function stopEvents() {
|
|
clearTimeout(eventsRetryTimeout);
|
|
eventsController?.abort();
|
|
eventsController = null;
|
|
setLive(false);
|
|
}
|
|
|
|
function scheduleEventsReconnect() {
|
|
clearTimeout(eventsRetryTimeout);
|
|
eventsRetryTimeout = setTimeout(connectEvents, eventsRetryDelay);
|
|
eventsRetryDelay = Math.min(eventsRetryDelay * 2, 30_000);
|
|
}
|
|
|
|
function handleServerEvent(raw) {
|
|
let event = "message";
|
|
const data = [];
|
|
for (const line of raw.split("\n")) {
|
|
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
else if (line.startsWith("data:")) data.push(line.slice(5).trim());
|
|
}
|
|
if (event === "queue" && data.length) {
|
|
applySnapshot(JSON.parse(data.join("\n")));
|
|
} else if (event === "library") {
|
|
void refreshLibrary();
|
|
}
|
|
}
|
|
|
|
async function connectEvents() {
|
|
stopEvents();
|
|
if (!canUseApi()) return;
|
|
|
|
const controller = new AbortController();
|
|
eventsController = controller;
|
|
try {
|
|
const key = apiKeyForRequests();
|
|
const response = await fetch("/api/events", {
|
|
headers: key ? { Authorization: `Bearer ${key}` } : {},
|
|
cache: "no-store",
|
|
signal: controller.signal,
|
|
});
|
|
if (response.status === 401) {
|
|
handleApiError(Object.assign(new Error("Unauthorized"), { status: 401 }));
|
|
return;
|
|
}
|
|
if (!response.ok || !response.body) {
|
|
throw new Error(`HTTP ${response.status}`);
|
|
}
|
|
|
|
setLive(true);
|
|
eventsRetryDelay = 1_000;
|
|
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
let buffer = "";
|
|
for (;;) {
|
|
const { value, done } = await reader.read();
|
|
if (done) break;
|
|
buffer += value;
|
|
let separator;
|
|
while ((separator = buffer.indexOf("\n\n")) !== -1) {
|
|
handleServerEvent(buffer.slice(0, separator));
|
|
buffer = buffer.slice(separator + 2);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
if (error.name === "AbortError") return;
|
|
}
|
|
|
|
if (eventsController === controller) {
|
|
setLive(false);
|
|
// Le temps de se reconnecter, l'état est rechargé pour ne rien manquer.
|
|
void refreshAll();
|
|
scheduleEventsReconnect();
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Affichage
|
|
|
|
// Pochette d'un morceau : la sienne (bibliothèque), sinon celle de son morceau de bibliothèque.
|
|
function coverUrlOf(track) {
|
|
return track.coverUrl ?? state.libraryById.get(track.libraryTrackId)?.coverUrl ?? null;
|
|
}
|
|
|
|
// Les adresses viennent du serveur (/covers/<nom aléatoire>) mais passent quand même par escapeHtml.
|
|
function coverHtml(url, modifier = "") {
|
|
const className = `cover ${modifier}`.trim();
|
|
return url
|
|
? `<img class="${className}" src="${escapeHtml(url)}" alt="" loading="lazy" />`
|
|
: `<div class="${className} cover--empty" aria-hidden="true"></div>`;
|
|
}
|
|
|
|
function trackMeta(track) {
|
|
const parts = [];
|
|
const duration = formatDuration(track.duration);
|
|
if (duration) parts.push(duration);
|
|
parts.push(track.permanent ? "Permanent" : "Temporaire");
|
|
if (track.size) parts.push(formatBytes(track.size));
|
|
parts.push(`Ajouté par ${escapeHtml(track.uploader || "inconnu")}`);
|
|
return parts.join(" • ");
|
|
}
|
|
|
|
function renderCurrentTrack() {
|
|
const track = state.current;
|
|
if (!track) {
|
|
elements.currentTrack.classList.add("player-current--empty");
|
|
elements.currentTrack.textContent =
|
|
state.queue.length > 0
|
|
? "File en attente : appuie sur Play ou rejoins le salon vocal."
|
|
: "En attente de lecture...";
|
|
return;
|
|
}
|
|
|
|
elements.currentTrack.classList.remove("player-current--empty");
|
|
elements.currentTrack.innerHTML = `
|
|
${coverHtml(coverUrlOf(track), "cover--large")}
|
|
<div class="media-item__info">
|
|
<div class="media-item__title">${escapeHtml(track.title || track.originalName)}</div>
|
|
<div class="media-item__meta">${trackMeta(track)}</div>
|
|
<div class="media-item__meta">Commencé à ${formatDate(track.startedAt || track.createdAt)}</div>
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
function currentPosition() {
|
|
const elapsed =
|
|
state.status === "playing" ? performance.now() - state.positionReceivedAt : 0;
|
|
return state.position + elapsed;
|
|
}
|
|
|
|
function renderProgress() {
|
|
const duration = state.current?.duration;
|
|
if (!state.current || !duration) {
|
|
elements.progress.hidden = true;
|
|
return;
|
|
}
|
|
elements.progress.hidden = false;
|
|
const seconds = Math.min(currentPosition() / 1000, duration);
|
|
const percent = Math.round((seconds / duration) * 100);
|
|
elements.progressBar.style.width = `${percent}%`;
|
|
elements.progressTrack.setAttribute("aria-valuenow", String(percent));
|
|
elements.progressElapsed.textContent = formatDuration(seconds);
|
|
elements.progressTotal.textContent = formatDuration(duration);
|
|
}
|
|
|
|
function renderQueue() {
|
|
elements.queueList.replaceChildren();
|
|
const hasTracks = state.queue.length > 0;
|
|
elements.queueEmpty.hidden = hasTracks;
|
|
elements.queueSummary.hidden = !hasTracks;
|
|
|
|
if (hasTracks) {
|
|
const total = state.queue.reduce((sum, track) => sum + (track.duration || 0), 0);
|
|
const totalLabel = total ? ` • ${formatDuration(total)}` : "";
|
|
elements.queueSummary.textContent = `${state.queue.length} morceau(x)${totalLabel}`;
|
|
}
|
|
|
|
state.queue.forEach((track, index) => {
|
|
const li = document.createElement("li");
|
|
li.className = "media-item media-item--queue";
|
|
li.innerHTML = `
|
|
${coverHtml(coverUrlOf(track))}
|
|
<div class="media-item__info">
|
|
<div class="media-item__title">${index + 1}. ${escapeHtml(track.title || track.originalName)}</div>
|
|
<div class="media-item__meta">${trackMeta(track)}</div>
|
|
</div>
|
|
<div class="media-item__actions">
|
|
<button class="btn btn--secondary btn--small" type="button" data-action="up" aria-label="Monter" title="Monter" ${index === 0 ? "disabled" : ""}>▲</button>
|
|
<button class="btn btn--secondary btn--small" type="button" data-action="down" aria-label="Descendre" title="Descendre" ${index === state.queue.length - 1 ? "disabled" : ""}>▼</button>
|
|
<button class="btn btn--danger btn--small" type="button" data-action="remove">Retirer</button>
|
|
</div>
|
|
`;
|
|
li.querySelectorAll("button").forEach((button) => {
|
|
button.addEventListener("click", () =>
|
|
handleQueueAction(button.dataset.action, track.id, index, button)
|
|
);
|
|
});
|
|
elements.queueList.appendChild(li);
|
|
});
|
|
}
|
|
|
|
// Groupes de la bibliothèque, dans l'ordre des sections ; « Sans section » en dernier.
|
|
function libraryGroups() {
|
|
const groups = state.sections.map((section) => ({ section, tracks: [] }));
|
|
const bySection = new Map(groups.map((group) => [group.section.id, group]));
|
|
const unsorted = { section: null, tracks: [] };
|
|
for (const track of state.library) {
|
|
(bySection.get(track.sectionId) ?? unsorted).tracks.push(track);
|
|
}
|
|
return [...groups, unsorted];
|
|
}
|
|
|
|
function renderLibrary() {
|
|
const query = elements.librarySearch.value.trim().toLowerCase();
|
|
const matches = (track) =>
|
|
`${track.title || ""} ${track.originalName || ""} ${track.artist || ""}`
|
|
.toLowerCase()
|
|
.includes(query);
|
|
const matchCount = state.library.filter(matches).length;
|
|
|
|
elements.libraryList.replaceChildren();
|
|
const isEmpty = state.library.length === 0 && state.sections.length === 0;
|
|
elements.libraryEmpty.hidden = !isEmpty && (matchCount > 0 || !query);
|
|
elements.libraryEmpty.textContent = isEmpty
|
|
? "Aucun fichier permanent enregistré."
|
|
: "Aucun morceau ne correspond à la recherche.";
|
|
elements.enqueueAllBtn.disabled = state.library.length === 0;
|
|
elements.enqueueAllShuffledBtn.disabled = state.library.length === 0;
|
|
|
|
// Sans section créée, la bibliothèque reste une simple liste.
|
|
if (state.sections.length === 0) {
|
|
elements.libraryList.append(renderTrackList(state.library.filter(matches)));
|
|
return;
|
|
}
|
|
|
|
const groups = libraryGroups();
|
|
groups.forEach((group, index) => {
|
|
const shown = group.tracks.filter(matches);
|
|
if (shown.length === 0 && (query || !group.section)) return;
|
|
elements.libraryList.append(
|
|
renderSection(group, shown, {
|
|
index,
|
|
last: state.sections.length - 1,
|
|
searching: Boolean(query),
|
|
})
|
|
);
|
|
});
|
|
}
|
|
|
|
function renderSection({ section, tracks }, shown, { index, last, searching }) {
|
|
const key = section?.id ?? "";
|
|
const details = document.createElement("details");
|
|
details.className = "library-section";
|
|
details.open = searching || !state.collapsedSections.has(key);
|
|
details.addEventListener("toggle", () => {
|
|
if (searching) return;
|
|
if (details.open) state.collapsedSections.delete(key);
|
|
else state.collapsedSections.add(key);
|
|
});
|
|
|
|
const total = tracks.reduce((sum, track) => sum + (track.duration || 0), 0);
|
|
const count = searching ? `${shown.length} sur ${tracks.length}` : String(tracks.length);
|
|
const disabledIfEmpty = tracks.length === 0 ? "disabled" : "";
|
|
details.innerHTML = `
|
|
<summary class="library-section__summary">
|
|
<span class="library-section__name">${escapeHtml(section?.name ?? "Sans section")}</span>
|
|
<span class="library-section__count">
|
|
${count} morceau(x)${total ? ` • ${formatDuration(total)}` : ""}
|
|
</span>
|
|
</summary>
|
|
<div class="library-section__toolbar toolbar">
|
|
<button class="btn btn--secondary btn--small" type="button" data-action="enqueue" ${disabledIfEmpty}>Tout ajouter</button>
|
|
<button class="btn btn--secondary btn--small" type="button" data-action="shuffle" ${disabledIfEmpty}>Mélangé</button>
|
|
${
|
|
section
|
|
? `<button class="btn btn--secondary btn--small" type="button" data-action="rename">Renommer</button>
|
|
<button class="btn btn--secondary btn--small" type="button" data-action="up" aria-label="Monter la section" title="Monter" ${index === 0 ? "disabled" : ""}>▲</button>
|
|
<button class="btn btn--secondary btn--small" type="button" data-action="down" aria-label="Descendre la section" title="Descendre" ${index === last ? "disabled" : ""}>▼</button>
|
|
<button class="btn btn--danger btn--small" type="button" data-action="delete">Supprimer</button>`
|
|
: ""
|
|
}
|
|
</div>
|
|
`;
|
|
details.querySelectorAll(".library-section__toolbar button").forEach((button) => {
|
|
button.addEventListener("click", () =>
|
|
handleSectionAction(button.dataset.action, section, index, button)
|
|
);
|
|
});
|
|
|
|
if (tracks.length === 0) {
|
|
const empty = document.createElement("p");
|
|
empty.className = "hint library-section__empty";
|
|
empty.textContent = "Aucun morceau dans cette section : choisis-la avec « Modifier » sur un morceau.";
|
|
details.append(empty);
|
|
} else {
|
|
details.append(renderTrackList(shown));
|
|
}
|
|
return details;
|
|
}
|
|
|
|
function renderTrackList(tracks) {
|
|
const list = document.createElement("ul");
|
|
list.className = "list list--stack";
|
|
for (const track of tracks) {
|
|
const li = document.createElement("li");
|
|
li.className = "media-item media-item--library";
|
|
const duration = formatDuration(track.duration);
|
|
li.innerHTML = `
|
|
${coverHtml(track.coverUrl)}
|
|
<div class="media-item__info">
|
|
<div class="media-item__title">${escapeHtml(track.title || track.originalName)}</div>
|
|
<div class="media-item__meta">
|
|
${duration ? `${duration} • ` : ""}${formatBytes(track.size)} • Ajouté le ${formatDate(track.createdAt)}
|
|
</div>
|
|
</div>
|
|
<div class="media-item__actions">
|
|
<button class="btn btn--small" type="button" data-action="enqueue">Ajouter</button>
|
|
<button class="btn btn--secondary btn--small" type="button" data-action="edit">Modifier</button>
|
|
<button class="btn btn--danger btn--small" type="button" data-action="delete">Supprimer</button>
|
|
</div>
|
|
`;
|
|
li.querySelectorAll("button").forEach((button) => {
|
|
button.addEventListener("click", () =>
|
|
handleLibraryAction(button.dataset.action, track, button)
|
|
);
|
|
});
|
|
list.append(li);
|
|
}
|
|
return list;
|
|
}
|
|
|
|
// Listes de sections du formulaire d'ajout et de la fenêtre de modification.
|
|
function renderSectionChoices() {
|
|
for (const select of [elements.uploadSectionSelect, elements.trackSectionSelect]) {
|
|
const selected = select.value;
|
|
select.replaceChildren(new Option("Sans section", ""));
|
|
for (const section of state.sections) {
|
|
select.append(new Option(section.name, section.id));
|
|
}
|
|
select.value = state.sections.some((section) => section.id === selected) ? selected : "";
|
|
}
|
|
elements.uploadSectionField.hidden =
|
|
state.sections.length === 0 || !elements.permanentCheckbox.checked;
|
|
}
|
|
|
|
function renderControls() {
|
|
const status = String(state.status).toLowerCase();
|
|
const isPaused = status === "paused" || status === "autopaused";
|
|
const isPlaying = status === "playing" || status === "buffering";
|
|
elements.pauseResumeBtn.textContent = isPaused ? "Reprendre" : "Pause";
|
|
elements.pauseResumeBtn.dataset.playerAction = isPaused ? "resume" : "pause";
|
|
elements.pauseResumeBtn.disabled = !(isPaused || isPlaying);
|
|
elements.loopBtn.setAttribute("aria-pressed", String(state.loop));
|
|
elements.loopBtn.textContent = state.loop ? "Boucle : oui" : "Boucle : non";
|
|
}
|
|
|
|
function renderAuth() {
|
|
const loggedIn = Boolean(state.user);
|
|
elements.loggedIn.hidden = !loggedIn;
|
|
elements.discordLogin.hidden = loggedIn || !state.oauthEnabled;
|
|
// Le mot de passe ne sert qu'en secours, quand la connexion Discord est désactivée. Un mot de
|
|
// passe déjà enregistré dans le navigateur reste envoyé et accepté.
|
|
elements.keyLogin.hidden = loggedIn || state.oauthEnabled;
|
|
if (loggedIn) {
|
|
elements.userName.textContent = state.user.name;
|
|
}
|
|
// Sans connexion Discord, le formulaire du mot de passe est la seule option : déplié.
|
|
if (!state.oauthEnabled) {
|
|
elements.keyLogin.open = true;
|
|
elements.keyLoginSummary.hidden = true;
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Actions
|
|
|
|
// 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 handleQueueAction(action, trackId, index, button) {
|
|
try {
|
|
if (action === "remove") {
|
|
await withBusyButton(button, () => apiFetch(`/queue/${trackId}`, { method: "DELETE" }));
|
|
} else if (action === "up" || action === "down") {
|
|
const position = index + (action === "up" ? -1 : 1);
|
|
if (position < 0 || position >= state.queue.length) return;
|
|
await withBusyButton(button, () =>
|
|
apiFetch(`/queue/${trackId}/move`, { method: "PATCH", body: { position } })
|
|
);
|
|
}
|
|
await afterAction();
|
|
} catch (error) {
|
|
setStatus(`Impossible de mettre à jour la file : ${error.message}`, "error");
|
|
}
|
|
}
|
|
|
|
async function handleLibraryAction(action, track, button) {
|
|
try {
|
|
if (action === "enqueue") {
|
|
await withBusyButton(button, () =>
|
|
apiFetch(`/library/${track.id}/enqueue`, {
|
|
method: "POST",
|
|
body: { requestedBy: requesterName() },
|
|
})
|
|
);
|
|
setStatus(`« ${track.title || track.originalName} » ajouté à la file`, "success");
|
|
} else if (action === "edit") {
|
|
openTrackEditor(track);
|
|
return;
|
|
} else if (action === "delete") {
|
|
if (!confirm(`Supprimer « ${track.title || track.originalName} » de la bibliothèque ?`)) {
|
|
return;
|
|
}
|
|
await withBusyButton(button, () =>
|
|
apiFetch(`/library/${track.id}`, { method: "DELETE" })
|
|
);
|
|
if (!state.live) await refreshLibrary();
|
|
}
|
|
await afterAction();
|
|
} catch (error) {
|
|
setStatus(`Action bibliothèque impossible : ${error.message}`, "error");
|
|
}
|
|
}
|
|
|
|
// sectionId : undefined pour toute la bibliothèque, null pour les morceaux sans section.
|
|
async function enqueueAll(shuffle, button, sectionId) {
|
|
try {
|
|
const { tracks } = await withBusyButton(button, () =>
|
|
apiFetch("/library/enqueue-all", {
|
|
method: "POST",
|
|
body: { shuffle, sectionId, requestedBy: requesterName() },
|
|
})
|
|
);
|
|
setStatus(`${tracks.length} morceau(x) ajouté(s) à la file`, "success");
|
|
await afterAction();
|
|
} catch (error) {
|
|
setStatus(`Ajout impossible : ${error.message}`, "error");
|
|
}
|
|
}
|
|
|
|
async function createSection(button) {
|
|
const name = prompt("Nom de la nouvelle section");
|
|
if (!name || !name.trim()) return;
|
|
try {
|
|
await withBusyButton(button, () =>
|
|
apiFetch("/library/sections", { method: "POST", body: { name: name.trim() } })
|
|
);
|
|
if (!state.live) await refreshLibrary();
|
|
} catch (error) {
|
|
setStatus(`Création de la section impossible : ${error.message}`, "error");
|
|
}
|
|
}
|
|
|
|
// section vaut null pour le groupe « Sans section », qui n'a que les actions d'ajout.
|
|
async function handleSectionAction(action, section, index, button) {
|
|
try {
|
|
if (action === "enqueue" || action === "shuffle") {
|
|
await enqueueAll(action === "shuffle", button, section?.id ?? null);
|
|
return;
|
|
}
|
|
if (action === "rename") {
|
|
const name = prompt("Nouveau nom de la section", section.name);
|
|
if (!name || !name.trim()) return;
|
|
await withBusyButton(button, () =>
|
|
apiFetch(`/library/sections/${section.id}`, {
|
|
method: "PATCH",
|
|
body: { name: name.trim() },
|
|
})
|
|
);
|
|
} else if (action === "up" || action === "down") {
|
|
const position = index + (action === "up" ? -1 : 1);
|
|
await withBusyButton(button, () =>
|
|
apiFetch(`/library/sections/${section.id}`, { method: "PATCH", body: { position } })
|
|
);
|
|
} else if (action === "delete") {
|
|
if (
|
|
!confirm(
|
|
`Supprimer la section « ${section.name} » ? Ses morceaux restent dans la bibliothèque, sans section.`
|
|
)
|
|
) {
|
|
return;
|
|
}
|
|
await withBusyButton(button, () =>
|
|
apiFetch(`/library/sections/${section.id}`, { method: "DELETE" })
|
|
);
|
|
}
|
|
if (!state.live) await refreshLibrary();
|
|
} catch (error) {
|
|
setStatus(`Action sur la section impossible : ${error.message}`, "error");
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Fenêtre de modification d'un morceau (titre, section, pochette)
|
|
|
|
const MAX_COVER_SIZE = 10 * 1024 * 1024;
|
|
let editedTrack = null;
|
|
let removeCover = false;
|
|
|
|
function showCoverPreview(url) {
|
|
const preview = elements.trackCoverPreview;
|
|
preview.classList.toggle("cover--empty", !url);
|
|
preview.style.backgroundImage = url ? `url("${url}")` : "";
|
|
}
|
|
|
|
function openTrackEditor(track) {
|
|
editedTrack = track;
|
|
removeCover = false;
|
|
elements.trackTitleInput.value = track.title || track.originalName;
|
|
renderSectionChoices();
|
|
elements.trackSectionSelect.value = track.sectionId ?? "";
|
|
elements.trackCoverInput.value = "";
|
|
elements.trackCoverRemoveBtn.hidden = !track.coverUrl;
|
|
showCoverPreview(track.coverUrl);
|
|
elements.trackDialog.showModal();
|
|
}
|
|
|
|
function previewChosenCover() {
|
|
const file = elements.trackCoverInput.files[0];
|
|
if (!file) {
|
|
showCoverPreview(removeCover ? null : editedTrack?.coverUrl);
|
|
return;
|
|
}
|
|
if (file.size > MAX_COVER_SIZE) {
|
|
setStatus("Image trop lourde : 10 Mo au plus", "error");
|
|
elements.trackCoverInput.value = "";
|
|
return;
|
|
}
|
|
const reader = new FileReader();
|
|
reader.addEventListener("load", () => showCoverPreview(reader.result));
|
|
reader.readAsDataURL(file);
|
|
elements.trackCoverRemoveBtn.hidden = false;
|
|
}
|
|
|
|
function clearChosenCover() {
|
|
removeCover = true;
|
|
elements.trackCoverInput.value = "";
|
|
elements.trackCoverRemoveBtn.hidden = true;
|
|
showCoverPreview(null);
|
|
}
|
|
|
|
async function saveTrackEditor(event) {
|
|
event.preventDefault();
|
|
const track = editedTrack;
|
|
if (!track) return;
|
|
|
|
const changes = {};
|
|
const title = elements.trackTitleInput.value.trim();
|
|
if (title && title !== (track.title || track.originalName)) changes.title = title;
|
|
const sectionId = elements.trackSectionSelect.value || null;
|
|
if (sectionId !== (track.sectionId ?? null)) changes.sectionId = sectionId;
|
|
const coverFile = elements.trackCoverInput.files[0];
|
|
|
|
try {
|
|
await withBusyButton(elements.trackSaveBtn, async () => {
|
|
if (Object.keys(changes).length > 0) {
|
|
await apiFetch(`/library/${track.id}`, { method: "PATCH", body: changes });
|
|
}
|
|
if (coverFile) {
|
|
const data = new FormData();
|
|
data.append("cover", coverFile);
|
|
await apiFetch(`/library/${track.id}/cover`, { method: "PUT", body: data });
|
|
} else if (removeCover && track.coverUrl) {
|
|
await apiFetch(`/library/${track.id}/cover`, { method: "DELETE" });
|
|
}
|
|
});
|
|
elements.trackDialog.close();
|
|
if (!state.live) await refreshLibrary();
|
|
} catch (error) {
|
|
// La fenêtre reste ouverte : la personne peut corriger (autre image…) et réessayer.
|
|
setStatus(`Modification impossible : ${error.message}`, "error");
|
|
if (!state.live) await refreshLibrary();
|
|
}
|
|
}
|
|
|
|
// Envoi avec XMLHttpRequest : contrairement à fetch, il indique la progression de l'envoi.
|
|
function uploadFile(file, { permanent, enqueue, section, title, onProgress }) {
|
|
return new Promise((resolve, reject) => {
|
|
const data = new FormData();
|
|
data.append("file", file);
|
|
data.append("permanent", String(permanent));
|
|
data.append("enqueue", String(enqueue));
|
|
data.append("uploader", requesterName());
|
|
if (title) data.append("notes", title);
|
|
if (permanent && section) data.append("section", section);
|
|
|
|
const request = new XMLHttpRequest();
|
|
request.open("POST", "/api/uploads");
|
|
const key = apiKeyForRequests();
|
|
if (key) request.setRequestHeader("Authorization", `Bearer ${key}`);
|
|
request.responseType = "json";
|
|
request.upload.addEventListener("progress", (event) => {
|
|
if (event.lengthComputable) onProgress(event.loaded / event.total);
|
|
});
|
|
request.addEventListener("load", () => {
|
|
if (request.status >= 200 && request.status < 300) {
|
|
resolve(request.response);
|
|
} else {
|
|
const error = new Error(request.response?.error || `Erreur ${request.status}`);
|
|
error.status = request.status;
|
|
reject(error);
|
|
}
|
|
});
|
|
request.addEventListener("error", () => reject(new Error("Connexion interrompue")));
|
|
request.send(data);
|
|
});
|
|
}
|
|
|
|
function addUploadRow(name) {
|
|
const li = document.createElement("li");
|
|
li.className = "upload-list__item";
|
|
li.innerHTML = `
|
|
<span class="upload-list__name"></span>
|
|
<progress max="100" value="0"></progress>
|
|
<span class="upload-list__state">En attente</span>
|
|
`;
|
|
li.querySelector(".upload-list__name").textContent = name;
|
|
elements.uploadList.appendChild(li);
|
|
return {
|
|
progress: (ratio) => {
|
|
li.querySelector("progress").value = Math.round(ratio * 100);
|
|
li.querySelector(".upload-list__state").textContent =
|
|
ratio < 1 ? `${Math.round(ratio * 100)} %` : "Vérification…";
|
|
},
|
|
done: (message, ok) => {
|
|
li.querySelector("progress").value = 100;
|
|
li.querySelector(".upload-list__state").textContent = message;
|
|
li.dataset.state = ok ? "ok" : "error";
|
|
},
|
|
};
|
|
}
|
|
|
|
async function handleUpload(event) {
|
|
event.preventDefault();
|
|
const files = [...elements.fileInput.files];
|
|
if (files.length === 0) {
|
|
setStatus("Choisis au moins un fichier audio", "error");
|
|
return;
|
|
}
|
|
|
|
const options = {
|
|
permanent: elements.permanentCheckbox.checked,
|
|
enqueue: elements.enqueueCheckbox.checked,
|
|
section: elements.uploadSectionSelect.value,
|
|
};
|
|
if (!options.permanent && !options.enqueue) {
|
|
setStatus("Un fichier temporaire doit être ajouté à la file d'attente", "error");
|
|
return;
|
|
}
|
|
|
|
const title = files.length === 1 ? elements.notesInput.value.trim() : "";
|
|
elements.uploadList.replaceChildren();
|
|
const rows = files.map((file) => addUploadRow(file.name));
|
|
let succeeded = 0;
|
|
|
|
await withBusyButton(elements.uploadSubmitBtn, async () => {
|
|
for (const [index, file] of files.entries()) {
|
|
try {
|
|
const { track } = await uploadFile(file, {
|
|
...options,
|
|
title,
|
|
onProgress: rows[index].progress,
|
|
});
|
|
rows[index].done(`Ajouté : ${track.title}`, true);
|
|
succeeded += 1;
|
|
} catch (error) {
|
|
rows[index].done(error.message, false);
|
|
if (error.status === 401) {
|
|
handleApiError(error);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
if (succeeded > 0) {
|
|
elements.uploadForm.reset();
|
|
}
|
|
setStatus(
|
|
`${succeeded} fichier(s) sur ${files.length} envoyé(s)`,
|
|
succeeded === files.length ? "success" : "error"
|
|
);
|
|
await afterAction();
|
|
}
|
|
|
|
async function handleUrlSubmit(event) {
|
|
event.preventDefault();
|
|
const url = elements.urlInput.value.trim();
|
|
if (!url) return;
|
|
try {
|
|
setStatus("Téléchargement en cours…", "info", false);
|
|
const { track } = await withBusyButton(elements.urlSubmitBtn, () =>
|
|
apiFetch("/uploads/url", {
|
|
method: "POST",
|
|
body: {
|
|
url,
|
|
permanent: elements.permanentCheckbox.checked,
|
|
enqueue: elements.enqueueCheckbox.checked,
|
|
section: elements.uploadSectionSelect.value || undefined,
|
|
uploader: requesterName(),
|
|
},
|
|
})
|
|
);
|
|
elements.urlForm.reset();
|
|
setStatus(`Ajouté : ${track.title}`, "success");
|
|
await afterAction();
|
|
} catch (error) {
|
|
setStatus(`Ajout impossible : ${error.message}`, "error");
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Connexion
|
|
|
|
async function loadSession() {
|
|
try {
|
|
const response = await fetch("/auth/me", { cache: "no-store" });
|
|
const data = await response.json();
|
|
state.oauthEnabled = Boolean(data.oauthEnabled);
|
|
state.user = data.user || null;
|
|
} catch {
|
|
state.oauthEnabled = false;
|
|
state.user = null;
|
|
}
|
|
}
|
|
|
|
function showLoginError() {
|
|
const params = new URLSearchParams(window.location.search);
|
|
const reason = params.get("login");
|
|
if (!reason) return;
|
|
setStatus(LOGIN_ERRORS[reason] || LOGIN_ERRORS.failed, "error", false);
|
|
history.replaceState(null, "", window.location.pathname);
|
|
}
|
|
|
|
function startSession() {
|
|
if (!canUseApi()) {
|
|
setStatus(
|
|
state.oauthEnabled
|
|
? "Connecte-toi avec Discord pour accéder au jukebox."
|
|
: "Renseigne le mot de passe pour accéder au jukebox.",
|
|
"info",
|
|
false
|
|
);
|
|
return;
|
|
}
|
|
clearStatus();
|
|
void refreshAll();
|
|
void connectEvents();
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Événements de la page
|
|
|
|
function bindEvents() {
|
|
elements.settingsForm.addEventListener("submit", (event) => {
|
|
event.preventDefault();
|
|
state.apiKey = elements.apiKeyInput.value.trim();
|
|
state.displayName = elements.displayNameInput.value.trim();
|
|
setStoredApiKey(state.apiKey, { remember: elements.rememberKeyCheckbox.checked });
|
|
setStoredDisplayName(state.displayName);
|
|
setStatus("Paramètres sauvegardés", "success");
|
|
startSession();
|
|
});
|
|
|
|
elements.logoutBtn.addEventListener("click", async () => {
|
|
await fetch("/auth/logout", { method: "POST" }).catch(() => {});
|
|
state.user = null;
|
|
stopEvents();
|
|
renderAuth();
|
|
startSession();
|
|
});
|
|
|
|
elements.playerButtons.forEach((button) => {
|
|
button.addEventListener("click", async () => {
|
|
const action = button.dataset.playerAction;
|
|
try {
|
|
await withBusyButton(button, () => apiFetch(`/player/${action}`, { method: "POST" }));
|
|
await afterAction();
|
|
} catch (error) {
|
|
setStatus(`Action impossible : ${error.message}`, "error");
|
|
} finally {
|
|
renderControls();
|
|
}
|
|
});
|
|
});
|
|
|
|
elements.loopBtn.addEventListener("click", async () => {
|
|
try {
|
|
const snapshot = await withBusyButton(elements.loopBtn, () =>
|
|
apiFetch("/player/loop", { method: "POST", body: { enabled: !state.loop } })
|
|
);
|
|
applySnapshot(snapshot);
|
|
} catch (error) {
|
|
setStatus(`Action impossible : ${error.message}`, "error");
|
|
}
|
|
});
|
|
|
|
elements.librarySearch.addEventListener("input", renderLibrary);
|
|
elements.newSectionBtn.addEventListener("click", () => createSection(elements.newSectionBtn));
|
|
elements.permanentCheckbox.addEventListener("change", renderSectionChoices);
|
|
|
|
elements.trackForm.addEventListener("submit", saveTrackEditor);
|
|
elements.trackCancelBtn.addEventListener("click", () => elements.trackDialog.close());
|
|
elements.trackCoverInput.addEventListener("change", previewChosenCover);
|
|
elements.trackCoverRemoveBtn.addEventListener("click", clearChosenCover);
|
|
elements.trackDialog.addEventListener("close", () => {
|
|
editedTrack = null;
|
|
});
|
|
elements.enqueueAllBtn.addEventListener("click", () =>
|
|
enqueueAll(false, elements.enqueueAllBtn)
|
|
);
|
|
elements.enqueueAllShuffledBtn.addEventListener("click", () =>
|
|
enqueueAll(true, elements.enqueueAllShuffledBtn)
|
|
);
|
|
|
|
elements.uploadForm.addEventListener("submit", handleUpload);
|
|
elements.urlForm.addEventListener("submit", handleUrlSubmit);
|
|
|
|
// Glisser-déposer des fichiers sur la section d'ajout : ils sont placés 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(`${files.length} fichier(s) prêt(s) à envoyer`, "info");
|
|
}
|
|
});
|
|
|
|
elements.heroUploadBtn.addEventListener("click", () =>
|
|
elements.uploadSection.scrollIntoView({ behavior: "smooth" })
|
|
);
|
|
elements.heroQueueBtn.addEventListener("click", () =>
|
|
elements.queueSection.scrollIntoView({ behavior: "smooth" })
|
|
);
|
|
|
|
// Onglet de nouveau visible : le flux a pu être coupé (mise en veille), on le relance.
|
|
document.addEventListener("visibilitychange", () => {
|
|
if (document.visibilityState === "visible" && canUseApi() && !state.live) {
|
|
eventsRetryDelay = 1_000;
|
|
void connectEvents();
|
|
}
|
|
});
|
|
}
|
|
|
|
async function initialize() {
|
|
elements.apiKeyInput.value = state.apiKey;
|
|
elements.displayNameInput.value = state.displayName;
|
|
elements.rememberKeyCheckbox.checked = isApiKeyRemembered();
|
|
bindEvents();
|
|
renderControls();
|
|
setInterval(renderProgress, 1_000);
|
|
|
|
await loadSession();
|
|
renderAuth();
|
|
startSession();
|
|
showLoginError();
|
|
}
|
|
|
|
initialize();
|