diff --git a/.env.example b/.env.example index 4db695b..362c48c 100644 --- a/.env.example +++ b/.env.example @@ -14,3 +14,11 @@ WEB_TRUSTED_PROXIES= NOTIFICATIONS_API_KEY= # Facultatif : lien d'invitation temporaire publié par /invitation sans option « lien ». INVITE_LINK= +# Facultatif : connexion avec Discord sur la page web (active si les trois sont définies). +# Secret OAuth2 de l'application (portail développeur Discord, onglet OAuth2). +DISCORD_CLIENT_SECRET= +# Adresse publique du site, sans / final (https://…). Ajouter /auth/discord/callback +# aux « Redirects » OAuth2 de l'application. +WEB_PUBLIC_URL= +# 32 caractères au moins (openssl rand -hex 32) ; le changer déconnecte tout le monde. +SESSION_SECRET= diff --git a/.forgejo/workflows/deploy.yml b/.forgejo/workflows/deploy.yml index 8d9f98d..eee2496 100644 --- a/.forgejo/workflows/deploy.yml +++ b/.forgejo/workflows/deploy.yml @@ -1,18 +1,33 @@ name: Deploy Palico Bot +# Les contrôles tournent sur chaque branche ; le déploiement, seulement après un push sur +# main dont les contrôles ont réussi. on: push: - branches: - - main + pull_request: jobs: - deploy: + check: runs-on: docker # Image fixée ici : celle du label « docker » (node:20-bullseye) n'est plus maintenue, # et son miroir de sécurité renvoie 404 (échec du run 4). container: image: node:24-bookworm + steps: + - uses: actions/checkout@v4 + - name: Install dependencies + run: npm ci + - name: Syntax checks and tests + run: npm run check + + deploy: + needs: check + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + runs-on: docker + container: + image: node:24-bookworm + steps: - name: Deploy on WebApps env: diff --git a/README.md b/README.md index f8eb37f..ba7e58d 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ npm run check Le dossier `storage/` est une donnée applicative et ne doit pas être remplacé pendant un déploiement. Sauvegarder régulièrement : -- `storage/runtime/library.json` ; +- `storage/runtime/library.json` (et `storage/runtime/queue.json`, la file en cours) ; - `storage/permanent/`. Les fichiers placés dans `storage/temp/` sont temporaires et nettoyés après @@ -57,12 +57,22 @@ La liste des serveurs de jeux est locale. La créer à partir du modèle : cp src/static/gameservers-list.example.json src/static/gameservers-list.json ``` +L'état de chaque serveur est soit saisi à la main (`"active"`), soit vérifié +toutes les deux minutes par le bot avec `"check": true` : il tente une connexion +TCP sur `"checkPort"` (ou `"port"`) de l'hôte de `"address"`. Pour un jeu dont +le port de jeu est en UDP, indiquer un port TCP annexe (RCON, requête) dans +`"checkPort"`. + ## Déploiement -Un push sur `main` lance `.forgejo/workflows/deploy.yml`, qui se connecte en SSH -à la VM et exécute `/usr/local/bin/deploy-palico-bot` (mise à jour du dépôt, -dépendances, redémarrage du service `palico-bot`). Le workflow ne lance ni les -contrôles ni les tests : lancer `npm run check` avant de pousser. +`.forgejo/workflows/deploy.yml` lance `npm ci` puis `npm run check` (syntaxe et +tests) à chaque push, sur toutes les branches. Sur `main`, et seulement si ces +contrôles réussissent, il se connecte ensuite en SSH à la VM et exécute +`/usr/local/bin/deploy-palico-bot` (mise à jour du dépôt, dépendances, redémarrage +du service `palico-bot`). + +Supervision : `/healthz` répond dès que le processus tourne ; `/readyz` répond +`503` tant que le bot n'est pas connecté à Discord. Variables facultatives : @@ -75,6 +85,44 @@ Variables facultatives : - `INVITE_LINK` : lien publié par `/invitation` quand la commande ne reçoit pas de lien. +## Jukebox + +La page `/jukebox` et les commandes `/play`, `/skip` et `/queue` pilotent la même +file d'attente. + +- `/play fichier:` (pièce jointe), `/play lien:` (lien direct vers un fichier + audio) ou `/play morceau:` (bibliothèque, avec autocomplétion) ; l'option + `garder` ajoute le fichier à la bibliothèque. La page web accepte aussi un + lien direct. YouTube et Spotify ne sont pas pris en charge. +- Le serveur télécharge lui-même les liens et refuse les adresses internes + (réseau local, boucle locale…), y compris après une redirection. +- Chaque morceau passe par `ffmpeg`, qui normalise le volume (EBU R128) et + encode en Opus : Discord reçoit l'audio sans réencodage. + +- La file est enregistrée dans `storage/runtime/queue.json` : après un + redémarrage, elle reprend dès que quelqu'un est dans le salon vocal. +- La page web reçoit les changements en direct par `GET /api/events` + (Server-Sent Events, même clé que le reste de l'API). + +### Connexion avec Discord + +Facultative : sans elle, la page web demande le mot de passe (`WEB_API_KEY`), qui +reste utilisable dans tous les cas. Pour l'activer : + +1. Portail développeur Discord, application du bot, onglet OAuth2 : copier le + secret client et ajouter la redirection `/auth/discord/callback`. +2. Définir `DISCORD_CLIENT_SECRET`, `WEB_PUBLIC_URL` (par exemple + `https://palico.example.com`) et `SESSION_SECRET` (`openssl rand -hex 32`). + +Seuls les membres du serveur (`DISCORD_GUILD_ID`) peuvent se connecter. La +session dure 30 jours (cookie signé, sans stockage côté serveur) et le nom +affiché dans la file est celui du membre sur le serveur. Une personne qui quitte +le serveur garde l'accès jusqu'à l'expiration de sa session ; changer +`SESSION_SECRET` déconnecte tout le monde. + +Après l'ajout ou la modification d'une commande, relancer `npm run deploy` pour +les enregistrer auprès de Discord. + ## Invitations Les membres ne peuvent pas créer d'invitation : un seul lien, à adhésion diff --git a/index.js b/index.js index 3ee14a5..806c80a 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,7 @@ import path from "path"; import { fileURLToPath } from "url"; import { config } from "./src/config.js"; import { MusicQueue } from "./src/music/queue.js"; +import { createQueuePersistence } from "./src/music/queuePersistence.js"; import { startWebServer } from "./src/web/server.js"; const __filename = fileURLToPath(import.meta.url); @@ -56,7 +57,13 @@ for (const file of eventFiles) { } } -const musicQueue = new MusicQueue(client); +const musicQueue = new MusicQueue(client, { + persistence: createQueuePersistence( + path.join(process.cwd(), "storage", "runtime", "queue.json") + ), +}); +// Les commandes du jukebox (/play, /skip, /queue) y accèdent par interaction.client. +client.musicQueue = musicQueue; await client.login(config.token); const { server } = startWebServer({ queue: musicQueue, client }); diff --git a/public/img/apple-touch-icon.png b/public/img/apple-touch-icon.png new file mode 100644 index 0000000..ca6ea21 Binary files /dev/null and b/public/img/apple-touch-icon.png differ diff --git a/public/img/favicon.png b/public/img/favicon.png new file mode 100644 index 0000000..f5db864 Binary files /dev/null and b/public/img/favicon.png differ diff --git a/public/img/palico-index.png b/public/img/palico-index.png deleted file mode 100644 index dc389a7..0000000 Binary files a/public/img/palico-index.png and /dev/null differ diff --git a/public/img/palico-index.webp b/public/img/palico-index.webp new file mode 100644 index 0000000..567eabc Binary files /dev/null and b/public/img/palico-index.webp differ diff --git a/public/img/palico-jukebox.png b/public/img/palico-jukebox.png deleted file mode 100644 index 3196cab..0000000 Binary files a/public/img/palico-jukebox.png and /dev/null differ diff --git a/public/img/palico-jukebox.webp b/public/img/palico-jukebox.webp new file mode 100644 index 0000000..6451a0f Binary files /dev/null and b/public/img/palico-jukebox.webp differ diff --git a/public/index.html b/public/index.html index 9739f4c..7d47b6b 100644 --- a/public/index.html +++ b/public/index.html @@ -4,12 +4,16 @@ Palico Bot + + + +
- Palico Bot + Palico Bot
diff --git a/public/jukebox.html b/public/jukebox.html index b7990d7..9577adf 100644 --- a/public/jukebox.html +++ b/public/jukebox.html @@ -4,177 +4,245 @@ Palico Jukebox + + +
- Palico Jukebox + Palico Jukebox

Le Jukebox du Palico Bot

Un peu de son pour le Discord !

Tu veux chill avec les autres sur un petit fond musical ?
- T'inquietes pas, je peux m'occuper de ca !
+ T'inquiète pas, je peux m'occuper de ça !

- Uploade des fichiers et gère la playlist depuis cette interface web. - Tout est synchronisé avec le salon vocal. + Ajoute des morceaux et gère la playlist depuis cette page, ou avec + /play sur Discord. Tout est synchronisé avec le salon vocal.

- - + +
-

Authentification

-

- La clé reste dans cet onglet jusqu'à sa fermeture. -

-
-
-
- - +

Connexion

+ + + + + +
- + -
+
-

Lecture en cours

-

- État en temps réel du player Discord. Contrôle instantané. -

+

Lecture en cours

+

État du player Discord, mis à jour en direct.

- + Hors ligne
En attente de lecture...
-
- -
+
+ + - - + + +
-
+
-

File d'attente

+

File d'attente

Réorganise les morceaux, supprime-les ou ajoute ceux de la bibliothèque.

+

    Aucun morceau en attente.

    -
    -

    Bibliothèque permanente

    -

    - Les fichiers conservés sont listés ici. Ajoute-les à la file ou - supprime-les. -

    -
      -

      - Aucun fichier permanent enregistré. -

      -
      - -
      +
      -

      Uploader une musique

      +

      Bibliothèque permanente

      - Formats audio supportés par FFmpeg. Les fichiers temporaires sont - supprimés automatiquement après lecture. + Les fichiers conservés sont listés ici. Ajoute-les à la file, + renomme-les ou supprime-les.

      -
      Drag & drop supporté
      +
      + + +
      -
      - - + + +
        +

        Aucun fichier permanent enregistré.

        +
        - +
        +
        +
        +

        Ajouter de la musique

        +

        + Fichiers audio (150 Mo au plus chacun) ou lien direct vers un + fichier. Les morceaux temporaires sont supprimés après lecture. +

        +
        +
        Glisser-déposer accepté
        +
        + +
        + + +
        + + + + + + -
        - - -
        + + - +
          + +
          + +
          + + +
          +

          YouTube et Spotify ne sont pas pris en charge.

          - + Retour à l'accueil
          diff --git a/public/scripts/common.js b/public/scripts/common.js index bf328bb..0e2ec49 100644 --- a/public/scripts/common.js +++ b/public/scripts/common.js @@ -1,20 +1,52 @@ const API_KEY_STORAGE_KEY = "palico-api-key"; const DISPLAY_NAME_STORAGE_KEY = "palico-display-name"; -export function getStoredApiKey() { - return sessionStorage.getItem(API_KEY_STORAGE_KEY) || ""; +// Le stockage peut être indisponible (navigation privée, cookies bloqués) : la page doit +// fonctionner quand même, simplement sans mémoire. +function storageGet(storage, key) { + try { + return storage.getItem(key); + } catch { + return null; + } } -export function setStoredApiKey(value) { - sessionStorage.setItem(API_KEY_STORAGE_KEY, value || ""); +function storageSet(storage, key, value) { + try { + if (value) { + storage.setItem(key, value); + } else { + storage.removeItem(key); + } + } catch { + // Stockage indisponible. + } +} + +export function getStoredApiKey() { + return ( + storageGet(sessionStorage, API_KEY_STORAGE_KEY) || + storageGet(localStorage, API_KEY_STORAGE_KEY) || + "" + ); +} + +export function isApiKeyRemembered() { + return Boolean(storageGet(localStorage, API_KEY_STORAGE_KEY)); +} + +// remember : garde la clé sur l'appareil (localStorage) au lieu de l'onglet (sessionStorage). +export function setStoredApiKey(value, { remember = false } = {}) { + storageSet(remember ? localStorage : sessionStorage, API_KEY_STORAGE_KEY, value); + storageSet(remember ? sessionStorage : localStorage, API_KEY_STORAGE_KEY, ""); } export function getStoredDisplayName() { - return localStorage.getItem(DISPLAY_NAME_STORAGE_KEY) || ""; + return storageGet(localStorage, DISPLAY_NAME_STORAGE_KEY) || ""; } export function setStoredDisplayName(value) { - localStorage.setItem(DISPLAY_NAME_STORAGE_KEY, value || ""); + storageSet(localStorage, DISPLAY_NAME_STORAGE_KEY, value); } export function createStatusManager(statusElement) { @@ -61,6 +93,19 @@ export function formatBytes(bytes = 0) { return `${(bytes / Math.pow(1024, index)).toFixed(1)} ${units[index]}`; } +// Durée lisible : 3:07, 1:05:09. null si inconnue. +export function formatDuration(seconds) { + const value = Number(seconds); + if (!Number.isFinite(value) || value < 0 || seconds === null) return null; + const total = Math.round(value); + const hours = Math.floor(total / 3600); + const minutes = Math.floor((total % 3600) / 60); + const secs = String(total % 60).padStart(2, "0"); + return hours > 0 + ? `${hours}:${String(minutes).padStart(2, "0")}:${secs}` + : `${minutes}:${secs}`; +} + export function formatDate(value) { if (!value) return "?"; try { diff --git a/public/scripts/jukebox.js b/public/scripts/jukebox.js index 51f0342..93b437a 100644 --- a/public/scripts/jukebox.js +++ b/public/scripts/jukebox.js @@ -2,356 +2,780 @@ import { createApiClient, createStatusManager, escapeHtml, - getStoredApiKey, - getStoredDisplayName, 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: [], 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: document.getElementById("status"), - apiKeyInput: document.getElementById("apiKey"), - displayNameInput: document.getElementById("displayName"), - settingsForm: document.getElementById("settingsForm"), - uploadForm: document.getElementById("uploadForm"), - fileInput: document.getElementById("musicFile"), - notesInput: document.getElementById("uploadNotes"), - permanentCheckbox: document.getElementById("permanentFile"), - enqueueCheckbox: document.getElementById("enqueueFile"), - currentTrack: document.getElementById("currentTrack"), - queueList: document.getElementById("queueList"), - queueEmpty: document.getElementById("queueEmpty"), - libraryList: document.getElementById("libraryList"), - libraryEmpty: document.getElementById("libraryEmpty"), - refreshBtn: document.getElementById("refreshBtn"), - pauseResumeBtn: document.getElementById("pauseResumeBtn"), + 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]"), - heroUploadBtn: document.getElementById("heroUploadBtn"), - heroQueueBtn: document.getElementById("heroQueueBtn"), - uploadSection: document.getElementById("uploadSection"), - queueSection: document.getElementById("queueSection"), - backHomeBtn: document.getElementById("backHomeBtn"), + queueList: $("queueList"), + queueEmpty: $("queueEmpty"), + queueSummary: $("queueSummary"), + libraryList: $("libraryList"), + libraryEmpty: $("libraryEmpty"), + librarySearch: $("librarySearch"), + enqueueAllBtn: $("enqueueAllBtn"), + enqueueAllShuffledBtn: $("enqueueAllShuffledBtn"), + uploadSection: $("uploadSection"), + uploadForm: $("uploadForm"), + uploadSubmitBtn: document.querySelector("#uploadForm button[type='submit']"), + fileInput: $("musicFile"), + notesInput: $("uploadNotes"), + permanentCheckbox: $("permanentFile"), + enqueueCheckbox: $("enqueueFile"), + uploadList: $("uploadList"), + urlForm: $("urlForm"), + urlInput: $("musicUrl"), + urlSubmitBtn: document.querySelector("#urlForm button[type='submit']"), + heroUploadBtn: $("heroUploadBtn"), + heroQueueBtn: $("heroQueueBtn"), + queueSection: $("queueSection"), }; -let pollIntervalId = null; -let refreshPromise = null; - const { setStatus, clearStatus } = createStatusManager(elements.status); -const apiFetch = createApiClient({ - basePath: "/api", - getApiKey: () => state.apiKey, -}); -function refreshAll(options = {}) { - if (refreshPromise) { +// 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; } - - refreshPromise = performRefresh(options).finally(() => { - refreshPromise = null; + followUpRefresh ??= refreshPromise.then(() => { + followUpRefresh = null; + return refreshAll(); }); - return refreshPromise; + return followUpRefresh; } -async function performRefresh({ silent = false } = {}) { - if (!state.apiKey) { - stopPolling(); - setStatus("Renseigne le mot de passe pour accéder au jukebox", "info", false); - return; - } - - if (!silent) { - clearStatus(); - } - +async function performRefresh() { + if (!canUseApi()) return; try { const [queueData, libraryData] = await Promise.all([ apiFetch("/queue"), apiFetch("/library"), ]); - - state.current = queueData.current; - state.queue = queueData.upcoming || []; - state.library = libraryData.tracks || []; - state.status = queueData.status || "idle"; - - renderCurrentTrack(); - renderQueue(); - renderLibrary(); - updatePauseResumeButton(); + applySnapshot(queueData); + applyLibrary(libraryData.tracks || []); } catch (error) { - if (error.status === 401) { - // Inutile d'insister : chaque échec compte dans la limite anti-force brute du serveur. - stopPolling(); - setStatus("Mot de passe refusé, vérifie-le puis sauvegarde", "error", false); - return; - } - setStatus(`Erreur: ${error.message}`, "error", false); + handleApiError(error); } } +async function refreshLibrary() { + try { + const libraryData = await apiFetch("/library"); + applyLibrary(libraryData.tracks || []); + } 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) { + state.library = tracks; + renderLibrary(); +} + +// --------------------------------------------------------------------------- +// 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 + +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() { - if (!elements.currentTrack) return; - if (!state.current) { + const track = state.current; + if (!track) { elements.currentTrack.classList.add("player-current--empty"); - elements.currentTrack.innerHTML = "En attente de lecture..."; + 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"); - const track = state.current; - const permanence = track.permanent ? "Permanent" : "Temporaire"; elements.currentTrack.innerHTML = `
          ${escapeHtml(track.title || track.originalName)}
          -
          - ${permanence} • ${formatBytes(track.size)} • Ajouté par ${escapeHtml( - track.uploader || "inconnu" - )} -
          -
          Commencé à ${formatDate(track.createdAt)}
          +
          ${trackMeta(track)}
          +
          Commencé à ${formatDate(track.startedAt || track.createdAt)}
          `; } -function renderQueue() { - if (!elements.queueList) return; - elements.queueList.innerHTML = ""; +function currentPosition() { + const elapsed = + state.status === "playing" ? performance.now() - state.positionReceivedAt : 0; + return state.position + elapsed; +} - if (!state.queue || state.queue.length === 0) { - elements.queueEmpty.style.display = "block"; +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); +} - elements.queueEmpty.style.display = "none"; +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"; - const permanence = track.permanent ? "Permanent" : "Temporaire"; li.innerHTML = `
          -
          ${escapeHtml(track.title || track.originalName)}
          -
          - ${permanence} • ${formatBytes(track.size)} • Ajouté par ${escapeHtml( - track.uploader || "inconnu" - )} -
          +
          ${index + 1}. ${escapeHtml(track.title || track.originalName)}
          +
          ${trackMeta(track)}
          - - - + + +
          `; - - 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); - }); + li.querySelectorAll("button").forEach((button) => { + button.addEventListener("click", () => + handleQueueAction(button.dataset.action, track.id, index, button) + ); }); - elements.queueList.appendChild(li); }); } function renderLibrary() { - if (!elements.libraryList) return; - elements.libraryList.innerHTML = ""; + const query = elements.librarySearch.value.trim().toLowerCase(); + const tracks = state.library.filter((track) => + `${track.title || ""} ${track.originalName || ""} ${track.artist || ""}` + .toLowerCase() + .includes(query) + ); - if (!state.library || state.library.length === 0) { - elements.libraryEmpty.style.display = "block"; - return; - } + elements.libraryList.replaceChildren(); + elements.libraryEmpty.hidden = tracks.length > 0; + elements.libraryEmpty.textContent = + state.library.length === 0 + ? "Aucun fichier permanent enregistré." + : "Aucun morceau ne correspond à la recherche."; + elements.enqueueAllBtn.disabled = state.library.length === 0; + elements.enqueueAllShuffledBtn.disabled = state.library.length === 0; - elements.libraryEmpty.style.display = "none"; - - state.library.forEach((track) => { + tracks.forEach((track) => { const li = document.createElement("li"); li.className = "media-item media-item--library"; + const duration = formatDuration(track.duration); li.innerHTML = `
          -
          ${escapeHtml(track.originalName)}
          +
          ${escapeHtml(track.title || track.originalName)}
          - ${formatBytes(track.size)} • Ajouté le ${formatDate(track.createdAt)} + ${duration ? `${duration} • ` : ""}${formatBytes(track.size)} • Ajouté le ${formatDate(track.createdAt)}
          - - + + +
          `; - - li.querySelectorAll("button").forEach((btn) => { - btn.addEventListener("click", (event) => { - const action = event.currentTarget.dataset.libraryAction; - const libraryId = event.currentTarget.dataset.libraryId; - handleLibraryAction(action, libraryId); - }); + li.querySelectorAll("button").forEach((button) => { + button.addEventListener("click", () => + handleLibraryAction(button.dataset.action, track, button) + ); }); - - elements.libraryList.appendChild(li); + elements.libraryList.appendChild(li); }); } -function updatePauseResumeButton() { - if (!elements.pauseResumeBtn) return; - const normalizedStatus = - typeof state.status === "string" ? state.status.toLowerCase() : "idle"; - const isPaused = normalizedStatus === "paused"; - const isPlaying = normalizedStatus === "playing"; - - if (isPaused) { - elements.pauseResumeBtn.textContent = "Reprendre"; - elements.pauseResumeBtn.dataset.playerAction = "resume"; - } else { - elements.pauseResumeBtn.textContent = "Pause"; - elements.pauseResumeBtn.dataset.playerAction = "pause"; - } - - const actionable = isPaused || isPlaying; - elements.pauseResumeBtn.disabled = !actionable; +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"; } -async function handleQueueAction(action, trackId, index) { +function renderAuth() { + const loggedIn = Boolean(state.user); + elements.loggedIn.hidden = !loggedIn; + elements.discordLogin.hidden = loggedIn || !state.oauthEnabled; + elements.keyLogin.hidden = loggedIn; + 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 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 }, - }); + 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 refreshAll({ silent: true }); + await afterAction(); } catch (error) { - setStatus(`Impossible de mettre à jour la file: ${error.message}`, "error"); + setStatus(`Impossible de mettre à jour la file : ${error.message}`, "error"); } } -async function handleLibraryAction(action, libraryId) { +async function handleLibraryAction(action, track, button) { try { if (action === "enqueue") { - await apiFetch(`/library/${libraryId}/enqueue`, { - method: "POST", - body: { requestedBy: state.displayName || "web-ui" }, - }); + 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 === "rename") { + const title = prompt("Nouveau titre", track.title || track.originalName); + if (!title || !title.trim()) return; + await withBusyButton(button, () => + apiFetch(`/library/${track.id}`, { method: "PATCH", body: { title: title.trim() } }) + ); + if (!state.live) await refreshLibrary(); } else if (action === "delete") { - if (!confirm("Supprimer ce fichier permanent ?")) { + if (!confirm(`Supprimer « ${track.title || track.originalName} » de la bibliothèque ?`)) { return; } - await apiFetch(`/library/${libraryId}`, { method: "DELETE" }); + await withBusyButton(button, () => + apiFetch(`/library/${track.id}`, { method: "DELETE" }) + ); + if (!state.live) await refreshLibrary(); } - await refreshAll({ silent: true }); + await afterAction(); } catch (error) { - setStatus(`Action bibliothèque impossible: ${error.message}`, "error"); + setStatus(`Action bibliothèque impossible : ${error.message}`, "error"); } } -function startPolling() { - stopPolling(); - pollIntervalId = setInterval(() => refreshAll({ silent: true }), 5000); +async function enqueueAll(shuffle, button) { + try { + const { tracks } = await withBusyButton(button, () => + apiFetch("/library/enqueue-all", { + method: "POST", + body: { shuffle, requestedBy: requesterName() }, + }) + ); + setStatus(`${tracks.length} morceau(x) ajouté(s) à la file`, "success"); + await afterAction(); + } catch (error) { + setStatus(`Ajout impossible : ${error.message}`, "error"); + } } -function stopPolling() { - clearInterval(pollIntervalId); - pollIntervalId = null; +// Envoi avec XMLHttpRequest : contrairement à fetch, il indique la progression de l'envoi. +function uploadFile(file, { permanent, enqueue, 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); + + 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 = ` + + + En attente + `; + 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, + }; + 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, + 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) => { + elements.settingsForm.addEventListener("submit", (event) => { event.preventDefault(); state.apiKey = elements.apiKeyInput.value.trim(); state.displayName = elements.displayNameInput.value.trim(); - setStoredApiKey(state.apiKey); + setStoredApiKey(state.apiKey, { remember: elements.rememberKeyCheckbox.checked }); setStoredDisplayName(state.displayName); setStatus("Paramètres sauvegardés", "success"); - refreshAll({ silent: true }); - if (state.apiKey) { - startPolling(); - } + startSession(); }); - elements.uploadForm?.addEventListener("submit", async (event) => { - event.preventDefault(); - const file = elements.fileInput.files[0]; - if (!file) { - setStatus("Merci de sélectionner un fichier audio", "error"); - return; - } - - try { - const data = new FormData(); - data.append("file", file); - data.append("permanent", elements.permanentCheckbox.checked ? "true" : "false"); - data.append("enqueue", elements.enqueueCheckbox.checked ? "true" : "false"); - if (state.displayName) { - data.append("uploader", state.displayName); - } - if (elements.notesInput.value) { - data.append("notes", elements.notesInput.value.trim()); - } - - setStatus("Upload en cours...", "info", false); - await apiFetch("/uploads", { method: "POST", body: data }); - elements.uploadForm.reset(); - elements.enqueueCheckbox.checked = true; - setStatus("Fichier envoyé avec succès", "success"); - await refreshAll({ silent: true }); - } catch (error) { - setStatus(`Échec de l'upload: ${error.message}`, "error"); - } + elements.logoutBtn.addEventListener("click", async () => { + await fetch("/auth/logout", { method: "POST" }).catch(() => {}); + state.user = null; + stopEvents(); + renderAuth(); + startSession(); }); - elements.refreshBtn?.addEventListener("click", () => refreshAll()); - elements.heroUploadBtn?.addEventListener("click", () => - elements.uploadSection?.scrollIntoView({ behavior: "smooth" }) - ); - elements.heroQueueBtn?.addEventListener("click", () => - elements.queueSection?.scrollIntoView({ behavior: "smooth" }) - ); - elements.backHomeBtn?.addEventListener("click", () => { - window.location.href = "/"; - }); - - elements.playerButtons?.forEach((button) => { + elements.playerButtons.forEach((button) => { button.addEventListener("click", async () => { const action = button.dataset.playerAction; try { - await apiFetch(`/player/${action}`, { method: "POST" }); - await refreshAll({ silent: true }); + await withBusyButton(button, () => apiFetch(`/player/${action}`, { method: "POST" })); + await afterAction(); } catch (error) { - setStatus(`Action player impossible: ${error.message}`, "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.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(); + } + }); } -function initialize() { +async function initialize() { elements.apiKeyInput.value = state.apiKey; elements.displayNameInput.value = state.displayName; + elements.rememberKeyCheckbox.checked = isApiKeyRemembered(); bindEvents(); - updatePauseResumeButton(); - refreshAll(); - if (state.apiKey) { - startPolling(); - } + renderControls(); + setInterval(renderProgress, 1_000); + + await loadSession(); + renderAuth(); + startSession(); + showLoginError(); } initialize(); diff --git a/public/style/styles.css b/public/style/styles.css index 6a2e9d6..78990bd 100644 --- a/public/style/styles.css +++ b/public/style/styles.css @@ -19,6 +19,25 @@ box-sizing: border-box; } +[hidden] { + display: none !important; +} + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; +} + +code { + background: rgba(255, 255, 255, 0.08); + border-radius: 6px; + padding: 0.1rem 0.35rem; +} + body { margin: 0; min-height: 100vh; @@ -109,6 +128,7 @@ p { .hero__visual img { max-width: 200px; width: 100%; + height: auto; filter: drop-shadow(0 25px 45px rgba(0, 0, 0, 0.45)); } @@ -146,6 +166,11 @@ p { backdrop-filter: blur(18px); } +.panel--dragover { + border-color: var(--accent); + border-style: dashed; +} + .panel__subtitle { color: var(--muted); margin-top: 0.35rem; @@ -176,6 +201,9 @@ label { } input[type="text"], +input[type="password"], +input[type="url"], +input[type="search"], input[type="file"], select, textarea { @@ -254,6 +282,149 @@ select:focus { font-size: 0.9rem; } +a.btn { + display: inline-block; + text-decoration: none; + text-align: center; +} + +.btn--discord { + background: #5865f2; + color: #fff; +} + +.btn--discord:hover { + box-shadow: 0 10px 25px rgba(88, 101, 242, 0.4); +} + +.btn[aria-pressed="true"] { + background: linear-gradient(120deg, var(--accent), var(--accent-strong)); + color: #08010f; +} + +.btn:focus-visible { + outline: 2px solid #fff; + outline-offset: 2px; +} + +.toolbar { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; +} + +.key-login summary { + cursor: pointer; + color: var(--muted); + margin: 1rem 0 0.75rem; +} + +.live-indicator { + display: inline-flex; + align-items: center; + gap: 0.45rem; + font-size: 0.85rem; + color: var(--muted-dark); + white-space: nowrap; +} + +.live-indicator::before { + content: ""; + width: 0.55rem; + height: 0.55rem; + border-radius: 50%; + background: var(--muted-dark); +} + +.live-indicator[data-live="true"] { + color: var(--success); +} + +.live-indicator[data-live="true"]::before { + background: var(--success); + box-shadow: 0 0 0 4px rgba(89, 255, 167, 0.15); +} + +.progress { + margin-top: 0.9rem; +} + +.progress__track { + height: 6px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.1); + overflow: hidden; +} + +.progress__bar { + height: 100%; + width: 0; + background: linear-gradient(120deg, var(--accent), var(--accent-strong)); + transition: width 0.9s linear; +} + +.progress__times { + display: flex; + justify-content: space-between; + color: var(--muted); + font-size: 0.85rem; + margin-top: 0.35rem; + font-variant-numeric: tabular-nums; +} + +.upload-list { + margin-top: 1rem; +} + +.upload-list__item { + display: grid; + grid-template-columns: minmax(0, 1fr) 140px minmax(0, 1fr); + align-items: center; + gap: 0.75rem; + padding: 0.4rem 0; + font-size: 0.9rem; +} + +.upload-list__name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.upload-list__item progress { + width: 100%; + accent-color: var(--accent); +} + +.upload-list__state { + color: var(--muted); +} + +.upload-list__item[data-state="ok"] .upload-list__state { + color: var(--success); +} + +.upload-list__item[data-state="error"] .upload-list__state { + color: var(--danger); +} + +.url-form { + border-top: 1px solid var(--border); + padding-top: 1.25rem; + margin-top: 1.5rem; +} + +.url-form__row { + display: flex; + gap: 0.75rem; +} + +.hint { + color: var(--muted-dark); + font-size: 0.85rem; + margin: 0.5rem 0 0; +} + .control-group { display: flex; flex-wrap: wrap; @@ -412,4 +583,23 @@ select:focus { .control-group { flex-direction: column; } + + .url-form__row { + flex-direction: column; + } + + .upload-list__item { + grid-template-columns: 1fr; + gap: 0.25rem; + } + + .media-item { + flex-direction: column; + align-items: stretch; + } + + .media-item__actions .btn { + width: auto; + flex: 1; + } } diff --git a/src/commands/game/maketeam.js b/src/commands/game/maketeam.js index fb6c761..da24db7 100644 --- a/src/commands/game/maketeam.js +++ b/src/commands/game/maketeam.js @@ -1,34 +1,34 @@ -import { SlashCommandBuilder } from "discord.js"; - -const command = { - data: new SlashCommandBuilder() - .setName("maketeam") - .setDescription("Crée des equipes au hasard") - .addIntegerOption((option) => - option +import { MessageFlags, SlashCommandBuilder } from "discord.js"; + +const command = { + data: new SlashCommandBuilder() + .setName("maketeam") + .setDescription("Crée des equipes au hasard") + .addIntegerOption((option) => + option .setName("number") .setDescription("Nombre d'équipe") .setMinValue(1) .setMaxValue(20) .setRequired(true) - ) - .addStringOption((option) => - option + ) + .addStringOption((option) => + option .setName("players") .setDescription("Liste des joueurs, séparés par un espace") .setMinLength(1) .setMaxLength(1000) .setRequired(true) - ), - async execute(interaction) { - const teamNumber = interaction.options.getInteger("number"); - const players = interaction.options.getString("players"); + ), + async execute(interaction) { + const teamNumber = interaction.options.getInteger("number"); + const players = interaction.options.getString("players"); const playersArray = players.trim().split(/\s+/); if (teamNumber > playersArray.length) { await interaction.reply({ content: "Le nombre d'équipes ne peut pas dépasser le nombre de joueurs.", - ephemeral: true, + flags: MessageFlags.Ephemeral, }); return; } @@ -42,22 +42,22 @@ const command = { shuffledPlayers[index], ]; } - - shuffledPlayers.forEach((player, index) => { - const teamIndex = index % teamNumber; - teams[teamIndex].push(player); - }); - - let message = ""; - let teamList = ""; - - teams.forEach((team, index) => { - teamList = `${teamList}\n${index + 1}. ${team.join(", ")}`; - }); - - message = `Yop ! Voici les équipes proposés :\n${teamList}`; - await interaction.reply(message); - }, -}; - -export { command }; + + shuffledPlayers.forEach((player, index) => { + const teamIndex = index % teamNumber; + teams[teamIndex].push(player); + }); + + let message = ""; + let teamList = ""; + + teams.forEach((team, index) => { + teamList = `${teamList}\n${index + 1}. ${team.join(", ")}`; + }); + + message = `Yop ! Voici les équipes proposés :\n${teamList}`; + await interaction.reply(message); + }, +}; + +export { command }; diff --git a/src/commands/jukebox/play.js b/src/commands/jukebox/play.js new file mode 100644 index 0000000..aa45584 --- /dev/null +++ b/src/commands/jukebox/play.js @@ -0,0 +1,126 @@ +import { MessageFlags, SlashCommandBuilder, escapeMarkdown } from "discord.js"; +import { downloadAudio } from "../../media/downloadAudio.js"; +import { ingestAudioFile } from "../../music/ingest.js"; +import { trackLabel } from "../../features/formatTrack.js"; +import { + TEMP_DIR, + createQueueTrackFromLibrary, + findPermanentTrack, + getPermanentLibrary, +} from "../../web/storage/storageManager.js"; + +const MAX_ATTACHMENT_SIZE = 150 * 1024 * 1024; + +function positionMessage(queue, track) { + if (queue.currentTrack?.id === track.id) { + return "c'est parti ! 🎶"; + } + const index = queue.queue.findIndex((queued) => queued.id === track.id); + return index >= 0 ? `position ${index + 1} dans la file.` : "ajouté à la file."; +} + +const command = { + data: new SlashCommandBuilder() + .setName("play") + .setDescription("Ajoute un morceau à la file du jukebox") + .addAttachmentOption((option) => + option.setName("fichier").setDescription("Fichier audio à jouer") + ) + .addStringOption((option) => + option + .setName("lien") + .setDescription("Lien direct vers un fichier audio (pas YouTube ni Spotify)") + .setMaxLength(2000) + ) + .addStringOption((option) => + option + .setName("morceau") + .setDescription("Morceau de la bibliothèque") + .setAutocomplete(true) + ) + .addBooleanOption((option) => + option + .setName("garder") + .setDescription("Garder le fichier ou le lien dans la bibliothèque") + ), + + async autocomplete(interaction) { + const query = interaction.options.getFocused().toLowerCase(); + const choices = getPermanentLibrary() + .filter((entry) => + `${entry.title || ""} ${entry.originalName || ""}`.toLowerCase().includes(query) + ) + .slice(0, 25) + .map((entry) => ({ name: trackLabel(entry).slice(0, 100), value: entry.id })); + await interaction.respond(choices); + }, + + async execute(interaction) { + const queue = interaction.client.musicQueue; + const attachment = interaction.options.getAttachment("fichier"); + const link = interaction.options.getString("lien"); + const libraryId = interaction.options.getString("morceau"); + const keep = interaction.options.getBoolean("garder") ?? false; + const sources = [attachment, link, libraryId].filter(Boolean); + + if (sources.length !== 1) { + await interaction.reply({ + content: "Choisis une seule source : `fichier`, `lien` ou `morceau`.", + flags: MessageFlags.Ephemeral, + }); + return; + } + + const uploader = interaction.member?.displayName || interaction.user.username; + + if (libraryId) { + const entry = findPermanentTrack(libraryId); + if (!entry) { + await interaction.reply({ + content: "Morceau introuvable dans la bibliothèque.", + flags: MessageFlags.Ephemeral, + }); + return; + } + const track = queue.enqueue(createQueueTrackFromLibrary(entry, uploader)); + await interaction.reply( + `**${escapeMarkdown(trackLabel(track))}** : ${positionMessage(queue, track)}` + ); + return; + } + + if (attachment && attachment.size > MAX_ATTACHMENT_SIZE) { + await interaction.reply({ + content: "Fichier trop volumineux (150 Mo au plus).", + flags: MessageFlags.Ephemeral, + }); + return; + } + + await interaction.deferReply(); + try { + const file = await downloadAudio(attachment?.url ?? link, { destinationDir: TEMP_DIR }); + if (attachment?.name) { + file.originalname = attachment.name; + } + const track = await ingestAudioFile( + file, + { permanent: keep, enqueue: true, uploader }, + { queue } + ); + await interaction.editReply( + `**${escapeMarkdown(trackLabel(track))}** : ${positionMessage(queue, track)}` + ); + } catch (error) { + if (!error.status) throw error; + // Erreur attendue (lien invalide, fichier non audio…) : on l'explique sans la publier. + await interaction.deleteReply().catch(() => {}); + await interaction.followUp({ + content: `Impossible d'ajouter ce morceau : ${error.message}`, + flags: MessageFlags.Ephemeral, + }); + } + }, +}; + +export { command }; diff --git a/src/commands/jukebox/queue.js b/src/commands/jukebox/queue.js new file mode 100644 index 0000000..17f9511 --- /dev/null +++ b/src/commands/jukebox/queue.js @@ -0,0 +1,41 @@ +import { MessageFlags, SlashCommandBuilder, escapeMarkdown } from "discord.js"; +import { trackLabel } from "../../features/formatTrack.js"; + +const SHOWN_TRACKS = 10; + +function buildQueueMessage(queue) { + const lines = []; + lines.push( + queue.currentTrack + ? `🎶 En cours : **${escapeMarkdown(trackLabel(queue.currentTrack))}**` + : "🎶 Rien en cours de lecture." + ); + + if (queue.queue.length === 0) { + lines.push("La file est vide. Ajoute un morceau avec `/play`."); + } else { + lines.push("", "__À suivre__ :"); + queue.queue.slice(0, SHOWN_TRACKS).forEach((track, index) => { + lines.push(`${index + 1}. ${escapeMarkdown(trackLabel(track))}`); + }); + const hidden = queue.queue.length - SHOWN_TRACKS; + if (hidden > 0) { + lines.push(`… et ${hidden} autre(s).`); + } + } + return lines.join("\n"); +} + +const command = { + data: new SlashCommandBuilder() + .setName("queue") + .setDescription("Affiche la file d'attente du jukebox"), + async execute(interaction) { + await interaction.reply({ + content: buildQueueMessage(interaction.client.musicQueue), + flags: MessageFlags.Ephemeral, + }); + }, +}; + +export { buildQueueMessage, command }; diff --git a/src/commands/jukebox/skip.js b/src/commands/jukebox/skip.js new file mode 100644 index 0000000..9d088c2 --- /dev/null +++ b/src/commands/jukebox/skip.js @@ -0,0 +1,24 @@ +import { MessageFlags, SlashCommandBuilder, escapeMarkdown } from "discord.js"; +import { trackLabel } from "../../features/formatTrack.js"; + +const command = { + data: new SlashCommandBuilder() + .setName("skip") + .setDescription("Passe au morceau suivant du jukebox"), + async execute(interaction) { + const queue = interaction.client.musicQueue; + const current = queue.currentTrack; + if (!current) { + await interaction.reply({ + content: "Rien n'est en cours de lecture.", + flags: MessageFlags.Ephemeral, + }); + return; + } + + queue.skip(); + await interaction.reply(`⏭️ **${escapeMarkdown(trackLabel(current))}** passé.`); + }, +}; + +export { command }; diff --git a/src/commands/utility/deletemsgs.js b/src/commands/utility/deletemsgs.js index dc7a194..ab527c7 100644 --- a/src/commands/utility/deletemsgs.js +++ b/src/commands/utility/deletemsgs.js @@ -1,8 +1,8 @@ -import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { requirePermission } from "../../features/permissions.js"; - -const command = { - data: new SlashCommandBuilder() + +const command = { + data: new SlashCommandBuilder() .setName("deletemsgs") .setDescription("Supprime tous les messages, sauf ceux épinglés") .setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages), @@ -15,12 +15,12 @@ const command = { if (!textChannel?.isTextBased() || !textChannel.messages) { await interaction.reply({ content: "Cette commande doit être utilisée dans un salon textuel.", - ephemeral: true, + flags: MessageFlags.Ephemeral, }); return; } - await interaction.deferReply({ ephemeral: true }); + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const fetched = await textChannel.messages.fetch({ limit: 100 }); const notPinned = fetched.filter((message) => !message.pinned); const deleted = await textChannel.bulkDelete(notPinned, true); @@ -28,5 +28,5 @@ const command = { await interaction.editReply(`Et voilà, ${deleted.size} message(s) supprimé(s) ! 🐱`); }, }; - -export { command }; + +export { command }; diff --git a/src/commands/utility/invitation.js b/src/commands/utility/invitation.js index 649f2ae..0f6758d 100644 --- a/src/commands/utility/invitation.js +++ b/src/commands/utility/invitation.js @@ -1,4 +1,4 @@ -import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { config } from "../../config.js"; import { requirePermission } from "../../features/permissions.js"; import { @@ -40,7 +40,7 @@ const command = { if (!interaction.guild || !channel?.isTextBased()) { await interaction.reply({ content: "Cette commande doit être utilisée dans un salon textuel du serveur.", - ephemeral: true, + flags: MessageFlags.Ephemeral, }); return; } @@ -49,12 +49,12 @@ const command = { if (!input) { await interaction.reply({ content: "Aucun lien : passe l'option `lien` ou définis `INVITE_LINK`.", - ephemeral: true, + flags: MessageFlags.Ephemeral, }); return; } - await interaction.deferReply({ ephemeral: true }); + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); if (!botCanPost(interaction)) { await interaction.editReply(NO_ACCESS_MESSAGE); diff --git a/src/commands/utility/listcommand.js b/src/commands/utility/listcommand.js index ea192b3..3d3460b 100644 --- a/src/commands/utility/listcommand.js +++ b/src/commands/utility/listcommand.js @@ -1,28 +1,33 @@ -import { SlashCommandBuilder } from "discord.js"; - -const command = { - data: new SlashCommandBuilder() - .setName("listcommand") - .setDescription("Affiche la liste des commandes disponibles"), - async execute(interaction) { - let message = `Voila la liste des commandes que tu peux utiliser : - __Categorie Utililaires__ : - \`/deletemsgs\`: Supprime les 100 derniers messages non épinglés - \`/invitation\`: Publie le message d'invitation temporaire (lien vérifié) - - __Categorie Vocal__ : - \`/muteall\`: Rends tout le monde muet - \`/unmuteall\`: Rends la parole à tout le monde - \`/deafall\`: Rends tout le monde sourd - \`/undeafall\`: Rends l'ouïe à tout le monde - - __Categorie Jeux__ : - \`/dice\`: Lance un ou plusieurs dés avec un nombre de faces choisi - \`/maketeam\`: Crée un certain nombre d'équipes en renseignant des joueurs (séparés par un espace) - `; - - await interaction.reply({ content: message, ephemeral: true }); - }, -}; - -export { command }; +import { MessageFlags, SlashCommandBuilder } from "discord.js"; + +const command = { + data: new SlashCommandBuilder() + .setName("listcommand") + .setDescription("Affiche la liste des commandes disponibles"), + async execute(interaction) { + let message = `Voila la liste des commandes que tu peux utiliser : + __Categorie Utililaires__ : + \`/deletemsgs\`: Supprime les 100 derniers messages non épinglés + \`/invitation\`: Publie le message d'invitation temporaire (lien vérifié) + + __Categorie Jukebox__ : + \`/play\`: Ajoute un morceau (fichier, lien direct ou morceau de la bibliothèque) + \`/skip\`: Passe au morceau suivant + \`/queue\`: Affiche la file d'attente + + __Categorie Vocal__ : + \`/muteall\`: Rends tout le monde muet + \`/unmuteall\`: Rends la parole à tout le monde + \`/deafall\`: Rends tout le monde sourd + \`/undeafall\`: Rends l'ouïe à tout le monde + + __Categorie Jeux__ : + \`/dice\`: Lance un ou plusieurs dés avec un nombre de faces choisi + \`/maketeam\`: Crée un certain nombre d'équipes en renseignant des joueurs (séparés par un espace) + `; + + await interaction.reply({ content: message, flags: MessageFlags.Ephemeral }); + }, +}; + +export { command }; diff --git a/src/commands/utility/ping.js b/src/commands/utility/ping.js index 46190ad..95ea08c 100644 --- a/src/commands/utility/ping.js +++ b/src/commands/utility/ping.js @@ -1,12 +1,12 @@ -import { SlashCommandBuilder } from "discord.js"; - -const command = { +import { MessageFlags, SlashCommandBuilder } from "discord.js"; + +const command = { data: new SlashCommandBuilder() - .setName("ping") - .setDescription("Reponds avec Pong"), + .setName("ping") + .setDescription("Reponds avec Pong"), async execute(interaction) { - await interaction.reply({ content: "Euh... Pong ! 🐱", ephemeral: true }); - }, -}; - -export { command }; + await interaction.reply({ content: "Euh... Pong ! 🐱", flags: MessageFlags.Ephemeral }); + }, +}; + +export { command }; diff --git a/src/commands/vocal/deafall.js b/src/commands/vocal/deafall.js index 9ec7ec5..9f7247a 100644 --- a/src/commands/vocal/deafall.js +++ b/src/commands/vocal/deafall.js @@ -1,17 +1,19 @@ import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { changeVoiceStatus } from "../../features/utilities.js"; import { requirePermission } from "../../features/permissions.js"; - -const command = { - data: new SlashCommandBuilder() + +const command = { + data: new SlashCommandBuilder() .setName("deafall") .setDescription("Deaf tout le monde dans le lounge") .setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers), async execute(interaction) { if (!(await requirePermission(interaction, PermissionFlagsBits.DeafenMembers))) return; + // Changer l'état de chaque membre peut dépasser les 3 s qu'accorde Discord pour répondre. + await interaction.deferReply(); await changeVoiceStatus(interaction.client, "deaf", "all"); - await interaction.reply("On n'entends plus rien ! 🐱"); - }, -}; - -export { command }; + await interaction.editReply("On n'entends plus rien ! 🐱"); + }, +}; + +export { command }; diff --git a/src/commands/vocal/muteall.js b/src/commands/vocal/muteall.js index 86f5dda..945c647 100644 --- a/src/commands/vocal/muteall.js +++ b/src/commands/vocal/muteall.js @@ -1,17 +1,19 @@ import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { changeVoiceStatus } from "../../features/utilities.js"; import { requirePermission } from "../../features/permissions.js"; - -const command = { - data: new SlashCommandBuilder() + +const command = { + data: new SlashCommandBuilder() .setName("muteall") .setDescription("Mute tout le monde dans le lounge") .setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers), async execute(interaction) { if (!(await requirePermission(interaction, PermissionFlagsBits.MuteMembers))) return; + // Changer l'état de chaque membre peut dépasser les 3 s qu'accorde Discord pour répondre. + await interaction.deferReply(); await changeVoiceStatus(interaction.client, "mute", "all"); - await interaction.reply("Voila, tout le monde est mioute ! 🐱"); - }, -}; - -export { command }; + await interaction.editReply("Voila, tout le monde est mioute ! 🐱"); + }, +}; + +export { command }; diff --git a/src/commands/vocal/undeafall.js b/src/commands/vocal/undeafall.js index 878b82d..e081208 100644 --- a/src/commands/vocal/undeafall.js +++ b/src/commands/vocal/undeafall.js @@ -1,17 +1,19 @@ import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { changeVoiceStatus } from "../../features/utilities.js"; import { requirePermission } from "../../features/permissions.js"; - -const command = { - data: new SlashCommandBuilder() + +const command = { + data: new SlashCommandBuilder() .setName("undeafall") .setDescription("Undeaf tout le monde dans le lounge") .setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers), async execute(interaction) { if (!(await requirePermission(interaction, PermissionFlagsBits.DeafenMembers))) return; + // Changer l'état de chaque membre peut dépasser les 3 s qu'accorde Discord pour répondre. + await interaction.deferReply(); await changeVoiceStatus(interaction.client, "undeaf", "all"); - await interaction.reply("Voila, les oreilles sont réparées ! 🐱"); - }, -}; - -export { command }; + await interaction.editReply("Voila, les oreilles sont réparées ! 🐱"); + }, +}; + +export { command }; diff --git a/src/commands/vocal/unmuteall.js b/src/commands/vocal/unmuteall.js index cb83668..1f7fa69 100644 --- a/src/commands/vocal/unmuteall.js +++ b/src/commands/vocal/unmuteall.js @@ -1,17 +1,19 @@ import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { changeVoiceStatus } from "../../features/utilities.js"; import { requirePermission } from "../../features/permissions.js"; - -const command = { - data: new SlashCommandBuilder() + +const command = { + data: new SlashCommandBuilder() .setName("unmuteall") .setDescription("Unmute tout le monde dans le lounge") .setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers), async execute(interaction) { if (!(await requirePermission(interaction, PermissionFlagsBits.MuteMembers))) return; + // Changer l'état de chaque membre peut dépasser les 3 s qu'accorde Discord pour répondre. + await interaction.deferReply(); await changeVoiceStatus(interaction.client, "unmute", "all"); - await interaction.reply("Et.... unmioute ! 🐱"); - }, -}; - -export { command }; + await interaction.editReply("Et.... unmioute ! 🐱"); + }, +}; + +export { command }; diff --git a/src/config.js b/src/config.js index 0afe09d..a31100f 100644 --- a/src/config.js +++ b/src/config.js @@ -41,6 +41,36 @@ const notificationsApiKey = process.env.NOTIFICATIONS_API_KEY?.trim() || null; // INVITE_LINK : lien publié par /invitation quand la commande ne reçoit pas de lien. const inviteLink = process.env.INVITE_LINK?.trim() || null; +// Connexion avec Discord sur la page web (facultative, active si les trois sont définies) : +// DISCORD_CLIENT_SECRET (portail développeur, OAuth2), WEB_PUBLIC_URL (adresse publique du +// site, sans / final) et SESSION_SECRET (32 caractères au moins, signe les sessions). +const discordClientSecret = process.env.DISCORD_CLIENT_SECRET?.trim() || null; +const webPublicUrl = process.env.WEB_PUBLIC_URL?.trim().replace(/\/+$/, "") || null; +const sessionSecret = process.env.SESSION_SECRET?.trim() || null; +const discordOAuthEnabled = Boolean(discordClientSecret && webPublicUrl && sessionSecret); + +const oauthVariablesSet = [discordClientSecret, webPublicUrl, sessionSecret].filter(Boolean).length; +if (oauthVariablesSet > 0 && !discordOAuthEnabled) { + console.warn( + "Connexion avec Discord désactivée : DISCORD_CLIENT_SECRET, WEB_PUBLIC_URL et SESSION_SECRET doivent toutes être définies" + ); +} + +if (discordOAuthEnabled) { + let publicUrl; + try { + publicUrl = new URL(webPublicUrl); + } catch { + throw new Error("WEB_PUBLIC_URL doit être une adresse complète (https://…)"); + } + if (publicUrl.protocol !== "https:" && publicUrl.hostname !== "localhost") { + throw new Error("WEB_PUBLIC_URL doit être en https"); + } + if (sessionSecret.length < 32) { + throw new Error("SESSION_SECRET doit contenir au moins 32 caractères"); + } +} + if (notificationsApiKey && notificationsApiKey === process.env.WEB_API_KEY) { throw new Error("NOTIFICATIONS_API_KEY doit être différente de WEB_API_KEY"); } @@ -54,6 +84,10 @@ const config = Object.freeze({ webTrustedProxies, notificationsApiKey, inviteLink, + discordOAuthEnabled, + discordClientSecret, + webPublicUrl, + sessionSecret, applicationId: process.env.DISCORD_APPLICATION_ID, token: process.env.DISCORD_TOKEN, voiceChannelId: process.env.VOICE_CHANNEL_ID, diff --git a/src/events/interactionCreate.js b/src/events/interactionCreate.js index 435e7a1..02ea72d 100644 --- a/src/events/interactionCreate.js +++ b/src/events/interactionCreate.js @@ -1,36 +1,48 @@ -import { Events } from "discord.js"; - -const event = { - name: Events.InteractionCreate, - async execute(interaction) { - if (!interaction.isChatInputCommand()) return; - +import { Events, MessageFlags } from "discord.js"; + +const ERROR_MESSAGE = "Oups, une erreur est survenue pendant la commande 😿"; + +const event = { + name: Events.InteractionCreate, + async execute(interaction) { + if (interaction.isAutocomplete()) { + const command = interaction.client.commands.get(interaction.commandName)?.command; + try { + await command?.autocomplete?.(interaction); + } catch (error) { + console.error(`Autocomplete failed for ${interaction.commandName}`, error); + } + return; + } + + if (!interaction.isChatInputCommand()) return; + const command = interaction.client.commands.get(interaction.commandName)?.command; - - if (!command) { - console.error( - `No command matching ${interaction.commandName} was found.` - ); - return; - } - - try { - await command.execute(interaction); - } catch (error) { - console.error(error); - if (interaction.replied || interaction.deferred) { - await interaction.followUp({ - content: "There was an error while executing this command!", - ephemeral: true, - }); - } else { - await interaction.reply({ - content: "There was an error while executing this command!", - ephemeral: true, - }); - } - } - }, -}; - -export { event }; + + if (!command) { + console.error( + `No command matching ${interaction.commandName} was found.` + ); + return; + } + + try { + await command.execute(interaction); + } catch (error) { + console.error(`Command ${interaction.commandName} failed`, error); + // Le message d'erreur peut lui-même échouer (interaction expirée) : on le journalise + // au lieu de laisser une promesse rejetée sans gestionnaire. + try { + if (interaction.replied || interaction.deferred) { + await interaction.followUp({ content: ERROR_MESSAGE, flags: MessageFlags.Ephemeral }); + } else { + await interaction.reply({ content: ERROR_MESSAGE, flags: MessageFlags.Ephemeral }); + } + } catch (replyError) { + console.error("Unable to report the command error to the user", replyError); + } + } + }, +}; + +export { event }; diff --git a/src/events/ready.js b/src/events/ready.js index d45a1df..61295df 100644 --- a/src/events/ready.js +++ b/src/events/ready.js @@ -1,14 +1,17 @@ import { Events } from "discord.js"; import { showGameServers } from "../features/showGameServers.js"; - -const event = { - name: Events.ClientReady, - once: true, + +const event = { + name: Events.ClientReady, + once: true, async execute(client) { - console.log( - `[${new Date().toLocaleString()}] Logged in as ${client.user.tag}` - ); - + console.log( + `[${new Date().toLocaleString()}] Logged in as ${client.user.tag}` + ); + + // File rechargée au démarrage : reprendre si quelqu'un est déjà dans le salon vocal. + client.musicQueue?.evaluateAloneStatus(); + try { await showGameServers(client); } catch (error) { @@ -16,5 +19,5 @@ const event = { } }, }; - -export { event }; + +export { event }; diff --git a/src/features/formatTrack.js b/src/features/formatTrack.js new file mode 100644 index 0000000..64ff866 --- /dev/null +++ b/src/features/formatTrack.js @@ -0,0 +1,17 @@ +// Durée lisible : 3:07, 1:05:09. +function formatDuration(seconds) { + if (!Number.isFinite(seconds) || seconds < 0) return null; + const total = Math.round(seconds); + const hours = Math.floor(total / 3600); + const minutes = Math.floor((total % 3600) / 60); + const secs = String(total % 60).padStart(2, "0"); + return hours > 0 ? `${hours}:${String(minutes).padStart(2, "0")}:${secs}` : `${minutes}:${secs}`; +} + +function trackLabel(track) { + const title = track.title || track.originalName || "Sans titre"; + const duration = formatDuration(track.duration); + return duration ? `${title} (${duration})` : title; +} + +export { formatDuration, trackLabel }; diff --git a/src/features/permissions.js b/src/features/permissions.js index 268ad95..ecdd252 100644 --- a/src/features/permissions.js +++ b/src/features/permissions.js @@ -1,3 +1,5 @@ +import { MessageFlags } from "discord.js"; + async function requirePermission(interaction, permission) { if (interaction.memberPermissions?.has(permission)) { return true; @@ -5,7 +7,7 @@ async function requirePermission(interaction, permission) { await interaction.reply({ content: "Tu n'as pas la permission d'utiliser cette commande.", - ephemeral: true, + flags: MessageFlags.Ephemeral, }); return false; } diff --git a/src/features/showGameServers.js b/src/features/showGameServers.js index f037f00..14772c2 100644 --- a/src/features/showGameServers.js +++ b/src/features/showGameServers.js @@ -1,38 +1,82 @@ +import net from "node:net"; import { config } from "../config.js"; -import { getJSONData } from "./utilities.js"; - -var currentStatus = []; - +import { getJSONData } from "./utilities.js"; + +const PROBE_TIMEOUT = 3_000; +const REFRESH_INTERVAL = 120_000; + +var currentStatus = []; + +// Essaie d'ouvrir une connexion TCP : vrai si le port répond dans le délai. +function probeTcp(host, port, { timeout = PROBE_TIMEOUT, connect = net.connect } = {}) { + return new Promise((resolve) => { + const socket = connect({ host, port }); + const finish = (online) => { + socket.destroy(); + resolve(online); + }; + socket.setTimeout(timeout, () => finish(false)); + socket.once("connect", () => finish(true)); + socket.once("error", () => finish(false)); + }); +} + +// État d'un serveur : sondé si "check" vaut true (TCP sur "checkPort", sinon "port", à l'hôte +// de "address"), sinon le champ "active" saisi à la main. Un jeu dont le port de jeu est en +// UDP peut être sondé sur un port TCP annexe (RCON, requête…) avec "checkPort". +async function serverStatus(server, probe = probeTcp) { + if (server.check !== true) { + return Boolean(server.active); + } + const host = server.checkHost || String(server.address || "").replace(/:\d+$/, ""); + const port = Number(server.checkPort ?? server.port); + if (!host || !Number.isInteger(port) || port <= 0 || port > 65_535) { + return false; + } + return probe(host, port); +} + +async function readServers(probe) { + const data = getJSONData("src/static/gameservers-list.json"); + const servers = await Promise.all( + data.servers.map(async (server) => ({ + ...server, + active: await serverStatus(server, probe), + })) + ); + return { ...data, servers }; +} + async function checkServersStatus(client) { - const data = getJSONData("src/static/gameservers-list.json"); - const newStatus = data.servers.map((server) => server.active); - - if (JSON.stringify(newStatus) === JSON.stringify(currentStatus)) { - return; - } - + const data = await readServers(); + const newStatus = data.servers.map((server) => server.active); + + if (JSON.stringify(newStatus) === JSON.stringify(currentStatus)) { + return; + } + await updateMessage(client, data); - currentStatus = newStatus; - return true; -} - + currentStatus = newStatus; + return true; +} + async function updateMessage(client, data) { - var newMessage = `Hello 😺 ! Voila les serveurs de jeux qu'on a chez nous :\n\n`; - - data.servers.forEach((server) => { - newMessage = - newMessage + - "```ansi\n" + - `${server.game} : ` + - `${server.active ? "Online" : "Offline"}\n` + - `${server.address}\n` + - "```"; - }); - + var newMessage = `Hello 😺 ! Voila les serveurs de jeux qu'on a chez nous :\n\n`; + + data.servers.forEach((server) => { + newMessage = + newMessage + + "```ansi\n" + + `${server.game} : ` + + `${server.active ? "[2;32mOnline[0m" : "[2;31mOffline[0m"}\n` + + `${server.address}\n` + + "```"; + }); + newMessage = - newMessage + - `\nPour mettre en ligne un serveur, faut voir avec <@${config.shinuwaUserId}> , c'est lui qui gère ca !\n`; - + newMessage + + `\nPour mettre en ligne un serveur, faut voir avec <@${config.shinuwaUserId}> , c'est lui qui gère ca !\n`; + const channel = client.channels.cache.get(config.textChannelId); if (!channel?.isTextBased()) { throw new Error("Salon textuel configuré introuvable"); @@ -46,16 +90,16 @@ async function updateMessage(client, data) { } async function showGameServers(client) { - const data = getJSONData("src/static/gameservers-list.json"); - currentStatus = data.servers.map((server) => server.active); - + const data = await readServers(); + currentStatus = data.servers.map((server) => server.active); + await updateMessage(client, data); const interval = setInterval(() => { checkServersStatus(client).catch((error) => console.error("Unable to update game server status", error) ); - }, 120000); + }, REFRESH_INTERVAL); interval.unref(); -} - -export { showGameServers }; +} + +export { probeTcp, serverStatus, showGameServers }; diff --git a/src/features/utilities.js b/src/features/utilities.js index 9bd332d..ce22090 100644 --- a/src/features/utilities.js +++ b/src/features/utilities.js @@ -1,6 +1,6 @@ -import fs from "fs"; +import fs from "fs"; import { config } from "../config.js"; - + async function changeVoiceStatus(client, status, members) { const changeStatus = async (type, value, selectedMembers) => { const operations = []; @@ -16,7 +16,15 @@ async function changeVoiceStatus(client, status, members) { } break; } - await Promise.all(operations); + // Un membre qui quitte le salon pendant l'opération ne doit pas faire échouer les autres. + const results = await Promise.allSettled(operations); + const failures = results.filter((result) => result.status === "rejected"); + if (failures.length > 0) { + console.error( + `changeVoiceStatus: ${failures.length} member(s) could not be updated`, + failures[0].reason + ); + } }; const voiceChannel = client.channels.cache.get(config.voiceChannelId); @@ -48,18 +56,18 @@ async function changeVoiceStatus(client, status, members) { throw new Error(`Statut vocal inconnu : ${status}`); } } - -function getJSONData(file) { - const jsonFile = fs.readFileSync(file); - const data = JSON.parse(jsonFile); - - return data; -} - -function getRandomInt(max) { - return Math.floor(Math.random() * max); -} - + +function getJSONData(file) { + const jsonFile = fs.readFileSync(file); + const data = JSON.parse(jsonFile); + + return data; +} + +function getRandomInt(max) { + return Math.floor(Math.random() * max); +} + export { changeVoiceStatus, getJSONData, diff --git a/src/media/downloadAudio.js b/src/media/downloadAudio.js new file mode 100644 index 0000000..d96d30d --- /dev/null +++ b/src/media/downloadAudio.js @@ -0,0 +1,197 @@ +import dns from "node:dns"; +import fs from "node:fs"; +import http from "node:http"; +import https from "node:https"; +import net from "node:net"; +import path from "node:path"; +import { randomUUID } from "node:crypto"; +import { pipeline } from "node:stream/promises"; + +const MAX_DOWNLOAD_SIZE = 150 * 1024 * 1024; +const MAX_REDIRECTS = 5; +const SOCKET_TIMEOUT = 30_000; +const TOTAL_TIMEOUT = 5 * 60_000; + +// Adresses jamais contactées : le bot tourne sur un réseau qui héberge d'autres services, et +// l'URL vient d'un utilisateur (protection contre la falsification de requêtes côté serveur). +const blockedAddresses = new net.BlockList(); +for (const [network, prefix] of [ + ["0.0.0.0", 8], + ["10.0.0.0", 8], + ["100.64.0.0", 10], + ["127.0.0.0", 8], + ["169.254.0.0", 16], + ["172.16.0.0", 12], + ["192.0.0.0", 24], + ["192.168.0.0", 16], + ["198.18.0.0", 15], + ["224.0.0.0", 4], + ["240.0.0.0", 4], +]) { + blockedAddresses.addSubnet(network, prefix, "ipv4"); +} +for (const [network, prefix] of [ + ["::", 128], + ["::1", 128], + ["fc00::", 7], + ["fe80::", 10], + ["ff00::", 8], + ["64:ff9b::", 96], + ["2002::", 16], +]) { + blockedAddresses.addSubnet(network, prefix, "ipv6"); +} + +function downloadError(message, status = 400) { + const error = new Error(message); + error.status = status; + return error; +} + +function isBlockedAddress(address) { + const family = net.isIP(address); + if (family === 0) return true; + if (family === 6) { + // Adresse IPv4 écrite en IPv6 (::ffff:10.0.0.1) : on vérifie la partie IPv4. + const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address); + if (mapped) return blockedAddresses.check(mapped[1], "ipv4"); + return blockedAddresses.check(address, "ipv6"); + } + return blockedAddresses.check(address, "ipv4"); +} + +// Résolution DNS qui refuse les adresses internes. Elle est appelée par la connexion elle-même : +// l'adresse vérifiée est celle qu'on contacte (pas de changement entre vérification et usage). +function safeLookup(hostname, options, callback) { + dns.lookup(hostname, { ...options, all: true }, (error, addresses) => { + if (error) return callback(error); + const allowed = addresses.filter(({ address }) => !isBlockedAddress(address)); + if (allowed.length === 0) { + return callback(downloadError("Adresse non autorisée")); + } + if (options.all) return callback(null, allowed); + return callback(null, allowed[0].address, allowed[0].family); + }); +} + +function parseUrl(value) { + let url; + try { + url = new URL(value); + } catch { + throw downloadError("Lien invalide"); + } + if (url.protocol !== "https:" && url.protocol !== "http:") { + throw downloadError("Seuls les liens http et https sont acceptés"); + } + if (url.username || url.password) { + throw downloadError("Les liens avec identifiants ne sont pas acceptés"); + } + // Les adresses IP écrites en clair ne passent pas par la résolution DNS : on les vérifie ici. + const hostname = url.hostname.replace(/^\[|\]$/g, ""); + if (net.isIP(hostname) && isBlockedAddress(hostname)) { + throw downloadError("Adresse non autorisée"); + } + return url; +} + +function fileNameFrom(response, url) { + const disposition = response.headers["content-disposition"] || ""; + const encoded = /filename\*=UTF-8''([^;]+)/i.exec(disposition)?.[1]; + const plain = /filename="?([^";]+)"?/i.exec(disposition)?.[1]; + let name = encoded || plain || path.posix.basename(url.pathname); + try { + name = decodeURIComponent(name); + } catch { + // Nom laissé tel quel. + } + name = path.basename(name).replace(/[\u0000-\u001f]/g, "").trim().slice(0, 255); + return name || "audio"; +} + +function request(url, { signal, lookup }) { + const client = url.protocol === "https:" ? https : http; + return new Promise((resolve, reject) => { + const req = client.get( + url, + { + lookup, + signal, + timeout: SOCKET_TIMEOUT, + headers: { "user-agent": "palico-bot", accept: "audio/*, */*;q=0.5" }, + }, + resolve + ); + req.on("timeout", () => req.destroy(downloadError("Le serveur distant ne répond pas", 504))); + req.on("error", reject); + }); +} + +// Télécharge un fichier dans destinationDir et renvoie un objet de la même forme qu'un fichier +// reçu par multer ({ path, originalname, size, mimetype }). +async function downloadAudio( + value, + { destinationDir, maxSize = MAX_DOWNLOAD_SIZE, lookup = safeLookup } = {} +) { + let url = parseUrl(value); + const signal = AbortSignal.timeout(TOTAL_TIMEOUT); + + for (let redirects = 0; ; redirects++) { + let response; + try { + response = await request(url, { signal, lookup }); + } catch (error) { + if (error.status) throw error; + throw downloadError(`Téléchargement impossible : ${error.message}`, 502); + } + + const status = response.statusCode; + if (status >= 300 && status < 400 && response.headers.location) { + response.resume(); + if (redirects >= MAX_REDIRECTS) { + throw downloadError("Trop de redirections", 502); + } + url = parseUrl(new URL(response.headers.location, url).href); + continue; + } + + if (status !== 200) { + response.resume(); + throw downloadError(`Le serveur distant a répondu ${status}`, 502); + } + + const announced = Number(response.headers["content-length"]); + if (Number.isFinite(announced) && announced > maxSize) { + response.destroy(); + throw downloadError("Fichier trop volumineux (150 Mo au plus)", 413); + } + + const filePath = path.join(destinationDir, `download-${randomUUID()}`); + let size = 0; + response.on("data", (chunk) => { + size += chunk.length; + if (size > maxSize) { + response.destroy(downloadError("Fichier trop volumineux (150 Mo au plus)", 413)); + } + }); + + try { + await pipeline(response, fs.createWriteStream(filePath)); + } catch (error) { + fs.rmSync(filePath, { force: true }); + if (error.status) throw error; + throw downloadError(`Téléchargement interrompu : ${error.message}`, 502); + } + + return { + path: filePath, + originalname: fileNameFrom(response, url), + size, + mimetype: String(response.headers["content-type"] || "application/octet-stream") + .split(";")[0] + .trim(), + }; + } +} + +export { downloadAudio, isBlockedAddress, safeLookup }; diff --git a/src/media/validateAudioFile.js b/src/media/validateAudioFile.js index 7cbb0aa..949554d 100644 --- a/src/media/validateAudioFile.js +++ b/src/media/validateAudioFile.js @@ -1,35 +1,134 @@ -import { execFile } from "node:child_process"; +import { execFile, spawn } from "node:child_process"; import { promisify } from "node:util"; const execFileAsync = promisify(execFile); -async function validateAudioFile(filePath) { +// Normalisation du volume (EBU R128, mode dynamique en une passe) : tous les morceaux sortent +// au même niveau, quel que soit le fichier d'origine. +const LOUDNORM_FILTER = "loudnorm=I=-16:TP=-1.5:LRA=11"; +const MAX_STDERR_LENGTH = 4_000; + +function cleanTag(value) { + if (typeof value !== "string") return null; + const cleaned = value.replace(/[\u0000-\u001f]/g, "").trim().slice(0, 200); + return cleaned || null; +} + +// Les noms des tags varient selon le format (« title » en ID3, « TITLE » en Vorbis) : on les +// met en minuscules. Les tags Ogg sont portés par le flux, les autres par le conteneur. +function lowerCaseTags(...tagSets) { + const tags = {}; + for (const set of tagSets) { + for (const [key, value] of Object.entries(set || {})) { + tags[key.toLowerCase()] ??= value; + } + } + return tags; +} + +// Vérifie qu'un fichier contient une piste audio et lit sa durée (secondes) et ses tags. +async function probeAudioFile(filePath) { + let parsed; try { const { stdout } = await execFileAsync( "ffprobe", [ "-v", "error", - "-select_streams", - "a:0", "-show_entries", - "stream=codec_type", + "format=duration:format_tags:stream=codec_type:stream_tags", "-of", - "default=noprint_wrappers=1:nokey=1", + "json", filePath, ], { timeout: 15_000, maxBuffer: 1024 * 1024 } ); - - if (stdout.trim() !== "audio") { - throw new Error("Aucune piste audio détectée"); - } + parsed = JSON.parse(stdout); } catch (error) { - const validationError = new Error("Le fichier fourni n'est pas un audio valide"); - validationError.status = 400; - validationError.cause = error; - throw validationError; + throw invalidAudioError(error); } + + const audioStream = parsed.streams?.find((stream) => stream.codec_type === "audio"); + if (!audioStream) { + throw invalidAudioError(new Error("Aucune piste audio détectée")); + } + + const duration = Number(parsed.format?.duration); + const tags = lowerCaseTags(parsed.format?.tags, audioStream.tags); + return { + duration: Number.isFinite(duration) && duration > 0 ? Math.round(duration) : null, + title: cleanTag(tags.title), + artist: cleanTag(tags.artist), + }; } -export { validateAudioFile }; +function invalidAudioError(cause) { + const error = new Error("Le fichier fourni n'est pas un audio valide"); + error.status = 400; + error.cause = cause; + return error; +} + +async function validateAudioFile(filePath) { + await probeAudioFile(filePath); +} + +// Décode le fichier, normalise le volume et encode en Ogg Opus avec le ffmpeg natif : Discord +// reçoit l'Opus tel quel, sans réencodage en JavaScript. Fermer le flux arrête ffmpeg. +function createOpusStream(filePath, { spawnProcess = spawn } = {}) { + const ffmpeg = spawnProcess( + "ffmpeg", + [ + "-hide_banner", + "-loglevel", + "error", + "-i", + filePath, + "-map", + "0:a:0", + "-vn", + "-af", + LOUDNORM_FILTER, + "-c:a", + "libopus", + "-b:a", + "128k", + "-ar", + "48000", + "-ac", + "2", + "-f", + "ogg", + "pipe:1", + ], + { stdio: ["ignore", "pipe", "pipe"] } + ); + + const output = ffmpeg.stdout; + let stderr = ""; + ffmpeg.stderr.on("data", (chunk) => { + if (stderr.length < MAX_STDERR_LENGTH) { + stderr += chunk.toString(); + } + }); + + ffmpeg.on("error", (error) => { + output.destroy(error); + }); + ffmpeg.on("close", (code, signal) => { + if (code !== 0 && signal === null && !output.destroyed) { + output.destroy( + new Error(`ffmpeg exited with code ${code}: ${stderr.trim().slice(0, 500)}`) + ); + } + }); + output.on("close", () => { + if (ffmpeg.exitCode === null && ffmpeg.signalCode === null) { + ffmpeg.kill("SIGKILL"); + } + }); + + return output; +} + +export { LOUDNORM_FILTER, createOpusStream, probeAudioFile, validateAudioFile }; diff --git a/src/music/ingest.js b/src/music/ingest.js new file mode 100644 index 0000000..3025d7b --- /dev/null +++ b/src/music/ingest.js @@ -0,0 +1,60 @@ +import { probeAudioFile } from "../media/validateAudioFile.js"; +import { + discardUploadedFile, + registerUploadedFile, +} from "../web/storage/storageManager.js"; + +function cleanText(value, maxLength) { + return String(value ?? "") + .replace(/[\u0000-\u001f]/g, "") + .trim() + .slice(0, maxLength); +} + +// Titre par défaut : « Artiste - Titre » d'après les tags, sinon le nom du fichier sans +// son extension. +function defaultTitle({ title, artist }, originalName) { + if (title) { + return (artist ? `${artist} - ${title}` : title).slice(0, 200); + } + return originalName.replace(/\.[a-z0-9]{1,10}$/i, "").slice(0, 200) || originalName; +} + +// Ajoute un fichier déjà présent dans storage/temp (upload, lien, pièce jointe Discord) : +// vérifie que c'est de l'audio, l'enregistre (bibliothèque si permanent) et le met en file. +// En cas d'échec, le fichier est supprimé. +async function ingestAudioFile( + file, + { permanent = false, enqueue = true, uploader, title } = {}, + { queue, probe = probeAudioFile } +) { + try { + if (!permanent && !enqueue) { + const error = new Error("Un fichier temporaire doit être ajouté à la file d'attente"); + error.status = 400; + throw error; + } + + const metadata = await probe(file.path); + const track = registerUploadedFile(file, { + permanent, + uploader: cleanText(uploader, 80) || "inconnu", + title: cleanText(title, 200) || defaultTitle(metadata, file.originalname), + duration: metadata.duration, + artist: metadata.artist, + }); + + if (permanent) { + queue.emit("libraryUpdate"); + } + if (enqueue) { + queue.enqueue(track); + } + return track; + } catch (error) { + discardUploadedFile(file); + throw error; + } +} + +export { defaultTitle, ingestAudioFile }; diff --git a/src/music/queue.js b/src/music/queue.js index db7692e..cf7a822 100644 --- a/src/music/queue.js +++ b/src/music/queue.js @@ -1,8 +1,9 @@ -import fs from "fs"; import { EventEmitter } from "events"; +import { randomUUID } from "node:crypto"; import { AudioPlayerStatus, NoSubscriberBehavior, + StreamType, VoiceConnectionStatus, createAudioPlayer, createAudioResource, @@ -11,6 +12,7 @@ import { } from "@discordjs/voice"; import { Events } from "discord.js"; import { config } from "../config.js"; +import { createOpusStream } from "../media/validateAudioFile.js"; import { serializeTrack, serializeTracks } from "../web/serializers.js"; import { deleteTrackFile, @@ -18,17 +20,35 @@ 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) { + // persistence : { load() → état | null, save(état) } pour garder la file d'un démarrage à + // l'autre (voir queuePersistence.js). Sans elle, la file est perdue à l'arrêt. + constructor( + client, + { retryDelays = CONNECT_RETRY_DELAYS, persistence = null } = {} + ) { super(); + this.setMaxListeners(50); // une écoute par page web ouverte (flux d'événements) this.client = client; this.queue = []; this.currentTrack = null; + this.loop = false; + // Le morceau en cours ne doit pas revenir en fin de file en mode boucle (retiré, en + // erreur, file vidée). + this.discardCurrent = false; + this.persistence = persistence; + this.saveTimeout = null; this.connection = null; this.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; @@ -48,24 +68,33 @@ class MusicQueue extends EventEmitter { this.client.on(Events.VoiceStateUpdate, this.voiceStateListener); this.audioPlayer.on(AudioPlayerStatus.Idle, () => { - if (this.currentTrack) { - handleTrackCompletion(this.currentTrack); - } + const finished = this.currentTrack; this.currentTrack = null; + if (finished) { + if (this.loop && !this.discardCurrent && !this.shuttingDown) { + // Mode boucle : le morceau repart en fin de file, fichier conservé. + const { startedAt: _startedAt, ...track } = finished; + this.queue.push({ ...track, id: randomUUID() }); + } else { + handleTrackCompletion(finished); + } + } + this.discardCurrent = false; if (!this.shuttingDown) { void this.playNext(); } }); + // Après une erreur, le player passe toujours en Idle : le gestionnaire ci-dessus + // termine le morceau et lance le suivant (sans le remettre en boucle). 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.discardCurrent = true; }); + this.on("queueUpdate", () => this.scheduleSave()); + this.restore(); + this.audioPlayer.on("stateChange", (oldState, newState) => { this.playbackStatus = newState.status; this.emit("queueUpdate", this.snapshot()); @@ -77,9 +106,21 @@ class MusicQueue extends EventEmitter { current: serializeTrack(this.currentTrack), upcoming: serializeTracks(this.queue), status: this.playbackStatus, + loop: this.loop, + // Millisecondes déjà jouées du morceau en cours (pauses exclues). + position: this.audioPlayer?.state?.resource?.playbackDuration ?? 0, }; } + // 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 +170,7 @@ class MusicQueue extends EventEmitter { ]); } catch { if (this.connection === connection) { - this.destroyConnection("voice connection lost"); + this.destroyConnection("voice connection lost", { requeue: true }); } } }); @@ -153,6 +194,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 +219,9 @@ class MusicQueue extends EventEmitter { } async runPlayNext() { - if (this.suspendedForAlone) { + this.cancelConnectRetry(); + + if (this.shuttingDown || this.suspendedForAlone) { return; } @@ -189,26 +236,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 +273,48 @@ class MusicQueue extends EventEmitter { } } + createResource(track) { + return createAudioResource(createOpusStream(track.path), { + inputType: StreamType.OggOpus, + }); + } + + 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.discardCurrent = true; this.skip(); - return this.currentTrack; + return removed; } return null; } @@ -262,12 +346,43 @@ class MusicQueue extends EventEmitter { } stop() { + this.cancelConnectRetry(); this.queue.forEach((track) => deleteTrackFile(track)); this.queue = []; + this.discardCurrent = Boolean(this.currentTrack); this.audioPlayer.stop(true); this.emit("queueUpdate", this.snapshot()); } + // Mélange les morceaux à venir (le morceau en cours n'est pas touché). + shuffle() { + for (let index = this.queue.length - 1; index > 0; index--) { + const randomIndex = Math.floor(Math.random() * (index + 1)); + [this.queue[index], this.queue[randomIndex]] = [ + this.queue[randomIndex], + this.queue[index], + ]; + } + this.emit("queueUpdate", this.snapshot()); + return this.snapshot(); + } + + setLoop(enabled) { + this.loop = Boolean(enabled); + this.emit("queueUpdate", this.snapshot()); + return this.snapshot(); + } + + // Met à jour le titre des morceaux en file venant d'une entrée de bibliothèque renommée. + renameLibraryTrack(libraryTrackId, title) { + for (const track of [this.currentTrack, ...this.queue]) { + if (track && track.libraryTrackId === libraryTrackId) { + track.title = title; + } + } + this.emit("queueUpdate", this.snapshot()); + } + pause() { this.audioPlayer.pause(true); } @@ -278,6 +393,7 @@ class MusicQueue extends EventEmitter { start() { this.suspendedForAlone = false; + this.connectFailures = 0; this.cancelIdleDisconnect(); if (!this.currentTrack) { return this.playNext(); @@ -304,6 +420,7 @@ class MusicQueue extends EventEmitter { this.currentTrack && this.currentTrack.libraryTrackId === libraryTrackId ) { + this.discardCurrent = true; this.skip(); } @@ -314,7 +431,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 +447,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 +468,9 @@ class MusicQueue extends EventEmitter { console.error("Failed to stop audio player", error); } - handleTrackCompletion(interruptedTrack); + if (!requeued) { + handleTrackCompletion(interruptedTrack); + } this.emit("queueUpdate", this.snapshot()); console.log( `[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})` @@ -384,7 +510,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 +525,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,35 +545,109 @@ class MusicQueue extends EventEmitter { } } - isBotAlone() { + // 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); - if (!channel) { - return false; - } - const clientId = this.client.user?.id; - if (!clientId) { - return false; + if (!channel || !clientId) { + return null; } - if (!channel.members.has(clientId)) { - return false; - } - - const others = channel.members.filter((member) => member.id !== clientId); - return others.size === 0; + 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); + const clientId = this.client.user?.id; + if (!channel || !clientId || !channel.members.has(clientId)) { + return false; + } + + return this.listeners().length === 0; + } + + // Avec la persistance, la file (morceau en cours en tête) est enregistrée et ses fichiers + // gardés pour le prochain démarrage ; sans elle, les fichiers temporaires sont supprimés. shutdown() { this.shuttingDown = true; this.cancelIdleDisconnect(); this.cancelAloneDisconnect(); + this.cancelConnectRetry(); + clearTimeout(this.saveTimeout); this.client.off(Events.VoiceStateUpdate, this.voiceStateListener); + if (this.persistence) { + this.destroyConnection("shutdown", { requeue: true }); + this.save(); + return; + } + this.queue.forEach((track) => deleteTrackFile(track)); this.queue = []; this.destroyConnection("shutdown"); } + + persistedState() { + return { + // Le morceau en cours reprendra du début, en tête de file. + queue: [this.currentTrack, ...this.queue] + .filter(Boolean) + .map(({ startedAt: _startedAt, ...track }) => track), + loop: this.loop, + }; + } + + scheduleSave() { + if (!this.persistence || this.saveTimeout || this.shuttingDown) { + return; + } + this.saveTimeout = setTimeout(() => { + this.saveTimeout = null; + this.save(); + }, 500); + this.saveTimeout.unref?.(); + } + + save() { + if (!this.persistence) return; + try { + this.persistence.save(this.persistedState()); + } catch (error) { + console.error("Unable to save the music queue", error); + } + } + + // Recharge la file enregistrée. Elle reste en attente (comme quand le bot est parti faute + // d'auditeurs) : la lecture reprend dès qu'il y a quelqu'un dans le salon, avec un ajout + // ou avec le bouton Play. + restore() { + if (!this.persistence) return; + let state; + try { + state = this.persistence.load(); + } catch (error) { + console.error("Unable to restore the music queue", error); + return; + } + if (!state) return; + + this.queue = (Array.isArray(state.queue) ? state.queue : []).filter( + (track) => track && typeof track.id === "string" && typeof track.path === "string" + ); + this.loop = Boolean(state.loop); + if (this.queue.length > 0) { + this.suspendedForAlone = true; + console.log( + `[${new Date().toLocaleString()}] MusicQueue restored ${this.queue.length} track(s)` + ); + } + } } export { MusicQueue }; diff --git a/src/music/queuePersistence.js b/src/music/queuePersistence.js new file mode 100644 index 0000000..0e330d7 --- /dev/null +++ b/src/music/queuePersistence.js @@ -0,0 +1,27 @@ +import fs from "node:fs"; +import path from "node:path"; + +// Enregistre la file dans un fichier JSON (écriture atomique) et ne recharge que les morceaux +// dont le fichier existe encore. +function createQueuePersistence(filePath) { + return { + load() { + if (!fs.existsSync(filePath)) return null; + const state = JSON.parse(fs.readFileSync(filePath, "utf8")); + return { + ...state, + queue: (state.queue || []).filter( + (track) => typeof track?.path === "string" && fs.existsSync(track.path) + ), + }; + }, + save(state) { + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + const temporaryFile = `${filePath}.${process.pid}.tmp`; + fs.writeFileSync(temporaryFile, JSON.stringify(state, null, 2)); + fs.renameSync(temporaryFile, filePath); + }, + }; +} + +export { createQueuePersistence }; diff --git a/src/static/gameservers-list.example.json b/src/static/gameservers-list.example.json index a251775..6fe4c99 100644 --- a/src/static/gameservers-list.example.json +++ b/src/static/gameservers-list.example.json @@ -1,10 +1,23 @@ { "servers": [ { - "game": "Nom du jeu", + "game": "Nom du jeu (état saisi à la main)", "address": "games.example.com:25565", "port": 25565, "active": false + }, + { + "game": "Nom du jeu (état vérifié par le bot, en TCP)", + "address": "games.example.com:25566", + "port": 25566, + "check": true + }, + { + "game": "Jeu en UDP (vérifié sur son port RCON, en TCP)", + "address": "games.example.com:8211", + "port": 8211, + "check": true, + "checkPort": 25575 } ] } diff --git a/src/web/auth/session.js b/src/web/auth/session.js new file mode 100644 index 0000000..615a853 --- /dev/null +++ b/src/web/auth/session.js @@ -0,0 +1,78 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; + +const SESSION_COOKIE = "palico_session"; +const STATE_COOKIE = "palico_oauth_state"; +const SESSION_DURATION = 30 * 24 * 60 * 60 * 1000; + +function sign(payload, secret) { + return createHmac("sha256", secret).update(payload).digest("base64url"); +} + +// Jeton de session sans stockage côté serveur : « données.signature », signé par HMAC. +// Changer SESSION_SECRET déconnecte tout le monde. +function createSessionToken({ id, name }, secret, now = Date.now()) { + const payload = Buffer.from( + JSON.stringify({ sub: id, name, exp: now + SESSION_DURATION }) + ).toString("base64url"); + return `${payload}.${sign(payload, secret)}`; +} + +function readSessionToken(token, secret, now = Date.now()) { + if (typeof token !== "string" || !secret) return null; + const [payload, signature, extra] = token.split("."); + if (!payload || !signature || extra !== undefined) return null; + + const expected = Buffer.from(sign(payload, secret)); + const received = Buffer.from(signature); + if (expected.length !== received.length || !timingSafeEqual(expected, received)) { + return null; + } + + try { + const data = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")); + if (typeof data.sub !== "string" || typeof data.exp !== "number" || data.exp < now) { + return null; + } + return { id: data.sub, name: String(data.name || "").slice(0, 80) }; + } catch { + return null; + } +} + +function parseCookies(header = "") { + const cookies = {}; + for (const part of header.split(";")) { + const index = part.indexOf("="); + if (index === -1) continue; + const name = part.slice(0, index).trim(); + try { + cookies[name] = decodeURIComponent(part.slice(index + 1).trim()); + } catch { + // Cookie mal formé : ignoré. + } + } + return cookies; +} + +function serializeCookie(name, value, { maxAge, path = "/", secure = true } = {}) { + return [ + `${name}=${encodeURIComponent(value)}`, + `Path=${path}`, + "HttpOnly", + "SameSite=Lax", + secure ? "Secure" : null, + maxAge !== undefined ? `Max-Age=${Math.floor(maxAge / 1000)}` : null, + ] + .filter(Boolean) + .join("; "); +} + +export { + SESSION_COOKIE, + SESSION_DURATION, + STATE_COOKIE, + createSessionToken, + parseCookies, + readSessionToken, + serializeCookie, +}; diff --git a/src/web/middlewares/auth.js b/src/web/middlewares/auth.js index f6ed74a..1e04ddb 100644 --- a/src/web/middlewares/auth.js +++ b/src/web/middlewares/auth.js @@ -30,6 +30,25 @@ function createBearerAuth(getExpectedKey) { const authMiddleware = createBearerAuth(() => config.webApiKey); +// API du jukebox : la clé (en-tête Authorization) ou une session Discord (cookie, voir +// sessionMiddleware). Avec le cookie, une requête qui modifie quelque chose doit venir du site +// lui-même (en-tête Origin), en plus de la protection SameSite du cookie. +function createJukeboxAuth({ publicUrl } = {}) { + const allowedOrigin = publicUrl ? new URL(publicUrl).origin : null; + return function jukeboxAuth(req, res, next) { + if (req.headers.authorization || !req.user) { + return authMiddleware(req, res, next); + } + + const safeMethod = req.method === "GET" || req.method === "HEAD"; + const origin = req.headers.origin; + if (!safeMethod && origin && origin !== allowedOrigin) { + return res.status(403).json({ error: "Origine refusée" }); + } + return next(); + }; +} + const LOOPBACK_ADDRESSES = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]); function isLoopbackAddress(address) { @@ -45,4 +64,4 @@ function localOnly(req, res, next) { return res.status(403).json({ error: "Route réservée aux applications locales", code: "LOCAL_ONLY" }); } -export { authMiddleware, createBearerAuth, isLoopbackAddress, localOnly }; +export { authMiddleware, createBearerAuth, createJukeboxAuth, isLoopbackAddress, localOnly }; diff --git a/src/web/routes/auth.js b/src/web/routes/auth.js new file mode 100644 index 0000000..3d09d4a --- /dev/null +++ b/src/web/routes/auth.js @@ -0,0 +1,125 @@ +import { Router } from "express"; +import { randomBytes } from "node:crypto"; +import { + SESSION_COOKIE, + SESSION_DURATION, + STATE_COOKIE, + createSessionToken, + parseCookies, + readSessionToken, + serializeCookie, +} from "../auth/session.js"; + +const DISCORD_API = "https://discord.com/api/v10"; +const STATE_DURATION = 10 * 60 * 1000; + +// Lit la session (cookie signé) et place l'utilisateur dans req.user. +function sessionMiddleware(oauth) { + return function readSession(req, _res, next) { + if (oauth.enabled) { + const token = parseCookies(req.headers.cookie)[SESSION_COOKIE]; + req.user = readSessionToken(token, oauth.sessionSecret); + } + next(); + }; +} + +// Connexion avec Discord (OAuth2, portée « identify ») réservée aux membres du serveur. +// oauth : { enabled, clientId, clientSecret, publicUrl, sessionSecret }. +// findMember(userId) renvoie le membre du serveur ou null. +function authRouter({ oauth, findMember, fetchImpl = fetch }) { + const router = Router(); + const secure = oauth.enabled && new URL(oauth.publicUrl).protocol === "https:"; + const redirectUri = oauth.enabled ? `${oauth.publicUrl}/auth/discord/callback` : null; + const fail = (res, reason) => res.redirect(303, `/jukebox/?login=${reason}`); + + router.get("/me", (req, res) => { + res.set("Cache-Control", "no-store"); + res.json({ oauthEnabled: oauth.enabled, user: req.user ?? null }); + }); + + router.get("/discord", (req, res) => { + if (!oauth.enabled) { + return res.status(404).json({ error: "Connexion avec Discord désactivée" }); + } + + const state = randomBytes(24).toString("base64url"); + res.append( + "Set-Cookie", + serializeCookie(STATE_COOKIE, state, { maxAge: STATE_DURATION, path: "/auth", secure }) + ); + const params = new URLSearchParams({ + client_id: oauth.clientId, + response_type: "code", + redirect_uri: redirectUri, + scope: "identify", + state, + prompt: "none", + }); + res.redirect(303, `https://discord.com/oauth2/authorize?${params}`); + }); + + router.get("/discord/callback", async (req, res) => { + if (!oauth.enabled) { + return res.status(404).json({ error: "Connexion avec Discord désactivée" }); + } + + const expectedState = parseCookies(req.headers.cookie)[STATE_COOKIE]; + res.append( + "Set-Cookie", + serializeCookie(STATE_COOKIE, "", { maxAge: 0, path: "/auth", secure }) + ); + if (req.query.error) return fail(res, "denied"); + if (!expectedState || req.query.state !== expectedState) return fail(res, "state"); + if (typeof req.query.code !== "string") return fail(res, "failed"); + + try { + const tokenResponse = await fetchImpl(`${DISCORD_API}/oauth2/token`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + client_id: oauth.clientId, + client_secret: oauth.clientSecret, + grant_type: "authorization_code", + code: req.query.code, + redirect_uri: redirectUri, + }), + }); + if (!tokenResponse.ok) throw new Error(`token exchange: ${tokenResponse.status}`); + const { access_token: accessToken } = await tokenResponse.json(); + + const userResponse = await fetchImpl(`${DISCORD_API}/users/@me`, { + headers: { authorization: `Bearer ${accessToken}` }, + }); + if (!userResponse.ok) throw new Error(`user lookup: ${userResponse.status}`); + const user = await userResponse.json(); + + const member = await findMember(user.id); + if (!member) return fail(res, "not-member"); + + const name = member.displayName || user.global_name || user.username; + res.append( + "Set-Cookie", + serializeCookie( + SESSION_COOKIE, + createSessionToken({ id: user.id, name }, oauth.sessionSecret), + { maxAge: SESSION_DURATION, secure } + ) + ); + console.log(`[${new Date().toLocaleString()}] Web login: ${user.id}`); + return res.redirect(303, "/jukebox/"); + } catch (error) { + console.error("Discord login failed", error); + return fail(res, "failed"); + } + }); + + router.post("/logout", (req, res) => { + res.append("Set-Cookie", serializeCookie(SESSION_COOKIE, "", { maxAge: 0, secure })); + res.status(204).end(); + }); + + return router; +} + +export { authRouter, sessionMiddleware }; diff --git a/src/web/routes/events.js b/src/web/routes/events.js new file mode 100644 index 0000000..4bd3fff --- /dev/null +++ b/src/web/routes/events.js @@ -0,0 +1,41 @@ +import { Router } from "express"; + +const HEARTBEAT_INTERVAL = 25_000; + +// Flux d'événements (Server-Sent Events) : « queue » envoie l'état de la file à chaque +// changement, « library » signale que la bibliothèque a changé. La page s'en sert à la place +// d'un rafraîchissement périodique. +function eventsRouter({ queue }) { + const router = Router(); + + router.get("/", (req, res) => { + res.writeHead(200, { + "Content-Type": "text/event-stream; charset=utf-8", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no", + }); + + const send = (event, data) => { + res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); + }; + const onQueueUpdate = (snapshot) => send("queue", snapshot); + const onLibraryUpdate = () => send("library", {}); + + send("queue", queue.snapshot()); + queue.on("queueUpdate", onQueueUpdate); + queue.on("libraryUpdate", onLibraryUpdate); + const heartbeat = setInterval(() => res.write(": ping\n\n"), HEARTBEAT_INTERVAL); + + // Fermeture de la connexion (onglet fermé, réseau coupé) : on arrête d'écouter la file. + res.on("close", () => { + clearInterval(heartbeat); + queue.off("queueUpdate", onQueueUpdate); + queue.off("libraryUpdate", onLibraryUpdate); + }); + }); + + return router; +} + +export { eventsRouter }; diff --git a/src/web/routes/library.js b/src/web/routes/library.js index 3087db3..5f76de4 100644 --- a/src/web/routes/library.js +++ b/src/web/routes/library.js @@ -4,6 +4,7 @@ import { deletePermanentTrack, findPermanentTrack, getPermanentLibrary, + updatePermanentTracks, } from "../storage/storageManager.js"; import { serializeTrack, serializeTracks } from "../serializers.js"; @@ -22,9 +23,45 @@ function libraryRouter({ queue }) { } queue.removeByLibraryId(track.id); + queue.emit("libraryUpdate"); res.json({ removed: serializeTrack(track) }); }); + router.patch("/:libraryId", (req, res) => { + const title = String(req.body?.title ?? "") + .replace(/[\u0000-\u001f]/g, "") + .trim() + .slice(0, 200); + if (!title) { + return res.status(400).json({ error: "Titre manquant" }); + } + + const [track] = updatePermanentTracks(new Map([[req.params.libraryId, { title }]])); + if (!track) { + return res.status(404).json({ error: "Fichier permanent introuvable" }); + } + + queue.renameLibraryTrack(track.id, title); + queue.emit("libraryUpdate"); + res.json({ track: serializeTrack(track) }); + }); + + // Ajoute toute la bibliothèque à la file, mélangée si shuffle vaut true. + router.post("/enqueue-all", (req, res) => { + const entries = getPermanentLibrary(); + if (req.body?.shuffle === true) { + for (let index = entries.length - 1; index > 0; index--) { + const randomIndex = Math.floor(Math.random() * (index + 1)); + [entries[index], entries[randomIndex]] = [entries[randomIndex], entries[index]]; + } + } + + const tracks = entries.map((entry) => + queue.enqueue(createQueueTrackFromLibrary(entry, req.user?.name ?? req.body?.requestedBy)) + ); + res.status(201).json({ tracks: serializeTracks(tracks) }); + }); + router.post("/:libraryId/enqueue", (req, res) => { const baseTrack = findPermanentTrack(req.params.libraryId); if (!baseTrack) { @@ -33,7 +70,7 @@ function libraryRouter({ queue }) { const queueTrack = createQueueTrackFromLibrary( baseTrack, - req.body?.requestedBy + req.user?.name ?? req.body?.requestedBy ); queue.enqueue(queueTrack); res.status(201).json({ track: serializeTrack(queueTrack) }); diff --git a/src/web/routes/player.js b/src/web/routes/player.js index 011d383..c00a4f1 100644 --- a/src/web/routes/player.js +++ b/src/web/routes/player.js @@ -28,6 +28,17 @@ function playerRouter({ queue }) { res.json(queue.snapshot()); }); + router.post("/shuffle", (req, res) => { + res.json(queue.shuffle()); + }); + + router.post("/loop", (req, res) => { + if (typeof req.body?.enabled !== "boolean") { + return res.status(400).json({ error: "enabled doit être un booléen" }); + } + res.json(queue.setLoop(req.body.enabled)); + }); + return router; } diff --git a/src/web/routes/queue.js b/src/web/routes/queue.js index ef7c7a4..059793b 100644 --- a/src/web/routes/queue.js +++ b/src/web/routes/queue.js @@ -22,7 +22,7 @@ function queueRouter({ queue }) { return res.status(404).json({ error: "Fichier permanent introuvable" }); } - const track = createQueueTrackFromLibrary(libraryTrack, requestedBy); + const track = createQueueTrackFromLibrary(libraryTrack, req.user?.name ?? requestedBy); queue.enqueue(track); res.status(201).json({ track: serializeTrack(track) }); }); diff --git a/src/web/routes/uploads.js b/src/web/routes/uploads.js index 1d69ef2..a2ee3de 100644 --- a/src/web/routes/uploads.js +++ b/src/web/routes/uploads.js @@ -1,26 +1,13 @@ import { Router } from "express"; import multer from "multer"; -import { validateAudioFile } from "../../media/validateAudioFile.js"; +import { downloadAudio } from "../../media/downloadAudio.js"; +import { ingestAudioFile } from "../../music/ingest.js"; import { serializeTrack } from "../serializers.js"; -import { - TEMP_DIR, - discardUploadedFile, - 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", -]); +import { TEMP_DIR } from "../storage/storageManager.js"; +// 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,55 +22,52 @@ const upload = multer({ callback(error); return; } - callback(null, ALLOWED_AUDIO_TYPES.has(file.mimetype)); + callback(null, true); }, }); function uploadsRouter({ queue }) { const router = Router(); + // Connecté avec Discord, le nom vient de la session et non du formulaire. + const options = ({ body, user }) => ({ + permanent: body?.permanent === "true" || body?.permanent === true, + enqueue: body?.enqueue !== "false" && body?.enqueue !== false, + uploader: user?.name || body?.uploader || "web-ui", + title: body?.notes, + }); + router.post("/", upload.single("file"), async (req, res, next) => { if (!req.file) { return res.status(400).json({ error: "Aucun fichier reçu" }); } - const permanent = req.body?.permanent === "true"; - const enqueue = req.body?.enqueue !== "false"; - const uploader = String(req.body?.uploader || "web-ui") - .replace(/[\u0000-\u001f]/g, "") - .trim() - .slice(0, 80); - const title = String(req.body?.notes || req.file.originalname) - .replace(/[\u0000-\u001f]/g, "") - .trim() - .slice(0, 200); - try { - if (!permanent && !enqueue) { - const error = new Error( - "Un fichier temporaire doit être ajouté à la file d'attente" - ); - error.status = 400; - throw error; - } - - await validateAudioFile(req.file.path); - const track = registerUploadedFile(req.file, { - permanent, - uploader, - title: title || req.file.originalname, - }); - - if (enqueue) { - queue.enqueue(track); - } - + const track = await ingestAudioFile(req.file, options(req), { queue }); return res.status(201).json({ track: serializeTrack(track), - enqueued: enqueue, + enqueued: options(req).enqueue, + }); + } catch (error) { + return next(error); + } + }); + + // Ajout depuis un lien direct vers un fichier audio : le serveur le télécharge lui-même. + router.post("/url", async (req, res, next) => { + const url = req.body?.url; + if (typeof url !== "string" || url.length > 2_000) { + return res.status(400).json({ error: "Lien manquant" }); + } + + try { + const file = await downloadAudio(url, { destinationDir: TEMP_DIR }); + const track = await ingestAudioFile(file, options(req), { queue }); + return res.status(201).json({ + track: serializeTrack(track), + enqueued: options(req).enqueue, }); } catch (error) { - discardUploadedFile(req.file); return next(error); } }); diff --git a/src/web/server.js b/src/web/server.js index e180f7d..d384d6c 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -5,15 +5,18 @@ import multer from "multer"; import path from "path"; import { config } from "../config.js"; import { - authMiddleware, createBearerAuth, + createJukeboxAuth, localOnly, } from "./middlewares/auth.js"; +import { authRouter, sessionMiddleware } from "./routes/auth.js"; +import { eventsRouter } from "./routes/events.js"; import { libraryRouter } from "./routes/library.js"; import { notificationsRouter } from "./routes/notifications.js"; import { playerRouter } from "./routes/player.js"; import { queueRouter } from "./routes/queue.js"; import { uploadsRouter } from "./routes/uploads.js"; +import { backfillLibraryMetadata } from "./storage/libraryMetadata.js"; import { cleanupTemporaryFiles, ensureStorageLayout, @@ -41,18 +44,54 @@ function authFailureLimit() { }); } +const UNKNOWN_MEMBER = 10007; + +// Membre du serveur Discord configuré, ou null s'il n'en fait pas partie. +function guildMemberFinder(client) { + return async (userId) => { + const guild = + client.guilds?.cache.get(config.discordGuildId) ?? + (await client.guilds.fetch(config.discordGuildId)); + try { + return await guild.members.fetch(userId); + } catch (error) { + if (error?.code === UNKNOWN_MEMBER) return null; + throw error; + } + }; +} + function createApp( dependencies, - { notificationsApiKey = config.notificationsApiKey } = {} + { + notificationsApiKey = config.notificationsApiKey, + oauth = { + enabled: config.discordOAuthEnabled, + clientId: config.applicationId, + clientSecret: config.discordClientSecret, + publicUrl: config.webPublicUrl, + sessionSecret: config.sessionSecret, + }, + findMember = guildMemberFinder(dependencies.client), + fetchImpl = fetch, + } = {} ) { const app = express(); app.disable("x-powered-by"); app.set("trust proxy", config.webTrustedProxies); app.use(helmet()); app.use(express.json({ limit: "32kb" })); + app.use(sessionMiddleware(oauth)); + // /healthz : le processus répond (sonde de vie). /readyz : le bot est aussi connecté à + // Discord, sinon 503 (à utiliser pour la supervision). + const discordReady = () => dependencies.client?.isReady?.() ?? false; app.get("/healthz", (_req, res) => { - res.json({ status: "ok" }); + res.json({ status: "ok", discord: discordReady() ? "ready" : "not-ready" }); + }); + app.get("/readyz", (_req, res) => { + const ready = discordReady(); + res.status(ready ? 200 : 503).json({ status: ready ? "ready" : "not-ready" }); }); // Messages privés pour les applications de confiance : connexions locales uniquement, @@ -66,18 +105,27 @@ function createApp( notificationsRouter(dependencies) ); + app.use( + "/auth", + // /auth/me est appelée à chaque chargement de page : seule la connexion est limitée. + apiRateLimit({ windowMs: 15 * 60_000, limit: 60, skip: (req) => req.path === "/me" }), + authRouter({ oauth, findMember, fetchImpl }) + ); + const apiRouter = express.Router(); apiRouter.use(apiRateLimit({ windowMs: 60_000, limit: 120 })); apiRouter.use(authFailureLimit()); - apiRouter.use(authMiddleware); + apiRouter.use(createJukeboxAuth({ publicUrl: oauth.publicUrl })); apiRouter.use( "/uploads", - apiRateLimit({ windowMs: 15 * 60_000, limit: 10 }), + // Envoi de plusieurs fichiers d'un coup : une requête par fichier. + apiRateLimit({ windowMs: 15 * 60_000, limit: 40 }), uploadsRouter(dependencies) ); apiRouter.use("/queue", queueRouter(dependencies)); apiRouter.use("/library", libraryRouter(dependencies)); apiRouter.use("/player", playerRouter(dependencies)); + apiRouter.use("/events", eventsRouter(dependencies)); app.use("/api", apiRouter); app.get(["/jukebox", "/jukebox/"], (_req, res) => @@ -101,9 +149,28 @@ 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(); + + backfillLibraryMetadata() + .then((updated) => { + if (updated.length > 0) { + console.log( + `[${new Date().toLocaleString()}] Library metadata completed for ${updated.length} track(s)` + ); + dependencies.queue.emit("libraryUpdate"); + } + }) + .catch((error) => console.error("Unable to complete library metadata", error)); const app = createApp(dependencies); const port = Number(process.env.PORT || config.webServerPort || 3000); @@ -113,6 +180,7 @@ function startWebServer(dependencies) { `[${new Date().toLocaleString()}] Web control server listening on port ${port}` ); }); + server.on("close", () => clearInterval(cleanupInterval)); return { app, server }; } diff --git a/src/web/storage/libraryMetadata.js b/src/web/storage/libraryMetadata.js new file mode 100644 index 0000000..462ca7f --- /dev/null +++ b/src/web/storage/libraryMetadata.js @@ -0,0 +1,24 @@ +import { probeAudioFile } from "../../media/validateAudioFile.js"; +import { getPermanentLibrary, updatePermanentTracks } from "./storageManager.js"; + +// Complète la durée et l'artiste des morceaux ajoutés avant que l'upload ne les relève. +// Un fichier illisible est ignoré : il sera retenté au prochain démarrage. +async function backfillLibraryMetadata({ probe = probeAudioFile } = {}) { + const missing = getPermanentLibrary().filter((entry) => entry.duration == null); + const updates = new Map(); + + for (const entry of missing) { + try { + const { duration, artist } = await probe(entry.path); + if (duration != null) { + updates.set(entry.id, { duration, artist: entry.artist ?? artist }); + } + } catch (error) { + console.error(`Unable to read metadata of library entry ${entry.id}`, error.cause ?? error); + } + } + + return updatePermanentTracks(updates); +} + +export { backfillLibraryMetadata }; diff --git a/src/web/storage/storageManager.js b/src/web/storage/storageManager.js index a6c7b18..19937f1 100644 --- a/src/web/storage/storageManager.js +++ b/src/web/storage/storageManager.js @@ -87,7 +87,13 @@ function writeLibrary(entries) { function registerUploadedFile( file, - { permanent, uploader = "unknown", title = file.originalname } + { + permanent, + uploader = "unknown", + title = file.originalname, + duration = null, + artist = null, + } ) { ensureStorageLayout(); const createdAt = new Date().toISOString(); @@ -102,7 +108,9 @@ function registerUploadedFile( 0 ); if (librarySize + file.size > MAX_LIBRARY_SIZE) { - throw new Error("La bibliothèque permanente a atteint sa limite de 2 Go"); + const error = new Error("La bibliothèque permanente a atteint sa limite de 2 Go"); + error.status = 413; + throw error; } const rawExtension = path.extname(file.originalname).toLowerCase(); @@ -120,6 +128,8 @@ function registerUploadedFile( path: finalPath, size: file.size, mimetype: file.mimetype, + duration, + artist, uploader, createdAt, }; @@ -135,6 +145,8 @@ function registerUploadedFile( storedName, size: file.size, mimetype: file.mimetype, + duration, + artist, permanent, uploader, libraryTrackId: permanentEntry ? permanentEntry.id : null, @@ -164,14 +176,21 @@ function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") { storedName: libraryTrack.storedName, size: libraryTrack.size, mimetype: libraryTrack.mimetype, + duration: libraryTrack.duration ?? null, + artist: libraryTrack.artist ?? null, permanent: true, - uploader: requestedBy, + uploader: + String(requestedBy ?? "") + .replace(/[\u0000-\u001f]/g, "") + .trim() + .slice(0, 80) || "library", libraryTrackId: libraryTrack.id, createdAt: new Date().toISOString(), }; } -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 +200,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); @@ -207,6 +229,24 @@ function discardUploadedFile(file) { deleteFileSafe(file?.path); } +// Modifie des champs d'entrées de la bibliothèque : updates est une Map id → champs. +// Relit le fichier juste avant d'écrire, pour ne pas écraser un ajout fait entre-temps. +function updatePermanentTracks(updates) { + const library = getPermanentLibrary(); + const updated = []; + for (const entry of library) { + const fields = updates.get(entry.id); + if (fields) { + Object.assign(entry, fields); + updated.push(entry); + } + } + if (updated.length > 0) { + writeLibrary(library); + } + return updated; +} + function deletePermanentTrack(id) { const library = getPermanentLibrary(); const index = library.findIndex((entry) => entry.id === id); @@ -248,6 +288,7 @@ export { cleanupTemporaryFiles, discardUploadedFile, deletePermanentTrack, + updatePermanentTracks, handleTrackCompletion, deleteTrackFile, }; diff --git a/test/audio.test.js b/test/audio.test.js new file mode 100644 index 0000000..0fff37d --- /dev/null +++ b/test/audio.test.js @@ -0,0 +1,68 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { spawn, spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { StreamType, createAudioResource } from "@discordjs/voice"; +import { createOpusStream, probeAudioFile } from "../src/media/validateAudioFile.js"; + +const hasFfmpeg = + spawnSync("ffmpeg", ["-version"]).status === 0 && + spawnSync("ffprobe", ["-version"]).status === 0; +const skip = hasFfmpeg ? false : "ffmpeg et ffprobe sont nécessaires"; + +const directory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-audio-")); +test.after(() => fs.rmSync(directory, { recursive: true, force: true })); + +// Un MP3 de `seconds` secondes (un la à 440 Hz) avec des tags ID3. +function makeTone(name, seconds, { title = "Chanson", artist = "Palico" } = {}) { + const file = path.join(directory, name); + const result = spawnSync("ffmpeg", [ + "-v", "error", "-y", + "-f", "lavfi", "-i", `sine=frequency=440:duration=${seconds}`, + "-metadata", `title=${title}`, "-metadata", `artist=${artist}`, + "-c:a", "libmp3lame", "-b:a", "64k", file, + ]); + assert.equal(result.status, 0, result.stderr?.toString()); + return file; +} + +test("probeAudioFile reads the duration and the tags", { skip }, async () => { + const metadata = await probeAudioFile(makeTone("tagged.mp3", 2)); + assert.equal(metadata.duration, 2); + assert.equal(metadata.title, "Chanson"); + assert.equal(metadata.artist, "Palico"); +}); + +test("probeAudioFile rejects a file without audio", { skip }, async () => { + const file = path.join(directory, "not-audio.mp3"); + fs.writeFileSync(file, "pas du son"); + await assert.rejects(probeAudioFile(file), { status: 400 }); +}); + +test("createOpusStream yields Opus packets that Discord can play as is", { skip }, async () => { + const resource = createAudioResource(createOpusStream(makeTone("short.mp3", 1)), { + inputType: StreamType.OggOpus, + }); + + let packets = 0; + for await (const packet of resource.playStream) { + assert.ok(Buffer.isBuffer(packet) && packet.length > 0); + packets += 1; + } + // 1 s d'audio en trames Opus de 20 ms : une cinquantaine de paquets. + assert.ok(packets >= 45, `${packets} paquets`); +}); + +test("closing the Opus stream stops ffmpeg", { skip }, async () => { + let child; + const output = createOpusStream(makeTone("long.mp3", 120), { + spawnProcess: (...args) => (child = spawn(...args)), + }); + + await new Promise((resolve) => output.once("data", resolve)); + const exited = new Promise((resolve) => child.once("exit", (_code, signal) => resolve(signal))); + output.destroy(); + assert.equal(await exited, "SIGKILL"); +}); diff --git a/test/commands.test.js b/test/commands.test.js index e19f76f..5c30d0e 100644 --- a/test/commands.test.js +++ b/test/commands.test.js @@ -31,7 +31,7 @@ async function loadCommands() { test("all Discord commands expose valid command data", async () => { const modules = await loadCommands(); - assert.equal(modules.length, 10); + assert.equal(modules.length, 13); for (const module of modules) { assert.doesNotThrow(() => module.command.data.toJSON()); assert.equal(typeof module.command.execute, "function"); @@ -57,3 +57,13 @@ test("administrative commands require Discord permissions", async () => { } } }); + +test("/queue lists the current track and what comes next", async () => { + const { buildQueueMessage } = await import("../src/commands/jukebox/queue.js"); + const message = buildQueueMessage({ + currentTrack: { title: "Thème *principal*", duration: 187 }, + queue: [{ title: "Suite", duration: 3909 }], + }); + assert.match(message, /En cours : \*\*Thème \\\*principal\\\* \(3:07\)\*\*/); + assert.match(message, /1\. Suite \(1:05:09\)/); +}); diff --git a/test/discordAuth.test.js b/test/discordAuth.test.js new file mode 100644 index 0000000..13e3014 --- /dev/null +++ b/test/discordAuth.test.js @@ -0,0 +1,165 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +Object.assign(process.env, { + NODE_ENV: "test", + DISCORD_GUILD_ID: "1", + SHINUWA_USER_ID: "1", + WEB_SERVER_PORT: "3000", + WEB_API_KEY: "web-key", + DISCORD_APPLICATION_ID: "client-id", + DISCORD_TOKEN: "test-token", + VOICE_CHANNEL_ID: "1", + TEXT_CHANNEL_ID: "1", + GAME_SERVERS_MESSAGE_ID: "1", +}); + +const { createApp } = await import("../src/web/server.js"); +const { createSessionToken, readSessionToken } = await import("../src/web/auth/session.js"); + +const SECRET = "s".repeat(40); +const MEMBER_ID = "111111111111111111"; +const STRANGER_ID = "222222222222222222"; + +const oauth = { + enabled: true, + clientId: "client-id", + clientSecret: "client-secret", + publicUrl: "http://localhost", + sessionSecret: SECRET, +}; + +// Faux Discord : le code « member » identifie un membre du serveur, « stranger » un inconnu. +function fakeDiscordFetch(calls) { + return async (url, options = {}) => { + calls.push({ url, options }); + if (url.endsWith("/oauth2/token")) { + const code = options.body.get("code"); + return Response.json({ access_token: `token-${code}` }); + } + if (url.endsWith("/users/@me")) { + const token = options.headers.authorization; + const id = token === "Bearer token-member" ? MEMBER_ID : STRANGER_ID; + return Response.json({ id, username: "palico", global_name: "Palico" }); + } + return new Response(null, { status: 404 }); + }; +} + +const fakeQueue = { + snapshot: () => ({ current: null, upcoming: [], status: "idle", loop: false, position: 0 }), +}; + +async function withApp(run) { + const calls = []; + const app = createApp( + { queue: fakeQueue, client: {} }, + { + oauth, + fetchImpl: fakeDiscordFetch(calls), + findMember: async (id) => (id === MEMBER_ID ? { displayName: "Chef Palico" } : null), + } + ); + const server = app.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + try { + await run(`http://127.0.0.1:${server.address().port}`, calls); + } finally { + await new Promise((resolve) => server.close(resolve)); + } +} + +function cookieValue(response, name) { + const header = response.headers.getSetCookie().find((cookie) => cookie.startsWith(`${name}=`)); + return header ? decodeURIComponent(header.split(";")[0].slice(name.length + 1)) : null; +} + +async function login(base, code) { + const start = await fetch(`${base}/auth/discord`, { redirect: "manual" }); + assert.equal(start.status, 303); + const authorizeUrl = new URL(start.headers.get("location")); + assert.equal(authorizeUrl.hostname, "discord.com"); + assert.equal(authorizeUrl.searchParams.get("scope"), "identify"); + const state = authorizeUrl.searchParams.get("state"); + const stateCookie = cookieValue(start, "palico_oauth_state"); + assert.equal(stateCookie, state); + + return fetch(`${base}/auth/discord/callback?code=${code}&state=${state}`, { + redirect: "manual", + headers: { cookie: `palico_oauth_state=${stateCookie}` }, + }); +} + +test("a guild member logs in with Discord and uses the jukebox API", async () => { + await withApp(async (base) => { + const callback = await login(base, "member"); + assert.equal(callback.status, 303); + assert.equal(callback.headers.get("location"), "/jukebox/"); + const session = cookieValue(callback, "palico_session"); + assert.ok(session); + + const me = await (await fetch(`${base}/auth/me`, { headers: { cookie: `palico_session=${session}` } })).json(); + assert.deepEqual(me, { oauthEnabled: true, user: { id: MEMBER_ID, name: "Chef Palico" } }); + + const queue = await fetch(`${base}/api/queue`, { headers: { cookie: `palico_session=${session}` } }); + assert.equal(queue.status, 200); + }); +}); + +test("someone outside the guild is turned away", async () => { + await withApp(async (base) => { + const callback = await login(base, "stranger"); + assert.equal(callback.headers.get("location"), "/jukebox/?login=not-member"); + assert.equal(cookieValue(callback, "palico_session"), null); + }); +}); + +test("a callback without the matching state is refused", async () => { + await withApp(async (base, calls) => { + const callback = await fetch(`${base}/auth/discord/callback?code=member&state=forged`, { + redirect: "manual", + headers: { cookie: "palico_oauth_state=other" }, + }); + assert.equal(callback.headers.get("location"), "/jukebox/?login=state"); + assert.equal(calls.length, 0); + }); +}); + +test("a cookie session cannot change anything from another site", async () => { + await withApp(async (base) => { + const session = createSessionToken({ id: MEMBER_ID, name: "Chef Palico" }, SECRET); + const response = await fetch(`${base}/api/player/skip`, { + method: "POST", + headers: { cookie: `palico_session=${session}`, origin: "https://evil.example" }, + }); + assert.equal(response.status, 403); + }); +}); + +test("tampered or expired session tokens are rejected", () => { + const token = createSessionToken({ id: MEMBER_ID, name: "Chef" }, SECRET, 0); + assert.equal(readSessionToken(token, SECRET, 1)?.id, MEMBER_ID); + assert.equal(readSessionToken(token, "x".repeat(40), 1), null); + const [payload, signature] = token.split("."); + const forged = Buffer.from(JSON.stringify({ sub: STRANGER_ID, name: "x", exp: 9e15 })).toString("base64url"); + assert.equal(readSessionToken(`${forged}.${signature}`, SECRET, 1), null); + assert.equal(readSessionToken(`${payload}.${signature}`, SECRET, 31 * 24 * 3600 * 1000), null); +}); + +test("without OAuth the API still needs the key", async () => { + const app = createApp({ queue: fakeQueue, client: {} }); + const server = app.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + const base = `http://127.0.0.1:${server.address().port}`; + try { + const me = await (await fetch(`${base}/auth/me`)).json(); + assert.equal(me.oauthEnabled, false); + assert.equal((await fetch(`${base}/api/queue`)).status, 401); + assert.equal( + (await fetch(`${base}/api/queue`, { headers: { authorization: "Bearer web-key" } })).status, + 200 + ); + } finally { + await new Promise((resolve) => server.close(resolve)); + } +}); diff --git a/test/downloadAudio.test.js b/test/downloadAudio.test.js new file mode 100644 index 0000000..92f9eb4 --- /dev/null +++ b/test/downloadAudio.test.js @@ -0,0 +1,114 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import dns from "node:dns"; +import fs from "node:fs"; +import http from "node:http"; +import os from "node:os"; +import path from "node:path"; +import { downloadAudio, isBlockedAddress } from "../src/media/downloadAudio.js"; + +const directory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-download-")); +test.after(() => fs.rmSync(directory, { recursive: true, force: true })); + +// Le serveur de test écoute en local, adresse que le téléchargeur refuse : les tests qui +// doivent l'atteindre passent une résolution DNS sans filtre. +const allowLocal = (hostname, options, callback) => dns.lookup(hostname, options, callback); + +async function withServer(handler, run) { + const server = http.createServer(handler); + server.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + try { + await run(`http://localhost:${server.address().port}`); + } finally { + await new Promise((resolve) => server.close(resolve)); + } +} + +test("internal and special addresses are blocked", () => { + for (const address of ["127.0.0.1", "10.1.2.3", "192.168.0.100", "172.20.0.1", "169.254.169.254", "100.64.0.1", "::1", "fd00::1", "fe80::1", "::ffff:10.0.0.1"]) { + assert.equal(isBlockedAddress(address), true, address); + } + for (const address of ["1.1.1.1", "151.101.130.132", "2606:4700::1111"]) { + assert.equal(isBlockedAddress(address), false, address); + } +}); + +test("a direct link is downloaded with its file name", async () => { + await withServer( + (req, res) => { + res.writeHead(200, { + "content-type": "audio/mpeg", + "content-disposition": "attachment; filename=\"chanson.mp3\"", + }); + res.end("fake audio"); + }, + async (base) => { + const file = await downloadAudio(`${base}/download?id=1`, { + destinationDir: directory, + lookup: allowLocal, + }); + assert.equal(file.originalname, "chanson.mp3"); + assert.equal(file.mimetype, "audio/mpeg"); + assert.equal(file.size, 10); + assert.equal(fs.readFileSync(file.path, "utf8"), "fake audio"); + } + ); +}); + +test("local addresses are refused, written as an IP or behind a host name", async () => { + await assert.rejects(downloadAudio("http://127.0.0.1:1/a.mp3", { destinationDir: directory }), { + status: 400, + }); + await withServer( + (req, res) => res.end("secret"), + async (base) => { + await assert.rejects(downloadAudio(`${base}/a.mp3`, { destinationDir: directory }), { + message: /non autorisée/, + }); + } + ); +}); + +test("a redirect towards an internal address is refused", async () => { + await withServer( + (req, res) => { + res.writeHead(302, { location: "http://192.168.0.100/admin" }); + res.end(); + }, + async (base) => { + await assert.rejects( + downloadAudio(`${base}/a.mp3`, { destinationDir: directory, lookup: allowLocal }), + { message: /non autorisée/ } + ); + } + ); +}); + +test("files over the size limit are refused and removed", async () => { + await withServer( + (req, res) => { + res.writeHead(200); + res.write(Buffer.alloc(600)); + res.end(Buffer.alloc(600)); + }, + async (base) => { + const before = fs.readdirSync(directory).length; + await assert.rejects( + downloadAudio(`${base}/big.mp3`, { + destinationDir: directory, + lookup: allowLocal, + maxSize: 1000, + }), + { status: 413 } + ); + assert.equal(fs.readdirSync(directory).length, before); + } + ); +}); + +test("only http and https links are accepted", async () => { + await assert.rejects(downloadAudio("file:///etc/passwd", { destinationDir: directory }), { + status: 400, + }); +}); diff --git a/test/gameServers.test.js b/test/gameServers.test.js new file mode 100644 index 0000000..105d9d8 --- /dev/null +++ b/test/gameServers.test.js @@ -0,0 +1,46 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import net from "node:net"; + +Object.assign(process.env, { + NODE_ENV: "test", + DISCORD_GUILD_ID: "1", + SHINUWA_USER_ID: "1", + WEB_SERVER_PORT: "3000", + WEB_API_KEY: "test-key", + DISCORD_APPLICATION_ID: "1", + DISCORD_TOKEN: "test-token", + VOICE_CHANNEL_ID: "1", + TEXT_CHANNEL_ID: "1", + GAME_SERVERS_MESSAGE_ID: "1", +}); + +const { probeTcp, serverStatus } = await import("../src/features/showGameServers.js"); + +test("a listening TCP port is online, a closed one offline", async () => { + const server = net.createServer((socket) => socket.end()); + server.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + const { port } = server.address(); + try { + assert.equal(await probeTcp("127.0.0.1", port), true); + } finally { + await new Promise((resolve) => server.close(resolve)); + } + assert.equal(await probeTcp("127.0.0.1", port), false); +}); + +test("servers without check keep their manual status", async () => { + const probe = () => assert.fail("must not probe"); + assert.equal(await serverStatus({ active: true }, probe), true); + assert.equal(await serverStatus({ active: false }, probe), false); +}); + +test("checked servers are probed on checkPort, else on port", async () => { + const probed = []; + const probe = async (host, port) => probed.push(`${host}:${port}`) && true; + await serverStatus({ address: "games.example.com:8211", port: 8211, check: true, checkPort: 25575 }, probe); + await serverStatus({ address: "games.example.com:25566", port: 25566, check: true }, probe); + assert.deepEqual(probed, ["games.example.com:25575", "games.example.com:25566"]); + assert.equal(await serverStatus({ address: "x", check: true }, probe), false); +}); diff --git a/test/ingest.test.js b/test/ingest.test.js new file mode 100644 index 0000000..26ba4a0 --- /dev/null +++ b/test/ingest.test.js @@ -0,0 +1,67 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +// storageManager.js fixe ses dossiers au chargement, d'après le répertoire de travail. +const originalDirectory = process.cwd(); +const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-ingest-")); +process.chdir(temporaryDirectory); +const storage = await import("../src/web/storage/storageManager.js"); +const { defaultTitle, ingestAudioFile } = await import("../src/music/ingest.js"); +storage.ensureStorageLayout(); +test.after(() => { + process.chdir(originalDirectory); + fs.rmSync(temporaryDirectory, { recursive: true, force: true }); +}); + +function fakeQueue() { + const queue = new EventEmitter(); + queue.enqueued = []; + queue.enqueue = (track) => queue.enqueued.push(track); + return queue; +} + +function tempFile(name) { + const filePath = path.join(storage.TEMP_DIR, `upload-${name}`); + fs.writeFileSync(filePath, "audio"); + return { path: filePath, originalname: name, size: 5, mimetype: "audio/mpeg" }; +} + +test("default titles come from the tags, else from the file name", () => { + assert.equal(defaultTitle({ title: "Song", artist: "Band" }, "x.mp3"), "Band - Song"); + assert.equal(defaultTitle({ title: "Song", artist: null }, "x.mp3"), "Song"); + assert.equal(defaultTitle({ title: null, artist: null }, "Mon morceau.flac"), "Mon morceau"); +}); + +test("an ingested file is queued with its metadata", async () => { + const queue = fakeQueue(); + let libraryUpdates = 0; + queue.on("libraryUpdate", () => libraryUpdates++); + + const track = await ingestAudioFile( + tempFile("a.mp3"), + { permanent: true, uploader: "Shinuwa\u0007" }, + { queue, probe: async () => ({ duration: 61, title: "Titre", artist: "Artiste" }) } + ); + + assert.equal(track.title, "Artiste - Titre"); + assert.equal(track.duration, 61); + assert.equal(track.uploader, "Shinuwa"); + assert.deepEqual(queue.enqueued, [track]); + assert.equal(libraryUpdates, 1); + assert.equal(storage.getPermanentLibrary()[0].duration, 61); +}); + +test("a file that is not audio is deleted", async () => { + const file = tempFile("b.mp3"); + const invalid = Object.assign(new Error("pas de l'audio"), { status: 400 }); + + await assert.rejects( + ingestAudioFile(file, {}, { queue: fakeQueue(), probe: async () => { throw invalid; } }), + invalid + ); + assert.equal(fs.existsSync(file.path), false); +}); diff --git a/test/musicQueue.test.js b/test/musicQueue.test.js index 2b56a77..4a96910 100644 --- a/test/musicQueue.test.js +++ b/test/musicQueue.test.js @@ -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", @@ -43,10 +44,206 @@ test("queue snapshots do not expose filesystem paths", () => { queue.currentTrack = { id: "current", path: "/private/current.mp3" }; queue.queue = [{ id: "next", path: "/private/next.mp3" }]; queue.playbackStatus = "playing"; + queue.loop = false; assert.deepEqual(queue.snapshot(), { current: { id: "current" }, upcoming: [{ id: "next" }], status: "playing", + loop: false, + position: 0, }); }); + +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(); +}); + +test("in loop mode a finished track goes back to the end of the queue", () => { + const { client } = fakeClient(); + const { queue } = fakeQueue(client); + queue.setLoop(true); + queue.currentTrack = track("a"); + queue.queue.push(track("b")); + queue.playNext = () => {}; + + queue.audioPlayer.emit("idle"); + assert.deepEqual(queue.queue.map(({ path }) => path), ["/nonexistent/b", "/nonexistent/a"]); + + // Un morceau retiré ou en erreur ne revient pas. + queue.currentTrack = track("c"); + queue.audioPlayer.emit("error", new Error("bad file")); + queue.audioPlayer.emit("idle"); + assert.equal(queue.queue.some(({ path }) => path === "/nonexistent/c"), false); + queue.shutdown(); +}); + +test("shuffle keeps every upcoming track", () => { + const { client } = fakeClient(); + const { queue } = fakeQueue(client); + queue.queue.push(...["a", "b", "c", "d", "e"].map(track)); + queue.shuffle(); + assert.deepEqual(queue.queue.map(({ id }) => id).sort(), ["a", "b", "c", "d", "e"]); + queue.shutdown(); +}); + +test("the queue survives a restart and waits for listeners", () => { + let saved = null; + const persistence = { load: () => saved, save: (state) => (saved = state) }; + const { client } = fakeClient(); + + const first = new MusicQueue(client, { persistence }); + first.queue.push(track("b")); + first.currentTrack = { ...track("a"), startedAt: "2026-01-01T00:00:00.000Z" }; + first.connection = { destroy() {} }; + first.setLoop(true); + first.shutdown(); + + assert.deepEqual(saved.queue.map(({ id }) => id), ["a", "b"]); + assert.equal("startedAt" in saved.queue[0], false); + + const second = new MusicQueue(client, { persistence }); + assert.deepEqual(second.queue.map(({ id }) => id), ["a", "b"]); + assert.equal(second.loop, true); + assert.equal(second.suspendedForAlone, true); + second.shutdown(); +}); diff --git a/test/storageManager.test.js b/test/storageManager.test.js index 15bb48a..d628c00 100644 --- a/test/storageManager.test.js +++ b/test/storageManager.test.js @@ -81,3 +81,36 @@ test("legacy library entries migrate without their absolute paths", async () => fs.rmSync(temporaryDirectory, { recursive: true, force: true }); } }); + +test("library metadata backfill fills the missing durations", async () => { + const originalDirectory = process.cwd(); + const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-storage-")); + + try { + process.chdir(temporaryDirectory); + const storage = await import(`../src/web/storage/storageManager.js?backfill=${Date.now()}`); + storage.ensureStorageLayout(); + const uploadedPath = path.join(storage.TEMP_DIR, "upload"); + fs.writeFileSync(uploadedPath, "fake audio content"); + storage.registerUploadedFile( + { path: uploadedPath, originalname: "old.mp3", size: 18, mimetype: "audio/mpeg" }, + { permanent: true, uploader: "test", title: "Old" } + ); + + // libraryMetadata.js importe storageManager.js sans paramètre : on passe par la même + // instance de module que lui, avec le répertoire de travail temporaire. + const { backfillLibraryMetadata } = await import("../src/web/storage/libraryMetadata.js"); + const shared = await import("../src/web/storage/storageManager.js"); + shared.ensureStorageLayout(); + const updated = await backfillLibraryMetadata({ + probe: async () => ({ duration: 42, artist: "Palico", title: null }), + }); + + assert.equal(updated.length, 1); + assert.equal(shared.getPermanentLibrary()[0].duration, 42); + assert.equal(shared.getPermanentLibrary()[0].artist, "Palico"); + } finally { + process.chdir(originalDirectory); + fs.rmSync(temporaryDirectory, { recursive: true, force: true }); + } +}); diff --git a/test/webServer.test.js b/test/webServer.test.js index da68460..d8eb218 100644 --- a/test/webServer.test.js +++ b/test/webServer.test.js @@ -114,3 +114,87 @@ test("only loopback connections count as local", () => { assert.equal(isLoopbackAddress(address), false); } }); + +test("/readyz reports whether the bot is connected to Discord", async () => { + const app = createApp({ queue: fakeQueue, client: { isReady: () => false } }); + const server = app.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + const base = `http://127.0.0.1:${server.address().port}`; + try { + assert.equal((await fetch(`${base}/healthz`)).status, 200); + assert.equal((await fetch(`${base}/readyz`)).status, 503); + } finally { + await new Promise((resolve) => server.close(resolve)); + } +}); + +test("the events stream sends the queue state, then every update", async () => { + const { EventEmitter } = await import("node:events"); + const queue = new EventEmitter(); + let snapshot = { current: null, upcoming: [], status: "idle", loop: false, position: 0 }; + queue.snapshot = () => snapshot; + queue.setLoop = (enabled) => { + snapshot = { ...snapshot, loop: enabled }; + queue.emit("queueUpdate", snapshot); + return snapshot; + }; + + const app = createApp({ queue, client: fakeClient() }); + const server = app.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + const base = `http://127.0.0.1:${server.address().port}`; + const controller = new AbortController(); + try { + const response = await fetch(`${base}/api/events`, { + headers: { authorization: "Bearer web-key" }, + signal: controller.signal, + }); + assert.equal(response.status, 200); + assert.match(response.headers.get("content-type"), /text\/event-stream/); + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + + let received = ""; + const readUntil = async (pattern) => { + while (!pattern.test(received)) { + const { value, done } = await reader.read(); + if (done) break; + received += value; + } + }; + + await readUntil(/event: queue\ndata: .*"loop":false/); + const loopResponse = await fetch(`${base}/api/player/loop`, { + method: "POST", + headers: { authorization: "Bearer web-key", "content-type": "application/json" }, + body: JSON.stringify({ enabled: true }), + }); + assert.equal(loopResponse.status, 200); + await readUntil(/"loop":true/); + assert.match(received, /"loop":true/); + + const invalid = await fetch(`${base}/api/player/loop`, { + method: "POST", + headers: { authorization: "Bearer web-key", "content-type": "application/json" }, + body: JSON.stringify({ enabled: "yes" }), + }); + assert.equal(invalid.status, 400); + + // Le client se déconnecte : le serveur cesse d'écouter la file. + assert.equal(queue.listenerCount("queueUpdate"), 1); + controller.abort(); + for (let attempt = 0; attempt < 50 && queue.listenerCount("queueUpdate") > 0; attempt++) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + assert.equal(queue.listenerCount("queueUpdate"), 0); + } finally { + controller.abort(); + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + } +}); + +test("the events stream requires the jukebox key", async () => { + await withServer({}, async ({ base }) => { + assert.equal((await fetch(`${base}/api/events`)).status, 401); + }); +});