diff --git a/.env.example b/.env.example index 2003a68..4db695b 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,6 @@ +NODE_ENV=test DISCORD_GUILD_ID= -# Personne qui gère les serveurs de jeux, mentionnée dans leur message (ancien nom : SHINUWA_USER_ID). -OWNER_USER_ID= +SHINUWA_USER_ID= WEB_SERVER_PORT=3000 WEB_API_KEY= DISCORD_APPLICATION_ID= @@ -14,11 +14,3 @@ 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 ce694a0..8d9f98d 100644 --- a/.forgejo/workflows/deploy.yml +++ b/.forgejo/workflows/deploy.yml @@ -1,40 +1,22 @@ name: Deploy Palico Bot -# Les contrôles tournent à chaque push, sur toutes les branches (une PR est donc contrôlée par -# le push de sa branche) ; le déploiement, seulement après un push sur main dont les -# contrôles ont réussi. on: push: + branches: + - main jobs: - check: + deploy: 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: DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }} - # Clé d'hôte de la VM (sortie de `ssh-keyscan -p 2911 192.168.0.100`) : sans elle, - # n'importe quelle machine qui répondrait à cette adresse recevrait la connexion. - DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }} run: | # L'image contient déjà le client SSH ; ne l'installer que s'il manque. if ! command -v ssh >/dev/null; then @@ -42,17 +24,11 @@ jobs: apt-get install -y --no-install-recommends openssh-client fi - if [ -z "$DEPLOY_KNOWN_HOSTS" ]; then - echo "Secret DEPLOY_KNOWN_HOSTS manquant (ssh-keyscan -p 2911 192.168.0.100)" >&2 - exit 1 - fi - mkdir -p ~/.ssh printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_ed25519 - printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > ~/.ssh/known_hosts chmod 600 ~/.ssh/id_ed25519 - ssh -o StrictHostKeyChecking=yes \ + ssh -o StrictHostKeyChecking=no \ -i ~/.ssh/id_ed25519 \ -p 2911 \ shinuwa@192.168.0.100 \ diff --git a/.gitignore b/.gitignore index c91a67d..30118f3 100644 --- a/.gitignore +++ b/.gitignore @@ -17,7 +17,6 @@ storage/permanent/* !storage/permanent/.gitkeep storage/temp/* !storage/temp/.gitkeep -storage/covers/ # Operating system files .DS_Store diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 6588332..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,10 +0,0 @@ -# palico-bot - -Bot Discord et jukebox web autohébergé (Node.js, discord.js, Express). Voir -[README.md](README.md) pour la configuration et le déploiement. - -- Validation : `npm run check` (syntaxe et tests) avant de rendre un travail. -- Conventions (langue, en-têtes de fichiers `/** @file … */` en trois niveaux, - feuille de style) : [CONTRIBUTING.md](CONTRIBUTING.md). Un nouveau fichier - reçoit son en-tête dès sa création ; un fichier modifié dont le rôle, les - appelants ou les pièges changent voit son en-tête mis à jour. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 64e0966..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,110 +0,0 @@ -# Contribuer à palico-bot - -## Validation - -```bash -npm run check -``` - -Vérifie la syntaxe de tous les fichiers JavaScript (front compris) puis lance les -tests, dont celui des en-têtes de fichiers (`test/fileHeaders.test.js`). - -## Langue - -- Code (noms de variables, fonctions, fichiers) et journaux du serveur : anglais. -- Commentaires, documentation et textes vus par les utilisateurs (Discord, page - web, erreurs de l'API) : français. - -## En-têtes de fichiers - -Chaque fichier JavaScript (sources, front, scripts et tests) commence par un -en-tête. Il s'adresse à quelqu'un qui ouvre le fichier pour la première fois : -ce que fait le fichier, pourquoi il existe et ce qu'il faut savoir avant de le -modifier. - -### Syntaxe - -- **JavaScript** : bloc JSDoc qui commence par `/**` puis ` * @file`. Le texte - de `@file` est la description ; ses lignes suivantes s'alignent sous le texte - (7 espaces après `*`). Les rubriques viennent après une ligne ` *` vide, et - leurs lignes suivantes sont décalées de 2 espaces. Une ligne vide sépare le - bloc du code. -- **CSS** : commentaire `/* … */` dont la première ligne est ` * Rôle : …`, puis - les mêmes rubriques (`Chargé par`, `Attention`). - -Pas de `@author`, `@version` ni `@since` : Git garde déjà cet historique, et ces -balises se périment. Pas de `@module` (le chemin suffit) ni de `@description` -(doublon du texte de `@file`). - -### Trois niveaux de détail - -**Fichier simple** (commande, route simple, test) : la description seule, en -une ou deux lignes. - -```js -/** - * @file Commande /skip : passe au morceau suivant du jukebox. - */ -``` - -**Fichier partagé** (module de `features/`, `media/`, authentification, -réglages) : la description, puis seulement les rubriques utiles parmi -`Utilisé par`, `Attention` et `@see`. - -```js -/** - * @file Enregistre la file du jukebox dans storage/runtime/queue.json pour la retrouver au redémarrage. - * - * Utilisé par : index.js, qui le passe à MusicQueue (option `persistence`). - * Attention : l'écriture passe par un fichier temporaire renommé, pour ne jamais laisser un JSON à - * moitié écrit ; au chargement, les morceaux dont le fichier a disparu sont ignorés. - */ -``` - -**Fichier central** (point d'entrée, file du jukebox, serveur web, stockage, -script de la page, ou tout fichier de plus de 300 lignes) : gabarit complet. - -```js -/** - * @file - * - * Contexte : - * Points d'entrée : - * Utilisé par : - * Dépend de : - * Attention : - * @see
- */ -``` - -### Ce que vérifie le test - -`test/fileHeaders.test.js` fait échouer `npm run check` quand : - -- un fichier JavaScript ne commence pas par `/**` puis ` * @file` ; -- un fichier de sa liste `CENTRAL_FILES`, ou un fichier source de plus de - 300 lignes, n'a pas `Contexte :`, `Utilisé par :` et `@see` ; -- `public/style/styles.css` ne commence pas par son `Rôle :`. - -Un fichier qui devient central s'ajoute à `CENTRAL_FILES`. Le test ne lit que la -présence des rubriques : leur contenu reste à écrire avec soin. - -### Règles - -- Écrire l'en-tête **après avoir lu le fichier**, jamais d'après son seul nom. -- Expliquer le pourquoi et le contexte, sans paraphraser le code. -- Citer les points d'entrée, pas toutes les fonctions : une liste complète se - périme. -- Omettre une rubrique vide plutôt que d'écrire « aucun ». -- Un commentaire qui explique une déclaration précise reste au-dessus de cette - déclaration, pas dans l'en-tête. -- Mettre l'en-tête à jour quand le rôle, les appelants ou les pièges du fichier - changent. - -## Feuille de style - -`public/style/styles.css` est servie telle quelle, sans compilation (pas de -Sass). Les couleurs viennent des variables de `:root` ; leurs versions -transparentes en dérivent avec `color-mix()` au lieu d'être recopiées en -`rgba()`. Les classes utilitaires (`u-…`, `.grid`) restent en fin de fichier, -pour l'emporter sur les composants. diff --git a/README.md b/README.md index 3d09787..65fd4ed 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,5 @@ # palico-bot -## Prérequis - -- Node.js 22.12 ou supérieur (prise en charge du protocole vocal DAVE de Discord) ; - `.nvmrc` indique la version utilisée pour le développement ; -- FFmpeg et FFprobe disponibles dans le `PATH` ; -- accès UDP sortant vers les serveurs vocaux Discord. - -Sur Debian ou Ubuntu : - -```bash -sudo apt install ffmpeg -npm ci -npm run check -``` - ## Configuration La configuration sensible est stockée dans un fichier `.env` exclu de Git. @@ -38,14 +23,30 @@ npm start npm run deploy ``` +Node.js 22.12 ou supérieur est nécessaire pour la prise en charge du protocole +vocal DAVE de Discord. + +## Prérequis + +- Node.js 24 LTS ; +- FFmpeg et FFprobe disponibles dans le `PATH` ; +- accès UDP sortant vers les serveurs vocaux Discord. + +Sur Debian ou Ubuntu : + +```bash +sudo apt install ffmpeg +npm ci +npm run check +``` + ## Données persistantes 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/sections.json` (sections de - la bibliothèque) et `storage/runtime/queue.json` (la file en cours) ; -- `storage/permanent/` (fichiers audio) et `storage/covers/` (pochettes). +- `storage/runtime/library.json` ; +- `storage/permanent/`. Les fichiers placés dans `storage/temp/` sont temporaires et nettoyés après 24 heures. @@ -56,29 +57,12 @@ 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 -`.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`). - -Secrets du dépôt : `DEPLOY_SSH_KEY` (clé privée de déploiement) et -`DEPLOY_KNOWN_HOSTS`, la clé d'hôte de la VM, vérifiée à la connexion : - -```bash -ssh-keyscan -p 2911 192.168.0.100 -``` - -Supervision : `/healthz` répond dès que le processus tourne ; `/readyz` répond -`503` tant que le bot n'est pas connecté à Discord. +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. Variables facultatives : @@ -91,73 +75,6 @@ Variables facultatives : - `INVITE_LINK` : lien publié par `/invitation` quand la commande ne reçoit pas de lien. -## Jukebox - -La page d'accueil du site (`/`) et les commandes `/play`, `/skip` et `/queue` -pilotent la même file d'attente. L'ancienne adresse `/jukebox/` redirige vers -`/`. - -- `/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 page web range la bibliothèque en sections (chacune peut être ajoutée à - la file d'un coup, mélangée ou non) et donne une image à chaque section et - une pochette à chaque morceau : celle intégrée au fichier est reprise à - l'ajout, et le bouton « Modifier » permet d'en envoyer une autre (PNG, JPEG, - WebP ou GIF), réduite en JPEG de 512 px. Images et pochettes sont servies - sous `/covers/` sans authentification, sous des noms aléatoires que seule - l'API donne. -- Les morceaux de la bibliothèque peuvent recevoir des étiquettes libres - (« épique », « calme »…), sans distinction de majuscules. Choisir une - étiquette au-dessus de la liste filtre la bibliothèque, et les boutons - « Tout ajouter » n'ajoutent alors que ses morceaux. - -- 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. -- Un morceau interrompu malgré lui (connexion vocale perdue, bot parti faute - d'auditeurs, redémarrage, même brutal) reprend 2 secondes avant l'endroit où - il s'était arrêté, au lieu de recommencer. Après un arrêt brutal, il peut - rejouer jusqu'à 30 secondes de plus : la position est enregistrée toutes les - 30 s. -- 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). -- La barre de position du lecteur permet d'avancer ou de reculer dans le - morceau en cours (`POST /api/player/seek`, `{ "position": }`) : - ffmpeg repart de cette position. En pause, la lecture reprend. - -### 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. - -## Commandes - -`/listcommand` affiche les commandes chargées, rangées par dossier de -`src/commands` ; une nouvelle commande y apparaît avec sa description. - -`/muteall`, `/unmuteall`, `/deafall` et `/undeafall` agissent sur le salon vocal -de la personne qui lance la commande, ou sur `VOICE_CHANNEL_ID` si elle n'est -dans aucun salon. - ## Invitations Les membres ne peuvent pas créer d'invitation : un seul lien, à adhésion @@ -179,16 +96,7 @@ que les connexions locales (pas celles relayées par Caddy) et la clé `NOTIFICATIONS_API_KEY` en `Authorization: Bearer …` ; sans cette variable, elle répond `503`. -Corps : `{ "userId": "", "content": "" }`, -plus deux champs facultatifs : - -- `embed` : `{ "title", "description"?, "url"?, "color"?, "thumbnail"?, "fields"?: [{ "name", "value", "inline"? }], "footer"?, "timestamp"? }` - (limites de Discord : titre 256 caractères, description 4096, 25 champs de 256/1024, pied 2048, - 6000 au total ; adresse et vignette en `https` uniquement, couleur entière de `0` à `0xFFFFFF`) ; -- `link` : `{ "label", "url" }`, un bouton de lien sous le message (libellé de 80 caractères au plus, - adresse `https`). - -Le texte reste obligatoire : c'est lui que montre la notification du téléphone. +Corps : `{ "userId": "", "content": "" }`. Réponses : `204` envoyé, `400` corps invalide, `401` mauvaise clé, `403` connexion non locale, `404` utilisateur inconnu (`UNKNOWN_USER`), `422` messages privés impossibles (`DM_CLOSED` : aucun serveur en commun avec le bot, ou messages diff --git a/deployCommands.js b/deployCommands.js index 1d59491..db46678 100644 --- a/deployCommands.js +++ b/deployCommands.js @@ -1,33 +1,55 @@ -/** - * @file Enregistre les commandes slash auprès de Discord pour le serveur configuré (`npm run deploy`), - * à relancer après l'ajout d'une commande ou un changement de ses options. - */ - -import { REST, Routes } from "discord.js"; +import { REST, Routes } from "discord.js"; +import fs from "fs"; +import path from "path"; +import { fileURLToPath } from "url"; import { config } from "./src/config.js"; -import { loadCommands } from "./src/loadCommands.js"; - -const commands = (await loadCommands()).map((command) => command.data.toJSON()); - -const rest = new REST().setToken(config.token); - -(async () => { - try { - console.log( - `Started refreshing ${commands.length} application (/) commands.` - ); - - const data = await rest.put( - Routes.applicationGuildCommands( - config.applicationId, - config.discordGuildId - ), - { body: commands } - ); - - console.log( - `Successfully reloaded ${data.length} application (/) commands.` - ); + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +const commands = []; +const foldersPath = path.join(__dirname, "src/commands"); +const commandFolders = fs.readdirSync(foldersPath); + +for (const folder of commandFolders) { + if (folder.indexOf("[disabled]") === -1 || config.environnement === "test") { + const commandsPath = path.join(foldersPath, folder); + const commandFiles = fs + .readdirSync(commandsPath) + .filter((file) => file.endsWith(".js")); + for (const file of commandFiles) { + const filePath = path.join(commandsPath, file); + const commandFile = await import(filePath); + if ("data" in commandFile.command && "execute" in commandFile.command) { + commands.push(commandFile.command.data.toJSON()); + } else { + console.log( + `[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.` + ); + } + } + } +} + +const rest = new REST().setToken(config.token); + +(async () => { + try { + console.log( + `Started refreshing ${commands.length} application (/) commands.` + ); + + const data = await rest.put( + Routes.applicationGuildCommands( + config.applicationId, + config.discordGuildId + ), + { body: commands } + ); + + console.log( + `Successfully reloaded ${data.length} application (/) commands.` + ); } catch (error) { console.error(error); process.exitCode = 1; diff --git a/index.js b/index.js index 023e7fc..3ee14a5 100644 --- a/index.js +++ b/index.js @@ -1,26 +1,9 @@ -/** - * @file Point d'entrée du bot : connecte le client Discord, branche les commandes et les événements, - * crée la file du jukebox et démarre le serveur web. - * - * Contexte : lancé par `npm start` ; un seul processus sert le bot et le site du jukebox. - * Points d'entrée : exporte `client` et `musicQueue` ; arrêt propre sur SIGTERM et SIGINT. - * Utilisé par : `npm start` (package.json). - * Dépend de : loadCommands.js, src/events/, music/queue.js, music/queuePersistence.js, web/server.js. - * Attention : - * - Les commandes trouvent la file par `interaction.client.musicQueue`. - * - À l'arrêt, les flux en direct des pages ouvertes sont coupés de force : sinon le serveur HTTP - * ne se ferme jamais. - * @see README.md#déploiement - */ - import { Client, Collection, GatewayIntentBits } from "discord.js"; import fs from "fs"; import path from "path"; import { fileURLToPath } from "url"; import { config } from "./src/config.js"; -import { loadCommands } from "./src/loadCommands.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); @@ -30,9 +13,29 @@ const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates], }); -client.commands = new Collection( - (await loadCommands()).map((command) => [command.data.name, command]) -); +client.commands = new Collection(); +const foldersPath = path.join(__dirname, "src/commands"); +const commandFolders = fs.readdirSync(foldersPath); + +for (const folder of commandFolders) { + if (folder.indexOf("[disabled]") === -1 || config.environnement === "test") { + const commandsPath = path.join(foldersPath, folder); + const commandFiles = fs + .readdirSync(commandsPath) + .filter((file) => file.endsWith(".js")); + for (const file of commandFiles) { + const filePath = path.join(commandsPath, file); + const commandFile = await import(filePath); + if ("data" in commandFile.command && "execute" in commandFile.command) { + client.commands.set(commandFile.command.data.name, commandFile); + } else { + console.log( + `[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.` + ); + } + } + } +} const eventsPath = path.join(__dirname, "src/events"); const eventFiles = fs @@ -53,13 +56,7 @@ for (const file of eventFiles) { } } -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; +const musicQueue = new MusicQueue(client); await client.login(config.token); const { server } = startWebServer({ queue: musicQueue, client }); @@ -83,9 +80,6 @@ async function shutdown(signal) { server.close(() => { clearTimeout(forceExit); }); - // close() n'attend que la fin des requêtes en cours : les flux en direct (/api/events) des - // pages jukebox ouvertes ne finissent jamais d'eux-mêmes et bloqueraient l'arrêt. - server.closeAllConnections(); } process.once("SIGTERM", () => void shutdown("SIGTERM")); diff --git a/package-lock.json b/package-lock.json index 75c26f5..4f17970 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,15 +22,15 @@ } }, "node_modules/@discordjs/builders": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.15.0.tgz", - "integrity": "sha512-AifaDWTw6WUDhKBn8E6mwwoyjDAcfsYq+ZE0nKSu1dMH1NLR22D3hGkNx+ctEv8NqHEHdAZnP5REteHDmn1lkA==", + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz", + "integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==", "license": "Apache-2.0", "dependencies": { "@discordjs/formatters": "^0.6.2", "@discordjs/util": "^1.2.0", "@sapphire/shapeshift": "^4.0.0", - "discord-api-types": "^0.38.50", + "discord-api-types": "^0.38.40", "fast-deep-equal": "^3.1.3", "ts-mixer": "^6.0.4", "tslib": "^2.6.3" @@ -67,9 +67,9 @@ } }, "node_modules/@discordjs/rest": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.3.tgz", - "integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==", + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.1.tgz", + "integrity": "sha512-wwQdgjeaoYFiaG+atbqx6aJDpqW7JHAo0HrQkBTbYzM3/PJ3GweQIpgElNcGZ26DCUOXMyawYd0YF7vtr+fZXg==", "license": "Apache-2.0", "dependencies": { "@discordjs/collection": "^2.1.1", @@ -77,10 +77,10 @@ "@sapphire/async-queue": "^1.5.3", "@sapphire/snowflake": "^3.5.5", "@vladfrangu/async_event_emitter": "^2.4.6", - "discord-api-types": "^0.38.50", + "discord-api-types": "^0.38.40", "magic-bytes.js": "^1.13.0", "tslib": "^2.6.3", - "undici": "^6.27.0" + "undici": "6.24.1" }, "engines": { "node": ">=18" @@ -101,6 +101,16 @@ "url": "https://github.com/discordjs/discord.js?sponsor" } }, + "node_modules/@discordjs/rest/node_modules/@sapphire/snowflake": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz", + "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, "node_modules/@discordjs/util": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz", @@ -172,21 +182,21 @@ } }, "node_modules/@emnapi/core": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz", - "integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==", + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz", + "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==", "license": "MIT", "optional": true, "peer": true, "dependencies": { - "@emnapi/wasi-threads": "1.2.3", + "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "node_modules/@emnapi/runtime": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", - "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz", + "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==", "license": "MIT", "optional": true, "peer": true, @@ -195,9 +205,9 @@ } }, "node_modules/@emnapi/wasi-threads": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz", - "integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz", + "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==", "license": "MIT", "optional": true, "peer": true, @@ -206,24 +216,21 @@ } }, "node_modules/@napi-rs/wasm-runtime": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.7.tgz", - "integrity": "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==", + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz", + "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==", "license": "MIT", "optional": true, "dependencies": { "@tybys/wasm-util": "^0.10.3" }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=23.5.0" - }, "funding": { "type": "github", "url": "https://github.com/sponsors/Brooooooklyn" }, "peerDependencies": { - "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", - "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" } }, "node_modules/@sapphire/async-queue": { @@ -250,9 +257,9 @@ } }, "node_modules/@sapphire/snowflake": { - "version": "3.5.5", - "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz", - "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==", + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.3.tgz", + "integrity": "sha512-jjmJywLAFoWeBi1W7994zZyiNWPIiqRRNAmSERxyg93xRGzNYvGjlZ0gR6x0F4gPRi2+0O6S71kOZYyr3cxaIQ==", "license": "MIT", "engines": { "node": ">=v14.0.0", @@ -524,9 +531,9 @@ } }, "node_modules/@tybys/wasm-util": { - "version": "0.10.5", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", - "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz", + "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==", "license": "MIT", "optional": true, "dependencies": { @@ -534,18 +541,18 @@ } }, "node_modules/@types/node": { - "version": "26.6.11", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz", - "integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==", + "version": "24.10.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz", + "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==", "license": "MIT", "dependencies": { - "undici-types": "~8.9.0" + "undici-types": "~7.16.0" } }, "node_modules/@types/ws": { - "version": "8.18.2", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", - "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", "license": "MIT", "dependencies": { "@types/node": "*" @@ -581,18 +588,18 @@ "license": "MIT" }, "node_modules/body-parser": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", - "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", "license": "MIT", "dependencies": { "bytes": "^3.1.2", - "content-type": "^2.1.0", + "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", - "iconv-lite": "^0.7.3", + "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", - "qs": "^6.16.1", + "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" }, @@ -604,6 +611,25 @@ "url": "https://opencollective.com/express" } }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, "node_modules/busboy": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", @@ -653,30 +679,40 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/content-disposition": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", - "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", + "node_modules/concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "engines": [ + "node >= 6.0" + ], "license": "MIT", - "engines": { - "node": ">=18" + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/content-disposition": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz", + "integrity": "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" + "engines": { + "node": ">= 0.6" } }, "node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", "license": "MIT", "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" + "node": ">= 0.6" } }, "node_modules/cookie": { @@ -724,30 +760,33 @@ } }, "node_modules/discord-api-types": { - "version": "0.38.60", - "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.60.tgz", - "integrity": "sha512-2xPScuQP3WOf3H4EKWLzvnhlfNl8sBMD+krT8CcjMVJa6o9D/6ssOSgKPTvHyIhQDKUX+gvUJZ43U4HqE+6tsA==", - "license": "MIT" + "version": "0.38.49", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.49.tgz", + "integrity": "sha512-XnqcWmnFZFAE8ZM8SHAw9DIV8D3Or00rMQ8iQLotrEA2PmXhl+ykaf6L6q4l474hrSUH1JaYcv+iOMRWp2p6Tg==", + "license": "MIT", + "workspaces": [ + "scripts/actions/documentation" + ] }, "node_modules/discord.js": { - "version": "14.28.1", - "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.28.1.tgz", - "integrity": "sha512-Je5OcqgurnIUQK4vR+gQnmzOf/lNQsD6d/UkV8ZOj+bFa5zJXPyiGXlbywp2EagwshVT18y7YNQNSRd3FjYkDw==", + "version": "14.26.4", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.26.4.tgz", + "integrity": "sha512-4oBp8tc6Kf8IDBwAHhbsMaAqx1b5fob9SNasZT7V6yyyUydoO5i5fGuX7TmvRtR+q/WgKRnRViRoAWnG7fNyvA==", "license": "Apache-2.0", "dependencies": { - "@discordjs/builders": "^1.15.0", + "@discordjs/builders": "^1.14.1", "@discordjs/collection": "1.5.3", "@discordjs/formatters": "^0.6.2", - "@discordjs/rest": "^2.6.3", + "@discordjs/rest": "^2.6.1", "@discordjs/util": "^1.2.0", "@discordjs/ws": "^1.2.3", - "@sapphire/snowflake": "3.5.5", - "discord-api-types": "^0.38.50", + "@sapphire/snowflake": "3.5.3", + "discord-api-types": "^0.38.40", "fast-deep-equal": "3.1.3", "lodash.snakecase": "4.1.1", "magic-bytes.js": "^1.13.0", "tslib": "^2.6.3", - "undici": "^6.27.0" + "undici": "6.24.1" }, "engines": { "node": ">=18" @@ -777,16 +816,12 @@ "license": "MIT" }, "node_modules/encodeurl": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", - "integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", "license": "MIT", "engines": { "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" } }, "node_modules/es-define-property": { @@ -835,15 +870,15 @@ } }, "node_modules/express": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", - "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", "license": "MIT", "dependencies": { "accepts": "^2.0.0", - "body-parser": "^2.3.0", - "content-disposition": "^2.0.1", - "content-type": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", @@ -859,14 +894,14 @@ "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", - "proxy-addr": "^2.0.8", - "qs": "^6.16.0", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", - "type-is": "^2.1.0", + "type-is": "^2.0.1", "vary": "^1.1.2" }, "engines": { @@ -878,12 +913,11 @@ } }, "node_modules/express-rate-limit": { - "version": "8.7.5", - "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.5.tgz", - "integrity": "sha512-wi+v38cx2EqD0JnhE/e74o5tFqKWUOAPFJIgyEiqJ8v2MNpoOAA3kI2hXYOI+YM+HE5yqbdAlVxm2GqOIeYOgA==", + "version": "8.5.2", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz", + "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==", "license": "MIT", "dependencies": { - "debug": "^4.4.3", "ip-address": "^10.2.0" }, "engines": { @@ -903,9 +937,9 @@ "license": "MIT" }, "node_modules/finalhandler": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", - "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz", + "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==", "license": "MIT", "dependencies": { "debug": "^4.4.0", @@ -916,11 +950,7 @@ "statuses": "^2.0.1" }, "engines": { - "node": ">= 18.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" + "node": ">= 0.8" } }, "node_modules/forwarded": { @@ -1024,9 +1054,9 @@ } }, "node_modules/helmet": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.3.0.tgz", - "integrity": "sha512-Qgpiaws3Sm30Av8Eah6sjMCZZwjlBu+E68rhpCWBshY1lb09HtLwj5GviX0OyQIn+ulUS0iX0AxN5n3tLZzz1w==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.2.0.tgz", + "integrity": "sha512-DRgTIUgnWcJ62KyarxxziuqYxKGnR6Rgg19BlbucN/dpmJbl1XOit6qvoOX0ZT+HhWe5OUVhU/a1zpGyc1xA0Q==", "license": "MIT", "engines": { "node": ">=18.0.0" @@ -1056,9 +1086,9 @@ } }, "node_modules/iconv-lite": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", - "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -1078,9 +1108,9 @@ "license": "ISC" }, "node_modules/ip-address": { - "version": "10.7.7", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.7.tgz", - "integrity": "sha512-He15rAs4jip5AEAz7XM9L+S6Y8LBMIDj6YewbYuJfmDnOCKWb+3TLOGnHFBTAIW7wpm5ohtZ+Xyo5PEaG+O2vQ==", + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz", + "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==", "license": "MIT", "engines": { "node": ">= 12" @@ -1114,9 +1144,9 @@ "license": "MIT" }, "node_modules/magic-bytes.js": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.1.tgz", - "integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==", + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.0.tgz", + "integrity": "sha512-afO2mnxW7GDTXMm5/AoN1WuOcdoKhtgXjIvHmobqTD1grNplhGdv3PFOyjCVmrnOZBIT/gD/koDKpYG+0mvHcg==", "license": "MIT" }, "node_modules/math-intrinsics": { @@ -1129,16 +1159,12 @@ } }, "node_modules/media-typer": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", - "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", "license": "MIT", "engines": { "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" } }, "node_modules/merge-descriptors": { @@ -1163,19 +1189,15 @@ } }, "node_modules/mime-types": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", - "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", + "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", "license": "MIT", "dependencies": { "mime-db": "^1.54.0" }, "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" + "node": ">= 0.6" } }, "node_modules/ms": { @@ -1185,13 +1207,14 @@ "license": "MIT" }, "node_modules/multer": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/multer/-/multer-2.5.0.tgz", - "integrity": "sha512-BsqOzYGVq49JcW2IzoSAxeKYRevb+dGGPPWleOR8Lrlk4igwxu1/9pwSXlByhCb7MVZDrNJFC0IBP5/O5nLYRw==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.2.0.tgz", + "integrity": "sha512-6rdyFg2kLrMh9Jee7/BMPuV9lEAd7lLW2YUpF9/YxR7njyoUwwQ0ZPh3TaIY50Sw6vlyD2HW3wGOkTS4P79xrQ==", "license": "MIT", "dependencies": { "append-field": "^1.0.0", "busboy": "^1.6.0", + "concat-stream": "^2.0.0", "type-is": "^1.6.18" }, "engines": { @@ -1246,25 +1269,18 @@ } }, "node_modules/negotiator": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", - "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", "license": "MIT", - "dependencies": { - "content-type": "^2.1.0" - }, "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" + "node": ">= 0.6" } }, "node_modules/object-inspect": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz", - "integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==", + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", "license": "MIT", "engines": { "node": ">= 0.4" @@ -1274,19 +1290,15 @@ } }, "node_modules/on-finished": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", - "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", "license": "MIT", "dependencies": { "ee-first": "1.1.1" }, "engines": { "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" } }, "node_modules/once": { @@ -1350,9 +1362,9 @@ } }, "node_modules/proxy-addr": { - "version": "2.0.8", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", - "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", "license": "MIT", "dependencies": { "forwarded": "0.2.0", @@ -1360,16 +1372,12 @@ }, "engines": { "node": ">= 0.10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" } }, "node_modules/qs": { - "version": "6.17.1", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", - "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", + "version": "6.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", "license": "BSD-3-Clause", "dependencies": { "es-define-property": "^1.0.1", @@ -1383,16 +1391,12 @@ } }, "node_modules/range-parser": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", - "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", "license": "MIT", "engines": { "node": ">= 0.6" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" } }, "node_modules/raw-body": { @@ -1410,10 +1414,24 @@ "node": ">= 0.10" } }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/router": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/router/-/router-2.3.0.tgz", - "integrity": "sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", "license": "MIT", "dependencies": { "debug": "^4.4.0", @@ -1424,12 +1442,28 @@ }, "engines": { "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" } }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", @@ -1437,35 +1471,31 @@ "license": "MIT" }, "node_modules/send": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", - "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", + "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", "license": "MIT", "dependencies": { - "debug": "^4.4.3", + "debug": "^4.3.5", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", - "http-errors": "^2.0.1", - "mime-types": "^3.0.2", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", - "statuses": "^2.0.2" + "statuses": "^2.0.1" }, "engines": { "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" } }, "node_modules/serve-static": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", - "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", "license": "MIT", "dependencies": { "encodeurl": "^2.0.0", @@ -1475,10 +1505,6 @@ }, "engines": { "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" } }, "node_modules/setprototypeof": { @@ -1576,6 +1602,15 @@ "node": ">=10.0.0" } }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/toidentifier": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", @@ -1592,9 +1627,9 @@ "license": "MIT" }, "node_modules/tslib": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", - "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, "node_modules/type-is": { @@ -1615,19 +1650,38 @@ "url": "https://opencollective.com/express" } }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, "node_modules/undici": { - "version": "6.29.1", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz", - "integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==", + "version": "6.27.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.27.0.tgz", + "integrity": "sha512-YmfV3YnEDzXRC5lZ2jWtWWHKGUm1zIt8AhesR1tens+HTNv+YZlN/dp6G727LOvMJ8xjP9Be7Y2Sdr96LDm+pg==", "license": "MIT", "engines": { "node": ">=18.17" } }, "node_modules/undici-types": { - "version": "8.9.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", - "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", "license": "MIT" }, "node_modules/unpipe": { @@ -1639,6 +1693,12 @@ "node": ">= 0.8" } }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", @@ -1655,9 +1715,9 @@ "license": "ISC" }, "node_modules/ws": { - "version": "8.23.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.1.tgz", - "integrity": "sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA==", + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", "license": "MIT", "engines": { "node": ">=10.0.0" diff --git a/public/img/apple-touch-icon.png b/public/img/apple-touch-icon.png deleted file mode 100644 index 81014dc..0000000 Binary files a/public/img/apple-touch-icon.png and /dev/null differ diff --git a/public/img/favicon.png b/public/img/favicon.png deleted file mode 100644 index 6efd069..0000000 Binary files a/public/img/favicon.png and /dev/null differ diff --git a/public/img/favicon.svg b/public/img/favicon.svg deleted file mode 100644 index 1d7500f..0000000 --- a/public/img/favicon.svg +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/public/img/palico-index.png b/public/img/palico-index.png new file mode 100644 index 0000000..dc389a7 Binary files /dev/null and b/public/img/palico-index.png differ diff --git a/public/img/palico-index.webp b/public/img/palico-index.webp deleted file mode 100644 index 567eabc..0000000 Binary files a/public/img/palico-index.webp and /dev/null differ diff --git a/public/img/palico-jukebox.png b/public/img/palico-jukebox.png new file mode 100644 index 0000000..3196cab Binary files /dev/null and b/public/img/palico-jukebox.png differ diff --git a/public/img/palico-jukebox.webp b/public/img/palico-jukebox.webp deleted file mode 100644 index 6451a0f..0000000 Binary files a/public/img/palico-jukebox.webp and /dev/null differ diff --git a/public/index.html b/public/index.html index a925193..9739f4c 100644 --- a/public/index.html +++ b/public/index.html @@ -2,277 +2,36 @@ - Palico Jukebox + Palico Bot - - - - - -
-
- - - Palico Jukebox - - - +
+
+ Palico Bot
-
- - - -
- - - -
-
-
-
-

Bibliothèque

-

Les morceaux conservés, rangés en sections.

-
- -
-
- - -
- - - -
-
- -
-

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. -

- -
- - -
- - - -
- - - - - - -
- -
-
- -
    - -
    - -
    - - -
    -

    YouTube et Spotify ne sont pas pris en charge.

    -
    -
    -
    -
    - - - - - - -
    -

    Modifier le morceau

    - -
    - -
    - - -

    PNG, JPEG, WebP ou GIF, 10 Mo au plus. Réduite à 512 px.

    - -
    +
    +
    + - - - - -
    - - -
    - -
    - - -

    Sépare-les par des virgules. Clique sur une étiquette existante pour l'ajouter.

    -
    -
    - -
    - - -
    - -
    - - +
    + diff --git a/public/jukebox.html b/public/jukebox.html new file mode 100644 index 0000000..b7990d7 --- /dev/null +++ b/public/jukebox.html @@ -0,0 +1,182 @@ + + + + + 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 !
    +
    + Uploade des fichiers et gère la playlist depuis cette interface web. + Tout est synchronisé avec le salon vocal. +

    +
    + + +
    +
    + +
    +
    +

    Authentification

    +

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

    +
    +
    +
    + + +
    +
    + + +
    +
    +
    + +
    +
    +
    +
    +
    + +
    + + +
    +
    +
    +

    Lecture en cours

    +

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

    +
    + +
    +
    + En attente de lecture... +
    +
    + + + + +
    +
    + +
    +
    +
    +

    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

        +

        + Formats audio supportés par FFmpeg. Les fichiers temporaires sont + supprimés automatiquement après lecture. +

        +
        +
        Drag & drop supporté
        +
        +
        + + + + + + +
        + + +
        + + +
        +
        +
        + +
        + +
        + + + + diff --git a/public/scripts/common.js b/public/scripts/common.js index b459a5b..bf328bb 100644 --- a/public/scripts/common.js +++ b/public/scripts/common.js @@ -1,61 +1,20 @@ -/** - * @file Outils de la page du jukebox indépendants de son affichage : mémoire du mot de passe et du nom, - * messages d'état, échappement HTML, formats de taille, durée et date, client de l'API. - * - * Utilisé par : public/scripts/jukebox.js. - * Attention : chargé tel quel par le navigateur (module ES, sans compilation). Le texte venu de l'API - * passe par escapeHtml avant d'être inséré en HTML. - */ - const API_KEY_STORAGE_KEY = "palico-api-key"; const DISPLAY_NAME_STORAGE_KEY = "palico-display-name"; -// 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; - } -} - -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) || - "" - ); + return sessionStorage.getItem(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 setStoredApiKey(value) { + sessionStorage.setItem(API_KEY_STORAGE_KEY, value || ""); } export function getStoredDisplayName() { - return storageGet(localStorage, DISPLAY_NAME_STORAGE_KEY) || ""; + return localStorage.getItem(DISPLAY_NAME_STORAGE_KEY) || ""; } export function setStoredDisplayName(value) { - storageSet(localStorage, DISPLAY_NAME_STORAGE_KEY, value); + localStorage.setItem(DISPLAY_NAME_STORAGE_KEY, value || ""); } export function createStatusManager(statusElement) { @@ -64,8 +23,7 @@ export function createStatusManager(statusElement) { function setStatus(message, type = "info", autoHide = true) { if (!statusElement) return; statusElement.textContent = message; - // Le type (info, success, error) passe par un attribut : la classe reste celle de la page. - statusElement.dataset.type = type; + statusElement.className = `status status--${type}`; statusElement.hidden = false; if (autoHide) { @@ -103,37 +61,13 @@ 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}`; -} - -// Date courte en français, sans les secondes : « 2 déc. 2026, 11:24 ». -const DATE_FORMAT = new Intl.DateTimeFormat("fr-FR", { dateStyle: "medium", timeStyle: "short" }); - -// Date seule : « 2 déc. 2026 ». -const DAY_FORMAT = new Intl.DateTimeFormat("fr-FR", { dateStyle: "medium" }); - -function formatWith(format, value) { - if (!value) return "?"; - const date = new Date(value); - return Number.isNaN(date.getTime()) ? String(value) : format.format(date); -} - export function formatDate(value) { - return formatWith(DATE_FORMAT, value); -} - -export function formatDay(value) { - return formatWith(DAY_FORMAT, value); + if (!value) return "?"; + try { + return new Date(value).toLocaleString(); + } catch (_) { + return value; + } } export function createApiClient({ getApiKey, basePath = "" } = {}) { diff --git a/public/scripts/jukebox.js b/public/scripts/jukebox.js index 5fe8ebb..51f0342 100644 --- a/public/scripts/jukebox.js +++ b/public/scripts/jukebox.js @@ -1,1386 +1,357 @@ -/** - * @file Page du jukebox (page d'accueil du site) : écran de connexion (Discord ou mot de passe), puis - * lecteur (position réglable), file d'attente, bibliothèque (sections, pochettes, étiquettes) - * et ajout de morceaux. - * - * Contexte : servi tel quel au navigateur (module ES, sans compilation) ; ne parle qu'à l'API de - * src/web/. - * Points d'entrée : initialize (au chargement), connectEvents (flux en direct), refreshAll. - * Utilisé par : public/index.html. - * Dépend de : common.js, et des identifiants des éléments de index.html (objet `elements`). - * Attention : - * - Sans session ni mot de passe, seul l'écran de connexion (#welcome) est affiché ; l'application - * (#app) n'apparaît qu'ensuite. Un mot de passe refusé ramène à l'écran de connexion. - * - Les icônes sont des SVG insérés par icon() : un élément porteur de data-icon reçoit la sienne - * au chargement ; le bouton lecture/pause change d'icône selon l'état. - * - Pendant qu'on fait glisser le curseur de position (state.seeking), l'état reçu ne le déplace - * pas ; la nouvelle position part au serveur quand on le lâche. - * - L'état arrive par le flux /api/events ; tant qu'il est coupé, chaque action recharge tout. - * - Le flux est lu avec fetch, et non EventSource, qui ne permet pas d'envoyer la clé. - * - Connecté avec Discord, la session (cookie) remplace la clé : pas d'en-tête Authorization. - * - Tout texte venu de l'API passe par escapeHtml avant d'aller dans innerHTML. - * - Les morceaux de la file n'ont pas de pochette : elle est prise sur leur morceau de bibliothèque - * (libraryTrackId), d'où le nouvel affichage de la file à chaque changement de la bibliothèque. - * - Le filtre par étiquette (state.activeTag) vaut aussi pour les boutons « Tout ajouter » : seuls - * les morceaux affichés partent dans la file. La recherche, elle, n'agit que sur l'affichage. - * - L'aperçu d'une pochette choisie passe par une URL data: ; la politique de sécurité des contenus - * (helmet) refuse les URL blob:. - * @see README.md#jukebox - */ - import { createApiClient, createStatusManager, escapeHtml, - formatBytes, - formatDay, - formatDuration, getStoredApiKey, getStoredDisplayName, - isApiKeyRemembered, + formatBytes, + formatDate, setStoredApiKey, setStoredDisplayName, } from "./common.js"; -const LOGIN_ERRORS = { - denied: "Connexion annulée.", - state: "La connexion a expiré, réessaie.", - "not-member": "Ce compte Discord ne fait pas partie du serveur.", - failed: "La connexion avec Discord a échoué, réessaie.", -}; - const state = { apiKey: getStoredApiKey(), displayName: getStoredDisplayName(), - oauthEnabled: false, - user: null, queue: [], current: null, library: [], - libraryById: new Map(), - sections: [], - // Sections repliées par la personne ("" : les morceaux sans section). - collapsedSections: new Set(), - // Étiquette choisie pour filtrer la bibliothèque, ou null. - activeTag: null, status: "idle", - loop: false, - // Position du morceau en cours (ms) au moment où l'état a été reçu. - position: 0, - positionReceivedAt: 0, - // Curseur de position tenu par la personne : l'état reçu ne doit pas le déplacer. - seeking: false, - live: false, }; -const $ = (id) => document.getElementById(id); const elements = { - status: $("status"), - loggedIn: $("loggedIn"), - userName: $("userName"), - logoutBtn: $("logoutBtn"), - discordLogin: $("discordLogin"), - keyLogin: $("keyLogin"), - keyLoginSummary: $("keyLoginSummary"), - apiKeyInput: $("apiKey"), - rememberKeyCheckbox: $("rememberKey"), - displayNameInput: $("displayName"), - settingsForm: $("settingsForm"), - welcome: $("welcome"), - app: $("app"), - liveIndicator: $("liveIndicator"), - playerSection: $("playerSection"), - currentTrack: $("currentTrack"), - progress: $("progress"), - seekInput: $("seekInput"), - progressElapsed: $("progressElapsed"), - progressTotal: $("progressTotal"), - playPauseButtons: document.querySelectorAll(".js-play-pause"), - loopBtn: $("loopBtn"), - miniPlayer: $("miniPlayer"), - miniPlayerInfo: $("miniPlayerInfo"), - miniPlayerCover: $("miniPlayerCover"), - miniPlayerTitle: $("miniPlayerTitle"), - miniProgressBar: $("miniProgressBar"), + 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"), playerButtons: document.querySelectorAll("[data-player-action]"), - queueList: $("queueList"), - queueEmpty: $("queueEmpty"), - queueSummary: $("queueSummary"), - libraryList: $("libraryList"), - libraryEmpty: $("libraryEmpty"), - librarySearch: $("librarySearch"), - libraryTags: $("libraryTags"), - newSectionBtn: $("newSectionBtn"), - enqueueAllBtn: $("enqueueAllBtn"), - enqueueAllShuffledBtn: $("enqueueAllShuffledBtn"), - uploadSection: $("uploadSection"), - goToUploadBtn: $("goToUploadBtn"), - uploadForm: $("uploadForm"), - uploadSubmitBtn: document.querySelector("#uploadForm button[type='submit']"), - fileInput: $("musicFile"), - dropzoneText: $("dropzoneText"), - notesInput: $("uploadNotes"), - permanentCheckbox: $("permanentFile"), - enqueueCheckbox: $("enqueueFile"), - uploadSectionField: $("uploadSectionField"), - uploadSectionSelect: $("uploadSectionSelect"), - uploadList: $("uploadList"), - urlForm: $("urlForm"), - urlInput: $("musicUrl"), - urlSubmitBtn: document.querySelector("#urlForm button[type='submit']"), - editDialog: $("editDialog"), - editDialogTitle: $("editDialogTitle"), - editForm: $("editForm"), - editCoverPreview: $("editCoverPreview"), - editCoverLabel: $("editCoverLabel"), - editCoverInput: $("editCoverInput"), - editCoverRemoveBtn: $("editCoverRemoveBtn"), - editNameLabel: $("editNameLabel"), - editNameInput: $("editNameInput"), - editSectionField: $("editSectionField"), - editSectionSelect: $("editSectionSelect"), - editTagsField: $("editTagsField"), - editTagsInput: $("editTagsInput"), - editTagSuggestions: $("editTagSuggestions"), - editCancelBtn: $("editCancelBtn"), - editSaveBtn: $("editSaveBtn"), + heroUploadBtn: document.getElementById("heroUploadBtn"), + heroQueueBtn: document.getElementById("heroQueueBtn"), + uploadSection: document.getElementById("uploadSection"), + queueSection: document.getElementById("queueSection"), + backHomeBtn: document.getElementById("backHomeBtn"), }; +let pollIntervalId = null; +let refreshPromise = null; + const { setStatus, clearStatus } = createStatusManager(elements.status); +const apiFetch = createApiClient({ + basePath: "/api", + getApiKey: () => state.apiKey, +}); -// 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"; - -// --------------------------------------------------------------------------- -// Icônes (SVG 24×24) : tracés pleins (fill) ou au trait. - -const ICONS = { - play: { fill: true, d: "M8 5.5v13a1 1 0 0 0 1.5.86l10.5-6.5a1 1 0 0 0 0-1.72L9.5 4.64A1 1 0 0 0 8 5.5z" }, - pause: { fill: true, d: "M7 5h3.5v14H7zM13.5 5H17v14h-3.5z" }, - next: { fill: true, d: "M5 5.5v13a1 1 0 0 0 1.5.86L15 13.6V18h2.5V6H15v4.4L6.5 4.64A1 1 0 0 0 5 5.5z" }, - shuffle: { d: "M16 3h5v5M4 20 21 3M21 16v5h-5M15 15l6 6M4 4l5 5" }, - loop: { d: "M17 2l4 4-4 4M3 11V9a3 3 0 0 1 3-3h15M7 22l-4-4 4-4M21 13v2a3 3 0 0 1-3 3H3" }, - plus: { d: "M12 5v14M5 12h14" }, - edit: { d: "M12 20h9M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z" }, - trash: { d: "M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6M10 11v5M14 11v5" }, - up: { d: "m18 15-6-6-6 6" }, - down: { d: "m6 9 6 6 6-6" }, - close: { d: "M18 6 6 18M6 6l12 12" }, - upload: { d: "M12 15V3M7 8l5-5 5 5M5 21h14" }, -}; - -function icon(name) { - const { fill = false, d } = ICONS[name]; - return ``; -} - -// Bouton rond à icône seule : son nom passe par aria-label et l'infobulle. -function iconButton(name, label, { action, extraClass = "", disabled = false } = {}) { - return ``; -} - -// Éléments de la page à icône : data-icon (icône seule) ou data-icon-before (devant le texte). -function renderStaticIcons() { - document.querySelectorAll("[data-icon]").forEach((element) => { - element.innerHTML = icon(element.dataset.icon); - }); - document.querySelectorAll("[data-icon-before]").forEach((element) => { - element.insertAdjacentHTML("afterbegin", icon(element.dataset.iconBefore)); - }); -} - -// --------------------------------------------------------------------------- -// 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; - }); +function refreshAll(options = {}) { + if (refreshPromise) { return refreshPromise; } - followUpRefresh ??= refreshPromise.then(() => { - followUpRefresh = null; - return refreshAll(); + + refreshPromise = performRefresh(options).finally(() => { + refreshPromise = null; }); - return followUpRefresh; + return refreshPromise; } -async function performRefresh() { - if (!canUseApi()) return; +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(); + } + try { const [queueData, libraryData] = await Promise.all([ apiFetch("/queue"), apiFetch("/library"), ]); - applySnapshot(queueData); - applyLibrary(libraryData); + + state.current = queueData.current; + state.queue = queueData.upcoming || []; + state.library = libraryData.tracks || []; + state.status = queueData.status || "idle"; + + renderCurrentTrack(); + renderQueue(); + renderLibrary(); + updatePauseResumeButton(); } catch (error) { - handleApiError(error); - } -} - -async function refreshLibrary() { - try { - applyLibrary(await apiFetch("/library")); - } catch (error) { - handleApiError(error); - } -} - -// Après une action : le flux en direct apporte le nouvel état ; sans lui, on recharge. -function afterAction() { - if (!state.live) { - return refreshAll(); - } - return null; -} - -function handleApiError(error) { - if (error.status === 401) { - stopEvents(); - if (state.user) { - state.user = null; - renderAuth(); - setStatus("Session expirée, reconnecte-toi.", "error", false); - } else { - // Inutile d'insister : chaque échec compte dans la limite anti-force brute du serveur. Le - // mot de passe reste dans le champ, pour le corriger. - state.apiKey = ""; - renderAuth(); - setStatus("Mot de passe refusé, vérifie-le puis réessaie.", "error", false); - } - return; - } - setStatus(`Erreur : ${error.message}`, "error", false); -} - -function applySnapshot(snapshot) { - state.current = snapshot.current; - state.queue = snapshot.upcoming || []; - state.status = snapshot.status || "idle"; - state.loop = Boolean(snapshot.loop); - state.position = Number(snapshot.position) || 0; - state.positionReceivedAt = performance.now(); - renderCurrentTrack(); - renderQueue(); - renderControls(); - renderProgress(); -} - -function applyLibrary({ tracks = [], sections = [] }) { - state.library = tracks; - state.libraryById = new Map(tracks.map((track) => [track.id, track])); - state.sections = sections; - renderLibrary(); - renderSectionChoices(); - renderCurrentTrack(); - renderQueue(); -} - -// --------------------------------------------------------------------------- -// Flux d'événements en direct (Server-Sent Events lus avec fetch, pour pouvoir envoyer la clé) - -let eventsController = null; -let eventsRetryDelay = 1_000; -let eventsRetryTimeout = null; - -function setLive(live) { - state.live = live; - elements.liveIndicator.dataset.live = String(live); - elements.liveIndicator.textContent = live ? "En direct" : "Hors ligne"; -} - -function stopEvents() { - clearTimeout(eventsRetryTimeout); - eventsController?.abort(); - eventsController = null; - setLive(false); -} - -function scheduleEventsReconnect() { - clearTimeout(eventsRetryTimeout); - eventsRetryTimeout = setTimeout(connectEvents, eventsRetryDelay); - eventsRetryDelay = Math.min(eventsRetryDelay * 2, 30_000); -} - -function handleServerEvent(raw) { - let event = "message"; - const data = []; - for (const line of raw.split("\n")) { - if (line.startsWith("event:")) event = line.slice(6).trim(); - else if (line.startsWith("data:")) data.push(line.slice(5).trim()); - } - if (event === "queue" && data.length) { - applySnapshot(JSON.parse(data.join("\n"))); - } else if (event === "library") { - void refreshLibrary(); - } -} - -async function connectEvents() { - stopEvents(); - if (!canUseApi()) return; - - const controller = new AbortController(); - eventsController = controller; - try { - const key = apiKeyForRequests(); - const response = await fetch("/api/events", { - headers: key ? { Authorization: `Bearer ${key}` } : {}, - cache: "no-store", - signal: controller.signal, - }); - if (response.status === 401) { - handleApiError(Object.assign(new Error("Unauthorized"), { status: 401 })); + 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; } - 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(); + setStatus(`Erreur: ${error.message}`, "error", false); } } -// --------------------------------------------------------------------------- -// Affichage - -// Pochette d'un morceau : la sienne (bibliothèque), sinon celle de son morceau de bibliothèque. -function coverUrlOf(track) { - return track.coverUrl ?? state.libraryById.get(track.libraryTrackId)?.coverUrl ?? null; -} - -// Les adresses viennent du serveur (/covers/) mais passent quand même par escapeHtml. -function coverHtml(url, modifier = "") { - const className = `cover ${modifier}`.trim(); - return url - ? `` - : ``; -} - -// Détails d'un morceau de la file. Le morceau en cours n'affiche pas sa position de reprise : elle -// est aussi celle d'un déplacement dans le morceau, et la barre de position la montre déjà. -function trackMeta(track, { queued = true } = {}) { - const parts = []; - const duration = formatDuration(track.duration); - if (duration && queued) parts.push(duration); - // Morceau interrompu (connexion perdue, redémarrage) : il reprend à cette position. - if (queued && track.resumeAt > 0) parts.push(`reprise à ${formatDuration(track.resumeAt)}`); - if (!track.permanent) parts.push("temporaire"); - parts.push(`ajouté par ${escapeHtml(track.uploader || "inconnu")}`); - const text = parts.join(" • "); - return text.charAt(0).toUpperCase() + text.slice(1); -} - -const trackTitle = (track) => escapeHtml(track.title || track.originalName); - function renderCurrentTrack() { - const track = state.current; - if (!track) { - elements.currentTrack.classList.add("player__track--empty"); - elements.currentTrack.textContent = - state.queue.length > 0 - ? "File en attente : appuie sur lecture ou rejoins le salon vocal." - : "Rien en cours. Ajoute un morceau depuis la bibliothèque."; - } else { - elements.currentTrack.classList.remove("player__track--empty"); - elements.currentTrack.innerHTML = ` - ${coverHtml(coverUrlOf(track), "cover--large")} -
        -
        ${trackTitle(track)}
        -
        ${trackMeta(track, { queued: false })}
        -
        - `; - } - renderMiniPlayer(); -} - -// Mini-lecteur des petits écrans : affiché pendant une lecture, quand le lecteur est hors de vue. -let playerInView = true; - -function renderMiniPlayer() { - const track = state.current; - const visible = Boolean(track) && !playerInView && canUseApi(); - elements.miniPlayer.hidden = !visible; - document.body.classList.toggle("has-mini-player", visible); - if (!track) return; - elements.miniPlayerCover.innerHTML = coverHtml(coverUrlOf(track)); - elements.miniPlayerTitle.innerHTML = trackTitle(track); -} - -function currentPosition() { - const elapsed = - state.status === "playing" ? performance.now() - state.positionReceivedAt : 0; - return state.position + elapsed; -} - -// Partie jouée du curseur : peinte par la feuille de style d'après --progress. -function paintSeek(seconds, duration) { - const percent = duration ? Math.min(100, (seconds / duration) * 100) : 0; - elements.seekInput.style.setProperty("--progress", `${percent}%`); - elements.seekInput.setAttribute("aria-valuetext", `${formatDuration(seconds)} sur ${formatDuration(duration)}`); - elements.progressElapsed.textContent = formatDuration(seconds); - return percent; -} - -function renderProgress() { - const duration = state.current?.duration; - if (!state.current || !duration) { - elements.progress.hidden = true; - elements.miniProgressBar.style.width = "0"; + if (!elements.currentTrack) return; + if (!state.current) { + elements.currentTrack.classList.add("player-current--empty"); + elements.currentTrack.innerHTML = "En attente de lecture..."; return; } - elements.progress.hidden = false; - elements.progressTotal.textContent = formatDuration(duration); - elements.seekInput.max = String(Math.floor(duration)); - if (state.seeking) return; - const seconds = Math.min(currentPosition() / 1000, duration); - elements.seekInput.value = String(Math.floor(seconds)); - const percent = paintSeek(seconds, duration); - elements.miniProgressBar.style.width = `${percent}%`; -} -// Envoie la position choisie au curseur. Les flèches du clavier en envoient une par appui : on -// attend un court instant pour n'envoyer que la dernière. -let seekTimeout = null; - -function previewSeek() { - state.seeking = true; - paintSeek(Number(elements.seekInput.value), state.current?.duration); -} - -function commitSeek() { - clearTimeout(seekTimeout); - seekTimeout = setTimeout(async () => { - const position = Number(elements.seekInput.value); - try { - applySnapshot(await apiFetch("/player/seek", { method: "POST", body: { position } })); - } catch (error) { - setStatus(`Impossible de changer de position : ${error.message}`, "error"); - } finally { - state.seeking = false; - renderProgress(); - } - }, 250); + 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)}
        + `; } function renderQueue() { - elements.queueList.replaceChildren(); - const hasTracks = state.queue.length > 0; - elements.queueEmpty.hidden = hasTracks; - elements.queueSummary.hidden = !hasTracks; + if (!elements.queueList) return; + elements.queueList.innerHTML = ""; - 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}`; + if (!state.queue || state.queue.length === 0) { + elements.queueEmpty.style.display = "block"; + return; } + elements.queueEmpty.style.display = "none"; + 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 = ` - ${coverHtml(coverUrlOf(track))}
        -
        ${index + 1}.${trackTitle(track)}
        -
        ${trackMeta(track)}
        +
        ${escapeHtml(track.title || track.originalName)}
        +
        + ${permanence} • ${formatBytes(track.size)} • Ajouté par ${escapeHtml( + track.uploader || "inconnu" + )} +
        - ${iconButton("up", "Monter", { disabled: index === 0 })} - ${iconButton("down", "Descendre", { disabled: index === state.queue.length - 1 })} - ${iconButton("close", "Retirer de la file", { action: "remove", extraClass: "icon-btn--danger" })} + + +
        `; - li.querySelectorAll("button").forEach((button) => { - button.addEventListener("click", () => - handleQueueAction(button.dataset.action, track.id, index, button) - ); + + 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); + }); }); + elements.queueList.appendChild(li); }); } -// Groupes de la bibliothèque, dans l'ordre des sections ; « Sans section » en dernier. -function libraryGroups() { - const groups = state.sections.map((section) => ({ section, tracks: [] })); - const bySection = new Map(groups.map((group) => [group.section.id, group])); - const unsorted = { section: null, tracks: [] }; - for (const track of state.library) { - (bySection.get(track.sectionId) ?? unsorted).tracks.push(track); - } - return [...groups, unsorted]; -} - -// Étiquettes : « Calme » et « calme » sont la même (comme sur le serveur, features/tags.js). -const tagKey = (tag) => tag.toLocaleLowerCase("fr"); -const trackHasTag = (track, tag) => (track.tags ?? []).some((item) => tagKey(item) === tagKey(tag)); - -// Étiquettes de la bibliothèque, par ordre alphabétique, avec leur nombre de morceaux. -function libraryTags() { - const tags = new Map(); - for (const track of state.library) { - for (const tag of track.tags ?? []) { - const entry = tags.get(tagKey(tag)) ?? { label: tag, count: 0 }; - entry.count += 1; - tags.set(tagKey(tag), entry); - } - } - return [...tags.values()].sort((a, b) => a.label.localeCompare(b.label, "fr")); -} - -function setActiveTag(tag) { - state.activeTag = tag && state.activeTag && tagKey(tag) === tagKey(state.activeTag) ? null : tag; - renderLibrary(); -} - -function tagButton(tag, { pressed = false, count } = {}) { - const button = document.createElement("button"); - button.type = "button"; - button.className = "tag"; - button.textContent = tag; - if (count !== undefined) { - const badge = document.createElement("span"); - badge.className = "tag__count"; - badge.textContent = String(count); - button.append(badge); - } - button.setAttribute("aria-pressed", String(pressed)); - button.addEventListener("click", () => setActiveTag(tag)); - return button; -} - -function renderTagFilter() { - const tags = libraryTags(); - if (state.activeTag && !tags.some(({ label }) => tagKey(label) === tagKey(state.activeTag))) { - state.activeTag = null; - } - elements.libraryTags.hidden = tags.length === 0; - elements.libraryTags.replaceChildren( - ...tags.map(({ label, count }) => - tagButton(label, { - count, - pressed: Boolean(state.activeTag) && tagKey(label) === tagKey(state.activeTag), - }) - ) - ); -} - function renderLibrary() { - renderTagFilter(); - const query = elements.librarySearch.value.trim().toLowerCase(); - const tag = state.activeTag; - const matches = (track) => - (!tag || trackHasTag(track, tag)) && - `${track.title || ""} ${track.originalName || ""} ${track.artist || ""} ${(track.tags ?? []).join(" ")}` - .toLowerCase() - .includes(query); - const matchCount = state.library.filter(matches).length; - const filtering = Boolean(query || tag); + if (!elements.libraryList) return; + elements.libraryList.innerHTML = ""; - elements.libraryList.replaceChildren(); - const isEmpty = state.library.length === 0 && state.sections.length === 0; - elements.libraryEmpty.hidden = !isEmpty && (matchCount > 0 || !filtering); - elements.libraryEmpty.textContent = isEmpty - ? "Aucun fichier permanent enregistré." - : "Aucun morceau ne correspond à la recherche."; - // Avec une étiquette choisie, les boutons n'ajoutent que ses morceaux. - const taggedCount = tag ? state.library.filter((track) => trackHasTag(track, tag)).length : 0; - elements.enqueueAllBtn.textContent = tag ? `Ajouter « ${tag} »` : "Tout ajouter"; - elements.enqueueAllShuffledBtn.textContent = tag - ? `Ajouter « ${tag} », mélangé` - : "Tout ajouter, mélangé"; - elements.enqueueAllBtn.disabled = (tag ? taggedCount : state.library.length) === 0; - elements.enqueueAllShuffledBtn.disabled = elements.enqueueAllBtn.disabled; - - // Sans section créée, la bibliothèque reste une simple liste. - if (state.sections.length === 0) { - elements.libraryList.append(renderTrackList(state.library.filter(matches))); + if (!state.library || state.library.length === 0) { + elements.libraryEmpty.style.display = "block"; return; } - const groups = libraryGroups(); - groups.forEach((group, index) => { - const shown = group.tracks.filter(matches); - if (shown.length === 0 && (filtering || !group.section)) return; - elements.libraryList.append( - renderSection(group, shown, { - index, - last: state.sections.length - 1, - searching: filtering, - }) - ); - }); -} + elements.libraryEmpty.style.display = "none"; -function renderSection({ section, tracks }, shown, { index, last, searching }) { - const key = section?.id ?? ""; - const details = document.createElement("details"); - details.className = "library-section"; - details.open = searching || !state.collapsedSections.has(key); - details.addEventListener("toggle", () => { - if (searching) return; - if (details.open) state.collapsedSections.delete(key); - else state.collapsedSections.add(key); - }); - - const total = tracks.reduce((sum, track) => sum + (track.duration || 0), 0); - const count = searching ? `${shown.length} sur ${tracks.length}` : String(tracks.length); - // Avec une étiquette choisie, « Tout ajouter » n'ajoute que les morceaux qui la portent. - const addable = state.activeTag - ? tracks.filter((track) => trackHasTag(track, state.activeTag)).length - : tracks.length; - const disabledIfEmpty = addable === 0 ? "disabled" : ""; - details.innerHTML = ` - - ${section?.coverUrl ? `` : ""} - - ${escapeHtml(section?.name ?? "Sans section")} - - ${count} morceau(x)${total ? ` • ${formatDuration(total)}` : ""} - - - -
        - - - ${ - section - ? ` - ${iconButton("edit", "Modifier la section")} - ${iconButton("up", "Monter la section", { disabled: index === 0 })} - ${iconButton("down", "Descendre la section", { disabled: index === last })} - ${iconButton("trash", "Supprimer la section", { action: "delete", extraClass: "icon-btn--danger" })} - ` - : "" - } -
        - `; - details.querySelectorAll(".library-section__toolbar button").forEach((button) => { - button.addEventListener("click", () => - handleSectionAction(button.dataset.action, section, index, button) - ); - }); - - if (tracks.length === 0) { - const empty = document.createElement("p"); - empty.className = "hint library-section__empty"; - empty.textContent = "Aucun morceau dans cette section : choisis-la avec « Modifier » sur un morceau."; - details.append(empty); - } else { - details.append(renderTrackList(shown)); - } - return details; -} - -function renderTrackList(tracks) { - const list = document.createElement("ul"); - list.className = "list list--stack"; - for (const track of tracks) { + state.library.forEach((track) => { const li = document.createElement("li"); li.className = "media-item media-item--library"; - const duration = formatDuration(track.duration); li.innerHTML = ` - ${coverHtml(track.coverUrl)}
        -
        ${trackTitle(track)}
        +
        ${escapeHtml(track.originalName)}
        - ${duration ? `${duration} • ` : ""}${formatBytes(track.size)} • ajouté le ${formatDay(track.createdAt)} + ${formatBytes(track.size)} • Ajouté le ${formatDate(track.createdAt)}
        -
        - - ${iconButton("edit", "Modifier le morceau")} - ${iconButton("trash", "Supprimer de la bibliothèque", { action: "delete", extraClass: "icon-btn--danger" })} + +
        `; - li.querySelectorAll(".media-item__actions button").forEach((button) => { - button.addEventListener("click", () => - handleLibraryAction(button.dataset.action, track, button) - ); + + 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.querySelector(".tag-list").append( - ...(track.tags ?? []).map((tag) => - tagButton(tag, { - pressed: Boolean(state.activeTag) && tagKey(tag) === tagKey(state.activeTag), - }) - ) - ); - list.append(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"; } - return list; + + const actionable = isPaused || isPlaying; + elements.pauseResumeBtn.disabled = !actionable; } -// Listes de sections du formulaire d'ajout et de la fenêtre de modification. -function renderSectionChoices() { - for (const select of [elements.uploadSectionSelect, elements.editSectionSelect]) { - const selected = select.value; - select.replaceChildren(new Option("Sans section", "")); - for (const section of state.sections) { - select.append(new Option(section.name, section.id)); - } - select.value = state.sections.some((section) => section.id === selected) ? selected : ""; - } - elements.uploadSectionField.hidden = - state.sections.length === 0 || !elements.permanentCheckbox.checked; -} - -// Action du bouton lecture/pause : pause pendant la lecture, reprise en pause, sinon lancement -// de la file (en attente après un redémarrage ou un départ du bot). -function playPauseAction() { - const status = String(state.status).toLowerCase(); - if (status === "playing" || status === "buffering") return "pause"; - if (status === "paused" || status === "autopaused") return "resume"; - return "play"; -} - -const PLAY_PAUSE_LABELS = { pause: "Pause", resume: "Reprendre", play: "Lecture" }; - -function renderControls() { - const action = playPauseAction(); - for (const button of elements.playPauseButtons) { - button.innerHTML = icon(action === "pause" ? "pause" : "play"); - button.setAttribute("aria-label", PLAY_PAUSE_LABELS[action]); - button.title = PLAY_PAUSE_LABELS[action]; - button.disabled = action === "play" && !state.current && state.queue.length === 0; - } - elements.loopBtn.setAttribute("aria-pressed", String(state.loop)); - elements.loopBtn.title = state.loop - ? "Boucle activée : la file rejoue en continu" - : "Boucle : la file rejoue en continu"; -} - -function renderAuth() { - const signedIn = canUseApi(); - elements.welcome.hidden = signedIn; - elements.app.hidden = !signedIn; - elements.liveIndicator.hidden = !signedIn; - elements.loggedIn.hidden = !signedIn; - elements.userName.textContent = state.user?.name || state.displayName || ""; - elements.discordLogin.hidden = !state.oauthEnabled; - // Le mot de passe ne sert qu'en secours, quand la connexion Discord est désactivée. Un mot de - // passe déjà enregistré dans le navigateur reste envoyé et accepté. - elements.keyLogin.hidden = state.oauthEnabled; - renderMiniPlayer(); - // 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) { +async function handleQueueAction(action, trackId, index) { try { if (action === "remove") { - await withBusyButton(button, () => apiFetch(`/queue/${trackId}`, { method: "DELETE" })); + await apiFetch(`/queue/${trackId}`, { method: "DELETE" }); } else if (action === "up" || action === "down") { - const position = index + (action === "up" ? -1 : 1); - if (position < 0 || position >= state.queue.length) return; - await withBusyButton(button, () => - apiFetch(`/queue/${trackId}/move`, { method: "PATCH", body: { position } }) - ); + const delta = action === "up" ? -1 : 1; + const newPosition = Math.max(0, Math.min(index + delta, state.queue.length - 1)); + if (newPosition === index) return; + await apiFetch(`/queue/${trackId}/move`, { + method: "PATCH", + body: { position: newPosition }, + }); } - await afterAction(); + await refreshAll({ silent: true }); } 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, track, button) { +async function handleLibraryAction(action, libraryId) { try { if (action === "enqueue") { - await withBusyButton(button, () => - apiFetch(`/library/${track.id}/enqueue`, { - method: "POST", - body: { requestedBy: requesterName() }, - }) - ); - setStatus(`« ${track.title || track.originalName} » ajouté à la file`, "success"); - } else if (action === "edit") { - openEditor("track", track); - return; - } else if (action === "delete") { - if (!confirm(`Supprimer « ${track.title || track.originalName} » de la bibliothèque ?`)) { - return; - } - await withBusyButton(button, () => - apiFetch(`/library/${track.id}`, { method: "DELETE" }) - ); - if (!state.live) await refreshLibrary(); - } - await afterAction(); - } catch (error) { - setStatus(`Action bibliothèque impossible : ${error.message}`, "error"); - } -} - -// sectionId : undefined pour toute la bibliothèque, null pour les morceaux sans section. -async function enqueueAll(shuffle, button, sectionId) { - try { - const { tracks } = await withBusyButton(button, () => - apiFetch("/library/enqueue-all", { + await apiFetch(`/library/${libraryId}/enqueue`, { method: "POST", - body: { shuffle, sectionId, tag: state.activeTag ?? undefined, requestedBy: requesterName() }, - }) - ); - setStatus(`${tracks.length} morceau(x) ajouté(s) à la file`, "success"); - await afterAction(); - } catch (error) { - setStatus(`Ajout impossible : ${error.message}`, "error"); - } -} - -async function createSection(button) { - const name = prompt("Nom de la nouvelle section"); - if (!name || !name.trim()) return; - try { - await withBusyButton(button, () => - apiFetch("/library/sections", { method: "POST", body: { name: name.trim() } }) - ); - if (!state.live) await refreshLibrary(); - } catch (error) { - setStatus(`Création de la section impossible : ${error.message}`, "error"); - } -} - -// section vaut null pour le groupe « Sans section », qui n'a que les actions d'ajout. -async function handleSectionAction(action, section, index, button) { - try { - if (action === "enqueue" || action === "shuffle") { - await enqueueAll(action === "shuffle", button, section?.id ?? null); - return; - } - if (action === "edit") { - openEditor("section", section); - return; - } - if (action === "up" || action === "down") { - const position = index + (action === "up" ? -1 : 1); - await withBusyButton(button, () => - apiFetch(`/library/sections/${section.id}`, { method: "PATCH", body: { position } }) - ); - } else if (action === "delete") { - if ( - !confirm( - `Supprimer la section « ${section.name} » ? Ses morceaux restent dans la bibliothèque, sans section.` - ) - ) { - return; - } - await withBusyButton(button, () => - apiFetch(`/library/sections/${section.id}`, { method: "DELETE" }) - ); - } - if (!state.live) await refreshLibrary(); - } catch (error) { - setStatus(`Action sur la section impossible : ${error.message}`, "error"); - } -} - -// --------------------------------------------------------------------------- -// Fenêtre de modification : morceau (titre, section, pochette) ou section (nom, image) - -const MAX_COVER_SIZE = 10 * 1024 * 1024; -// { kind: "track" | "section", item } pendant que la fenêtre est ouverte. -let editing = null; -let removeCover = false; - -function showCoverPreview(url) { - const preview = elements.editCoverPreview; - preview.classList.toggle("cover--empty", !url); - preview.style.backgroundImage = url ? `url("${url}")` : ""; -} - -function openEditor(kind, item) { - const isTrack = kind === "track"; - editing = { kind, item }; - removeCover = false; - elements.editDialogTitle.textContent = isTrack ? "Modifier le morceau" : "Modifier la section"; - elements.editCoverLabel.textContent = isTrack ? "Pochette" : "Image"; - elements.editCoverRemoveBtn.textContent = isTrack ? "Retirer la pochette" : "Retirer l'image"; - elements.editNameLabel.textContent = isTrack ? "Titre" : "Nom"; - elements.editNameInput.maxLength = isTrack ? 200 : 80; - elements.editNameInput.value = isTrack ? item.title || item.originalName : item.name; - elements.editSectionField.hidden = !isTrack; - elements.editTagsField.hidden = !isTrack; - if (isTrack) { - renderSectionChoices(); - elements.editSectionSelect.value = item.sectionId ?? ""; - elements.editTagsInput.value = (item.tags ?? []).join(", "); - renderTagSuggestions(); - } - elements.editCoverInput.value = ""; - elements.editCoverRemoveBtn.hidden = !item.coverUrl; - showCoverPreview(item.coverUrl); - elements.editDialog.showModal(); -} - -function previewChosenCover() { - const file = elements.editCoverInput.files[0]; - if (!file) { - showCoverPreview(removeCover ? null : editing?.item.coverUrl); - return; - } - if (file.size > MAX_COVER_SIZE) { - setStatus("Image trop lourde : 10 Mo au plus", "error"); - elements.editCoverInput.value = ""; - return; - } - const reader = new FileReader(); - reader.addEventListener("load", () => showCoverPreview(reader.result)); - reader.readAsDataURL(file); - elements.editCoverRemoveBtn.hidden = false; -} - -function clearChosenCover() { - removeCover = true; - elements.editCoverInput.value = ""; - elements.editCoverRemoveBtn.hidden = true; - showCoverPreview(null); -} - -// Étiquettes tapées dans la fenêtre, séparées par des virgules. -function typedTags() { - return elements.editTagsInput.value - .split(",") - .map((tag) => tag.trim()) - .filter(Boolean); -} - -// Étiquettes déjà utilisées dans la bibliothèque et pas encore tapées : un clic les ajoute. -function renderTagSuggestions() { - const typed = new Set(typedTags().map(tagKey)); - const suggestions = libraryTags().filter(({ label }) => !typed.has(tagKey(label))); - elements.editTagSuggestions.replaceChildren( - ...suggestions.map(({ label }) => { - const button = document.createElement("button"); - button.type = "button"; - button.className = "tag"; - button.textContent = `+ ${label}`; - button.addEventListener("click", () => { - elements.editTagsInput.value = [...typedTags(), label].join(", "); - renderTagSuggestions(); + body: { requestedBy: state.displayName || "web-ui" }, }); - return button; - }) - ); -} - -// Changements de texte à envoyer : titre, section et étiquettes d'un morceau, nom d'une section. -function editorChanges({ kind, item }) { - const changes = {}; - const name = elements.editNameInput.value.trim(); - if (kind === "section") { - if (name && name !== item.name) changes.name = name; - return changes; - } - if (name && name !== (item.title || item.originalName)) changes.title = name; - const sectionId = elements.editSectionSelect.value || null; - if (sectionId !== (item.sectionId ?? null)) changes.sectionId = sectionId; - const tags = typedTags(); - if (tags.join("\n") !== (item.tags ?? []).join("\n")) changes.tags = tags; - return changes; -} - -async function saveEditor(event) { - event.preventDefault(); - if (!editing) return; - const { kind, item } = editing; - const path = kind === "track" ? `/library/${item.id}` : `/library/sections/${item.id}`; - const changes = editorChanges(editing); - const coverFile = elements.editCoverInput.files[0]; - - try { - await withBusyButton(elements.editSaveBtn, async () => { - if (Object.keys(changes).length > 0) { - await apiFetch(path, { method: "PATCH", body: changes }); - } - if (coverFile) { - const data = new FormData(); - data.append("cover", coverFile); - await apiFetch(`${path}/cover`, { method: "PUT", body: data }); - } else if (removeCover && item.coverUrl) { - await apiFetch(`${path}/cover`, { method: "DELETE" }); - } - }); - elements.editDialog.close(); - if (!state.live) await refreshLibrary(); - } catch (error) { - // La fenêtre reste ouverte : la personne peut corriger (autre image…) et réessayer. - setStatus(`Modification impossible : ${error.message}`, "error"); - if (!state.live) await refreshLibrary(); - } -} - -// Envoi avec XMLHttpRequest : contrairement à fetch, il indique la progression de l'envoi. -function uploadFile(file, { permanent, enqueue, section, title, onProgress }) { - return new Promise((resolve, reject) => { - const data = new FormData(); - data.append("file", file); - data.append("permanent", String(permanent)); - data.append("enqueue", String(enqueue)); - data.append("uploader", requesterName()); - if (title) data.append("notes", title); - if (permanent && section) data.append("section", section); - - const request = new XMLHttpRequest(); - request.open("POST", "/api/uploads"); - const key = apiKeyForRequests(); - if (key) request.setRequestHeader("Authorization", `Bearer ${key}`); - request.responseType = "json"; - request.upload.addEventListener("progress", (event) => { - if (event.lengthComputable) onProgress(event.loaded / event.total); - }); - request.addEventListener("load", () => { - if (request.status >= 200 && request.status < 300) { - resolve(request.response); - } else { - const error = new Error(request.response?.error || `Erreur ${request.status}`); - error.status = request.status; - reject(error); - } - }); - request.addEventListener("error", () => reject(new Error("Connexion interrompue"))); - request.send(data); - }); -} - -function addUploadRow(name) { - const li = document.createElement("li"); - li.className = "upload-list__item"; - li.innerHTML = ` - - - 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"; - }, - }; -} - -const DROPZONE_PROMPT = elements.dropzoneText.innerHTML; - -function renderChosenFiles() { - const files = [...elements.fileInput.files]; - if (files.length === 0) { - elements.dropzoneText.innerHTML = DROPZONE_PROMPT; - return; - } - const names = files.map((file) => file.name).join(", "); - elements.dropzoneText.innerHTML = `${files.length} fichier(s) prêt(s) : ${escapeHtml(names)}`; -} - -async function handleUpload(event) { - event.preventDefault(); - const files = [...elements.fileInput.files]; - if (files.length === 0) { - setStatus("Choisis au moins un fichier audio", "error"); - return; - } - - const options = { - permanent: elements.permanentCheckbox.checked, - enqueue: elements.enqueueCheckbox.checked, - section: elements.uploadSectionSelect.value, - }; - if (!options.permanent && !options.enqueue) { - setStatus("Un fichier temporaire doit être ajouté à la file d'attente", "error"); - return; - } - - const title = files.length === 1 ? elements.notesInput.value.trim() : ""; - elements.uploadList.replaceChildren(); - const rows = files.map((file) => addUploadRow(file.name)); - let succeeded = 0; - - await withBusyButton(elements.uploadSubmitBtn, async () => { - for (const [index, file] of files.entries()) { - try { - const { track } = await uploadFile(file, { - ...options, - title, - onProgress: rows[index].progress, - }); - rows[index].done(`Ajouté : ${track.title}`, true); - succeeded += 1; - } catch (error) { - rows[index].done(error.message, false); - if (error.status === 401) { - handleApiError(error); - break; - } + } else if (action === "delete") { + if (!confirm("Supprimer ce fichier permanent ?")) { + return; } + await apiFetch(`/library/${libraryId}`, { method: "DELETE" }); } - }); - - if (succeeded > 0) { - elements.uploadForm.reset(); - renderChosenFiles(); - } - setStatus( - `${succeeded} fichier(s) sur ${files.length} envoyé(s)`, - succeeded === files.length ? "success" : "error" - ); - await afterAction(); -} - -async function handleUrlSubmit(event) { - event.preventDefault(); - const url = elements.urlInput.value.trim(); - if (!url) return; - try { - setStatus("Téléchargement en cours…", "info", false); - const { track } = await withBusyButton(elements.urlSubmitBtn, () => - apiFetch("/uploads/url", { - method: "POST", - body: { - url, - permanent: elements.permanentCheckbox.checked, - enqueue: elements.enqueueCheckbox.checked, - section: elements.uploadSectionSelect.value || undefined, - uploader: requesterName(), - }, - }) - ); - elements.urlForm.reset(); - setStatus(`Ajouté : ${track.title}`, "success"); - await afterAction(); + await refreshAll({ silent: true }); } catch (error) { - setStatus(`Ajout impossible : ${error.message}`, "error"); + setStatus(`Action bibliothèque 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 startPolling() { + stopPolling(); + pollIntervalId = setInterval(() => refreshAll({ silent: true }), 5000); } -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 stopPolling() { + clearInterval(pollIntervalId); + pollIntervalId = null; } -function startSession() { - renderAuth(); - if (!canUseApi()) 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, { remember: elements.rememberKeyCheckbox.checked }); + setStoredApiKey(state.apiKey); setStoredDisplayName(state.displayName); - startSession(); - }); - - elements.logoutBtn.addEventListener("click", async () => { - if (state.user) { - await fetch("/auth/logout", { method: "POST" }).catch(() => {}); + setStatus("Paramètres sauvegardés", "success"); + refreshAll({ silent: true }); + if (state.apiKey) { + startPolling(); } - state.user = null; - state.apiKey = ""; - setStoredApiKey(""); - elements.apiKeyInput.value = ""; - stopEvents(); - startSession(); }); - elements.playPauseButtons.forEach((button) => { - button.addEventListener("click", async () => { - try { - const snapshot = await withBusyButton(button, () => - apiFetch(`/player/${playPauseAction()}`, { method: "POST" }) - ); - applySnapshot(snapshot); - } catch (error) { - setStatus(`Action impossible : ${error.message}`, "error"); - } finally { - renderControls(); + 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.seekInput.addEventListener("input", previewSeek); - elements.seekInput.addEventListener("change", commitSeek); + 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 withBusyButton(button, () => apiFetch(`/player/${action}`, { method: "POST" })); - await afterAction(); + await apiFetch(`/player/${action}`, { method: "POST" }); + await refreshAll({ silent: true }); } catch (error) { - setStatus(`Action impossible : ${error.message}`, "error"); - } finally { - renderControls(); + setStatus(`Action player impossible: ${error.message}`, "error"); } }); }); - - elements.loopBtn.addEventListener("click", async () => { - try { - const snapshot = await withBusyButton(elements.loopBtn, () => - apiFetch("/player/loop", { method: "POST", body: { enabled: !state.loop } }) - ); - applySnapshot(snapshot); - } catch (error) { - setStatus(`Action impossible : ${error.message}`, "error"); - } - }); - - elements.librarySearch.addEventListener("input", renderLibrary); - elements.newSectionBtn.addEventListener("click", () => createSection(elements.newSectionBtn)); - elements.permanentCheckbox.addEventListener("change", renderSectionChoices); - - elements.editForm.addEventListener("submit", saveEditor); - elements.editCancelBtn.addEventListener("click", () => elements.editDialog.close()); - elements.editCoverInput.addEventListener("change", previewChosenCover); - elements.editTagsInput.addEventListener("input", renderTagSuggestions); - elements.editCoverRemoveBtn.addEventListener("click", clearChosenCover); - elements.editDialog.addEventListener("close", () => { - editing = null; - }); - elements.enqueueAllBtn.addEventListener("click", () => - enqueueAll(false, elements.enqueueAllBtn) - ); - elements.enqueueAllShuffledBtn.addEventListener("click", () => - enqueueAll(true, elements.enqueueAllShuffledBtn) - ); - - elements.uploadForm.addEventListener("submit", handleUpload); - elements.urlForm.addEventListener("submit", handleUrlSubmit); - - // Glisser-déposer des fichiers sur la section d'ajout : ils sont placés dans le formulaire. - elements.uploadSection.addEventListener("dragover", (event) => { - event.preventDefault(); - elements.uploadSection.classList.add("panel--dragover"); - }); - elements.uploadSection.addEventListener("dragleave", (event) => { - if (!elements.uploadSection.contains(event.relatedTarget)) { - elements.uploadSection.classList.remove("panel--dragover"); - } - }); - elements.uploadSection.addEventListener("drop", (event) => { - event.preventDefault(); - elements.uploadSection.classList.remove("panel--dragover"); - const files = event.dataTransfer?.files; - if (files?.length) { - elements.fileInput.files = files; - renderChosenFiles(); - } - }); - elements.fileInput.addEventListener("change", renderChosenFiles); - - elements.goToUploadBtn.addEventListener("click", () => { - elements.uploadSection.scrollIntoView({ behavior: "smooth" }); - }); - elements.miniPlayerInfo.addEventListener("click", () => { - elements.playerSection.scrollIntoView({ behavior: "smooth" }); - }); - - // Le mini-lecteur ne s'affiche que quand le lecteur est hors de vue. - new IntersectionObserver(([entry]) => { - playerInView = entry.isIntersecting; - renderMiniPlayer(); - }).observe(elements.playerSection); - - // Onglet de nouveau visible : le flux a pu être coupé (mise en veille), on le relance. - document.addEventListener("visibilitychange", () => { - if (document.visibilityState === "visible" && canUseApi() && !state.live) { - eventsRetryDelay = 1_000; - void connectEvents(); - } - }); } -async function initialize() { - renderStaticIcons(); +function initialize() { elements.apiKeyInput.value = state.apiKey; elements.displayNameInput.value = state.displayName; - elements.rememberKeyCheckbox.checked = isApiKeyRemembered(); bindEvents(); - renderControls(); - setInterval(renderProgress, 1_000); - - await loadSession(); - startSession(); - showLoginError(); + updatePauseResumeButton(); + refreshAll(); + if (state.apiKey) { + startPolling(); + } } initialize(); diff --git a/public/style/styles.css b/public/style/styles.css index 6f0a3f1..6a2e9d6 100644 --- a/public/style/styles.css +++ b/public/style/styles.css @@ -1,348 +1,155 @@ -/* - * Rôle : feuille de style unique du site, c'est-à-dire de la page du jukebox (public/index.html), - * y compris les éléments créés par public/scripts/jukebox.js (morceaux, sections, icônes). - * Chargé par : public/index.html. - * Attention : servie telle quelle, sans compilation. Les couleurs viennent des variables de :root ; - * leurs versions transparentes en dérivent avec color-mix() au lieu d'être recopiées en rgba(). - * Chaque paire texte/fond des variables dépasse un contraste de 4,5 : le vérifier avant d'en - * changer une. La mise en page passe sur deux colonnes à partir de 1000 px ; en dessous, le - * mini-lecteur (.mini-player) prend le relais du lecteur hors de vue. - */ - -/* ------------------------------------------------------------------------------------------------ - * Variables - */ - :root { color-scheme: dark; - --bg: #0b0712; - /* Panneaux, puis éléments posés dessus (champs, boutons, listes déroulantes), puis survol. */ - --surface: #140e1d; - --surface-raised: #1d1529; - --surface-hover: #281d38; - --border: rgba(255, 255, 255, 0.07); - --border-strong: rgba(255, 255, 255, 0.13); - --text: #f4effa; - --muted: #b9aecb; - --muted-dark: #8f82a6; - /* Fond des boutons principaux (avec --on-accent dessus), et accent utilisé comme texte. */ - --accent: #b47aff; - --accent-hover: #c493ff; - --on-accent: #12041f; - --accent-text: #cfa8ff; - --danger: #ff7a93; - --success: #6ee7a8; - --shadow: rgba(0, 0, 0, 0.5); - --radius: 12px; - --radius-lg: 18px; - --topbar-height: 60px; - --mini-player-height: 64px; + --bg: #06030d; + --bg-card: rgba(22, 14, 36, 0.9); + --bg-glass: rgba(42, 25, 66, 0.65); + --border: rgba(255, 255, 255, 0.08); + --accent: #b259ff; + --accent-strong: #d66bff; + --muted: #cbc4d5; + --muted-dark: #8c7ea7; + --danger: #ff4d6d; + --success: #59ffa7; + --gradient: radial-gradient(circle at 20% 20%, #2d1a49, transparent 45%), + radial-gradient(circle at 80% 0%, #551e8c, transparent 40%), + radial-gradient(circle at 50% 80%, #150b28, transparent 30%); } -/* ------------------------------------------------------------------------------------------------ - * Base - */ - * { box-sizing: border-box; } -[hidden] { - display: none !important; -} - -/* Masqué à l'écran mais lu par les lecteurs d'écran. Les !important l'emportent sur les règles - des champs (largeur 100 %, marges intérieures), qui ont une spécificité plus forte. */ -.visually-hidden { - position: absolute !important; - width: 1px !important; - height: 1px !important; - margin: -1px !important; - padding: 0 !important; - border: 0 !important; - overflow: hidden; - clip: rect(0 0 0 0); - white-space: nowrap; -} - -html { - scroll-padding-top: calc(var(--topbar-height) + 1rem); -} - body { margin: 0; min-height: 100vh; font-family: "Inter", "Segoe UI", system-ui, -apple-system, BlinkMacSystemFont, sans-serif; - line-height: 1.45; - background: - radial-gradient(ellipse 70% 45% at 50% -5%, color-mix(in srgb, var(--accent) 18%, transparent), transparent), - var(--bg); - background-attachment: fixed; - color: var(--text); - /* Cases à cocher et barres de progression natives aux couleurs du site. */ - accent-color: var(--accent); + background: var(--gradient), #050109; + color: #f7f1ff; } -/* Place pour le mini-lecteur, fixé en bas de l'écran quand il est affiché. */ -body.has-mini-player { - padding-bottom: calc(var(--mini-player-height) + 1rem); +main { + max-width: 1200px; + margin: 0 auto; + padding: 0 1.5rem 4rem; } h1, h2, -h3 { +h3, +h4 { margin: 0; - line-height: 1.2; } p { margin-top: 0; } -code { - background: var(--surface-hover); - border-radius: 6px; - padding: 0.1rem 0.35rem; -} - -/* Icônes SVG insérées par jukebox.js (fonction icon). */ -.icon { - width: 1.2em; - height: 1.2em; - flex-shrink: 0; - fill: none; - stroke: currentColor; - stroke-width: 2; - stroke-linecap: round; - stroke-linejoin: round; -} - -.icon--fill { - fill: currentColor; - stroke: none; -} - -.hint { - color: var(--muted-dark); - font-size: 0.85rem; - margin: 0.4rem 0 0; -} - -.empty { - color: var(--muted-dark); - text-align: center; - margin: 1rem 0 0.5rem; -} - -.eyebrow { - color: var(--accent-text); - font-size: 0.8rem; - font-weight: 600; - letter-spacing: 0.08em; - text-transform: uppercase; - margin-bottom: 0.75rem; -} - -/* ------------------------------------------------------------------------------------------------ - * Barre du haut - */ - -.topbar { - position: sticky; - top: 0; - z-index: 20; - height: var(--topbar-height); - background: color-mix(in srgb, var(--bg) 80%, transparent); - backdrop-filter: blur(12px); - border-bottom: 1px solid var(--border); -} - -.topbar__inner { - display: flex; - align-items: center; - gap: 1rem; - max-width: 1280px; - height: 100%; - margin: 0 auto; - padding: 0 1.25rem; -} - -.brand { - display: flex; - align-items: center; - gap: 0.6rem; - color: var(--text); - font-weight: 700; - font-size: 1.05rem; - text-decoration: none; - white-space: nowrap; -} - -.topbar__account { - display: flex; - align-items: center; - gap: 0.75rem; - margin-left: auto; - min-width: 0; -} - -.topbar__user { +.text--muted { color: var(--muted); - font-size: 0.9rem; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + text-align: center; } -.live-indicator { +.hero { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: center; + gap: 2rem; + padding: 3rem 1.5rem; + max-width: 1200px; + margin: 0 auto; +} + +.hero--home { + flex-direction: row; + align-items: center; + text-align: left; + gap: 2.75rem; +} + +.hero--home .hero__visual img { + max-width: 320px; +} + +.hero__content { + flex: 1; + min-width: 280px; +} + +.hero__content h1 { + font-size: 2.2rem; + line-height: 1.1; + margin-top: 1rem; + margin-bottom: 1rem; +} + +.hero__content p { + color: var(--muted); + font-size: 1.05rem; + max-width: 500px; +} + +.hero__actions { + display: flex; + gap: 1rem; + margin-top: 1.5rem; +} + +.hero__actions--centered { + justify-content: center; + margin: 2rem auto 3rem; +} + +.hero__visual { + min-width: 200px; + display: flex; + justify-content: center; +} + +.hero__visual img { + max-width: 200px; + width: 100%; + filter: drop-shadow(0 25px 45px rgba(0, 0, 0, 0.45)); +} + +.hero__visual--large img { + max-width: 270px; +} + +.hero__auth { + max-width: 300px; +} + +.pill { display: inline-flex; align-items: center; gap: 0.45rem; - font-size: 0.8rem; - color: var(--muted-dark); - white-space: nowrap; - - &::before { - content: ""; - width: 0.5rem; - height: 0.5rem; - border-radius: 50%; - background: var(--muted-dark); - } - - &[data-live="true"] { - color: var(--success); - } - - &[data-live="true"]::before { - background: var(--success); - box-shadow: 0 0 0 4px color-mix(in srgb, var(--success) 15%, transparent); - } -} - -/* ------------------------------------------------------------------------------------------------ - * Écran de connexion - */ - -.welcome { - display: flex; - align-items: center; - justify-content: center; - gap: 3rem; - max-width: 1000px; - min-height: calc(100vh - var(--topbar-height)); - margin: 0 auto; - padding: 2rem 1.5rem; -} - -.welcome__visual { - width: 100%; - max-width: 300px; - height: auto; - filter: drop-shadow(0 25px 45px var(--shadow)); -} - -.welcome__content { - flex: 1; - max-width: 460px; - - & h1 { - font-size: 2.3rem; - margin-bottom: 1rem; - } - - & .btn--discord { - margin-top: 0.5rem; - } -} - -.welcome__text { + font-size: 0.9rem; + padding: 0.35rem 0.85rem; + border-radius: 999px; + background: rgba(255, 255, 255, 0.08); color: var(--muted); - font-size: 1.05rem; - margin-bottom: 1.5rem; + letter-spacing: 0.05em; + text-transform: uppercase; } -/* Mot de passe : replié sous le bouton Discord, ou seul moyen de se connecter. */ -.key-login { - margin-top: 1.25rem; - - & summary { - cursor: pointer; - color: var(--muted); - } -} - -.key-login__form { - margin-top: 1rem; - padding: 1.25rem; - border: 1px solid var(--border); - border-radius: var(--radius-lg); - background: var(--surface); -} - -/* ------------------------------------------------------------------------------------------------ - * Mise en page de l'application - */ - -.layout { - display: grid; - gap: 1.25rem; - max-width: 1280px; - margin: 0 auto; - padding: 1.25rem 1.25rem 3rem; -} - -.layout__side, -.layout__main { - display: flex; - flex-direction: column; - gap: 1.25rem; - min-width: 0; -} - -/* Deux colonnes : bibliothèque à gauche ; lecteur et file à droite, fixés pendant le défilement, - la file défilant dans son panneau. */ -@media (min-width: 1000px) { - .layout { - grid-template-columns: minmax(0, 1fr) 380px; - align-items: start; - } - - .layout__main { - grid-column: 1; - grid-row: 1; - } - - .layout__side { - grid-column: 2; - grid-row: 1; - position: sticky; - top: calc(var(--topbar-height) + 1.25rem); - max-height: calc(100vh - var(--topbar-height) - 2.5rem); - } - - .queue { - min-height: 0; - overflow-y: auto; - } -} - -/* ------------------------------------------------------------------------------------------------ - * Panneaux - */ - .panel { - border-radius: var(--radius-lg); - padding: 1.25rem 1.5rem; + border-radius: 18px; + padding: 1.75rem; + margin-bottom: 1.75rem; border: 1px solid var(--border); - background: var(--surface); - box-shadow: 0 12px 30px var(--shadow); } -/* Fichiers glissés au-dessus de la section d'ajout. */ -.panel--dragover { - border-color: var(--accent); - border-style: dashed; +.panel--glass { + background: var(--bg-glass); + box-shadow: 0 20px 38px rgba(2, 0, 8, 0.45); + backdrop-filter: blur(18px); +} + +.panel__subtitle { + color: var(--muted); + margin-top: 0.35rem; + margin-bottom: 1.5rem; } .panel__header { @@ -350,104 +157,46 @@ code { justify-content: space-between; align-items: flex-start; gap: 1rem; - margin-bottom: 1rem; -} - -.panel__title { - font-size: 1.15rem; -} - -.panel__subtitle { - color: var(--muted); - font-size: 0.92rem; - margin: 0.25rem 0 0; -} - -#uploadSection .panel__subtitle { - margin-bottom: 1rem; + margin-bottom: 1.25rem; } .badge { - padding: 0.25rem 0.7rem; - background: color-mix(in srgb, var(--accent) 16%, transparent); - color: var(--accent-text); - border-radius: 999px; - font-size: 0.8rem; - white-space: nowrap; + padding: 0.35rem 0.9rem; + background: rgba(178, 89, 255, 0.2); + color: var(--accent); + border-radius: 12px; + font-size: 0.85rem; } -/* ------------------------------------------------------------------------------------------------ - * Formulaires - */ - label { display: block; - font-size: 0.9rem; + font-size: 0.95rem; color: var(--muted); margin-bottom: 0.35rem; } input[type="text"], -input[type="password"], -input[type="url"], -input[type="search"], input[type="file"], select, textarea { width: 100%; - padding: 0.65rem 0.9rem; - border-radius: var(--radius); - border: 1px solid var(--border-strong); - background: var(--surface-raised); - color: var(--text); - font: inherit; - font-size: 0.95rem; -} - -::placeholder { - color: var(--muted-dark); -} - -/* Fond plein, options comprises : le navigateur dessine sinon la liste ouverte sur du blanc. */ -select { - cursor: pointer; -} - -select option, -select optgroup { - background-color: var(--surface-raised); - color: var(--text); + padding: 0.7rem 0.9rem; + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.12); + background: rgba(255, 255, 255, 0.05); + color: #fff; + font-size: 1rem; } input[type="file"] { - padding: 0.45rem; - color: var(--muted); - cursor: pointer; - - &::file-selector-button { - margin-right: 0.75rem; - padding: 0.35rem 0.9rem; - border: 1px solid var(--border-strong); - border-radius: 999px; - background: var(--surface-hover); - color: var(--text); - font: inherit; - font-size: 0.85rem; - font-weight: 600; - cursor: pointer; - } - - &:hover::file-selector-button { - border-color: var(--accent); - } + padding: 0.5rem; } -input:focus-visible, -textarea:focus-visible, -select:focus-visible { - outline: 2px solid color-mix(in srgb, var(--accent) 60%, transparent); - outline-offset: 1px; - border-color: transparent; +input:focus, +textarea:focus, +select:focus { + outline: 2px solid rgba(178, 89, 255, 0.5); + border-color: rgba(178, 89, 255, 0.6); } .form-checkbox { @@ -455,497 +204,104 @@ select:focus-visible { align-items: flex-start; gap: 0.5rem; color: var(--muted); - cursor: pointer; } .form-checkbox__input { - margin-top: 0.2rem; + margin-top: 0.25rem; } -.form-actions { - margin-top: 1rem; - display: flex; - justify-content: flex-end; -} - -/* Zone de dépôt : le vrai champ de fichiers est masqué, la zone en est l'étiquette. */ -.dropzone { - display: flex; - align-items: center; - justify-content: center; - gap: 0.75rem; - min-height: 96px; - margin: 0; - padding: 1rem; - border: 1.5px dashed var(--border-strong); - border-radius: var(--radius-lg); - background: var(--surface-raised); - color: var(--muted); - text-align: center; - cursor: pointer; - transition: border-color 0.15s ease, background 0.15s ease; - - &:hover, - .panel--dragover & { - border-color: var(--accent); - background: var(--surface-hover); - } - - & strong { - color: var(--accent-text); - } - - input:focus-visible + & { - outline: 2px solid var(--accent); - outline-offset: 2px; - } -} - -.dropzone__icon { - display: inline-flex; - font-size: 1.4rem; - color: var(--accent-text); -} - -.dropzone__text { - overflow-wrap: anywhere; -} - -/* ------------------------------------------------------------------------------------------------ - * Boutons - */ - .btn { - display: inline-flex; - align-items: center; - justify-content: center; - gap: 0.4rem; - border: 1px solid var(--border-strong); + border: none; border-radius: 999px; - padding: 0.55rem 1.2rem; - font: inherit; - font-size: 0.92rem; + padding: 0.65rem 1.55rem; font-weight: 600; - line-height: 1.2; cursor: pointer; - background: var(--surface-raised); - color: var(--text); - text-decoration: none; - white-space: nowrap; - transition: background 0.15s ease, border-color 0.15s ease; - - &:hover { - background: var(--surface-hover); - } - - &:disabled { - opacity: 0.45; - cursor: not-allowed; - } - - &:focus-visible { - outline: 2px solid var(--accent-text); - outline-offset: 2px; - } + background: linear-gradient(120deg, var(--accent), var(--accent-strong)); + color: #08010f; + transition: transform 0.15s ease, box-shadow 0.15s ease; } -.btn--primary { - background: var(--accent); - border-color: transparent; - color: var(--on-accent); +.btn:hover { + transform: translateY(-1px); + box-shadow: 0 10px 25px rgba(178, 89, 255, 0.35); +} - &:hover { - background: var(--accent-hover); - } +.btn:disabled { + opacity: 0.55; + cursor: not-allowed; + box-shadow: none; + transform: none; +} + +.btn--secondary { + background: rgba(255, 255, 255, 0.15); + color: #fff; +} + +.btn--danger { + background: linear-gradient(120deg, #ff4d6d, #ff89a5); + color: #fff; } .btn--ghost { background: transparent; -} - -.btn--danger { - background: color-mix(in srgb, var(--danger) 12%, transparent); - border-color: color-mix(in srgb, var(--danger) 35%, transparent); - color: var(--danger); - - &:hover { - background: color-mix(in srgb, var(--danger) 22%, transparent); - } + border: 1px solid rgba(255, 255, 255, 0.35); + color: #fff; } .btn--small { - padding: 0.35rem 0.85rem; - font-size: 0.85rem; + padding: 0.4rem 1rem; + font-size: 0.9rem; } -/* Bouton aux couleurs de Discord (blurple), avec son logo. */ -.btn.btn--discord { - gap: 0.55rem; - width: 100%; - min-height: 48px; - border: 1px solid #6f7bff; - border-radius: var(--radius); - background: #5865f2; - box-shadow: 0 6px 16px rgba(35, 39, 96, 0.38), inset 0 1px 0 rgba(255, 255, 255, 0.14); - color: #fff; - font-weight: 700; - - & svg { - flex: 0 0 24px; - width: 24px; - height: 24px; - } - - &:hover { - border-color: #7c86ff; - background: #4752c4; - } -} - -/* Bouton rond à icône seule ; son nom passe par aria-label. */ -.icon-btn { - display: inline-grid; - place-items: center; - flex-shrink: 0; - width: 36px; - height: 36px; - padding: 0; - border: none; - border-radius: 50%; - background: transparent; - color: var(--muted); - font-size: 1rem; - cursor: pointer; - transition: background 0.15s ease, color 0.15s ease; - - &:hover { - background: var(--surface-hover); - color: var(--text); - } - - &:disabled { - opacity: 0.3; - cursor: not-allowed; - background: transparent; - } - - &:focus-visible { - outline: 2px solid var(--accent-text); - outline-offset: 2px; - } - - /* Bouton à bascule activé (boucle). */ - &[aria-pressed="true"] { - background: color-mix(in srgb, var(--accent) 18%, transparent); - color: var(--accent-text); - } -} - -.icon-btn--primary { - background: var(--accent); - color: var(--on-accent); - - &:hover { - background: var(--accent-hover); - color: var(--on-accent); - } -} - -.icon-btn--large { - width: 56px; - height: 56px; - font-size: 1.35rem; -} - -.icon-btn--danger:hover { - background: color-mix(in srgb, var(--danger) 15%, transparent); - color: var(--danger); -} - -.toolbar { +.control-group { display: flex; flex-wrap: wrap; - gap: 0.5rem; + gap: 0.75rem; + margin-top: 1.25rem; } -/* ------------------------------------------------------------------------------------------------ - * Lecteur : morceau en cours, position, commandes - */ - -.player__track { - display: flex; - align-items: center; +.grid { + display: grid; gap: 1rem; - margin: 1rem 0 0.75rem; - min-height: 96px; } -.player__track--empty { - justify-content: center; - color: var(--muted-dark); - text-align: center; +.grid--two { + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); } -.player__title { - font-weight: 700; - font-size: 1.05rem; - overflow-wrap: anywhere; -} - -.player__controls { - display: flex; - align-items: center; - justify-content: center; - gap: 1rem; - margin-top: 0.5rem; -} - -.player__stop { - display: flex; - margin: 1rem auto 0; -} - -/* Barre de position : un curseur natif, dont la partie jouée est peinte d'après --progress. */ -.seek__input { - --progress: 0%; - appearance: none; - -webkit-appearance: none; - display: block; - width: 100%; - height: 18px; - margin: 0; - background: transparent; - cursor: pointer; - - &::-webkit-slider-runnable-track { - height: 6px; - border-radius: 999px; - background: linear-gradient( - to right, - var(--accent) var(--progress), - var(--surface-hover) var(--progress) - ); - } - - &::-webkit-slider-thumb { - -webkit-appearance: none; - width: 14px; - height: 14px; - margin-top: -4px; - border-radius: 50%; - background: var(--text); - opacity: 0; - transition: opacity 0.15s ease; - } - - &::-moz-range-track { - height: 6px; - border-radius: 999px; - background: var(--surface-hover); - } - - &::-moz-range-progress { - height: 6px; - border-radius: 999px; - background: var(--accent); - } - - &::-moz-range-thumb { - width: 14px; - height: 14px; - border: none; - border-radius: 50%; - background: var(--text); - opacity: 0; - transition: opacity 0.15s ease; - } - - &:hover::-webkit-slider-thumb, - &:focus-visible::-webkit-slider-thumb, - &:active::-webkit-slider-thumb, - &:hover::-moz-range-thumb, - &:focus-visible::-moz-range-thumb, - &:active::-moz-range-thumb { - opacity: 1; - } - - &:focus-visible { - outline: 2px solid var(--accent-text); - outline-offset: 4px; - border-radius: 4px; - } -} - -.seek__times { - display: flex; - justify-content: space-between; - color: var(--muted-dark); - font-size: 0.8rem; - margin-top: 0.2rem; - font-variant-numeric: tabular-nums; -} - -/* Mini-lecteur des petits écrans, en bas de l'écran. Jamais affiché sur deux colonnes. */ -.mini-player { - position: fixed; - left: 0.75rem; - right: 0.75rem; - bottom: 0.75rem; - z-index: 15; - display: flex; - align-items: center; - gap: 0.5rem; - height: var(--mini-player-height); - padding: 0 0.6rem; - overflow: hidden; - border: 1px solid var(--border-strong); - border-radius: var(--radius-lg); - background: color-mix(in srgb, var(--surface-raised) 92%, transparent); - backdrop-filter: blur(12px); - box-shadow: 0 12px 30px var(--shadow); - - @media (min-width: 1000px) { - display: none !important; - } - - & .icon-btn--primary { - width: 42px; - height: 42px; - } -} - -.mini-player__info { - display: flex; - align-items: center; - gap: 0.65rem; - flex: 1; - min-width: 0; - padding: 0; - border: none; - background: none; - color: var(--text); - font: inherit; - text-align: left; - cursor: pointer; - - & .cover { - width: 44px; - height: 44px; - border-radius: 10px; - } -} - -.mini-player__title { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - font-weight: 600; - font-size: 0.92rem; -} - -.mini-player__progress { - position: absolute; - left: 0; - right: 0; - bottom: 0; - height: 3px; - - & > div { - height: 100%; - width: 0; - background: var(--accent); - transition: width 0.9s linear; - } -} - -/* ------------------------------------------------------------------------------------------------ - * Ajout de morceaux : envois en cours, ajout par lien - */ - -.upload-list { +.u-mt-1 { 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; - - & progress { - width: 100%; - } - - &[data-state="ok"] .upload-list__state { - color: var(--success); - } - - &[data-state="error"] .upload-list__state { - color: var(--danger); - } -} - -.upload-list__name { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.upload-list__state { - color: var(--muted); -} - -.url-form { - border-top: 1px solid var(--border); - padding-top: 1.25rem; - margin-top: 1.5rem; -} - -.url-form__row { +.form-actions { + margin-top: 1.25rem; display: flex; - gap: 0.75rem; + justify-content: flex-end; } -/* ------------------------------------------------------------------------------------------------ - * Messages d'état (voir createStatusManager dans common.js) : bulle en bas de l'écran - */ - -.toast { - position: fixed; - left: 50%; - bottom: 1.25rem; - z-index: 30; - transform: translateX(-50%); - width: max-content; - max-width: min(560px, calc(100% - 1.5rem)); - padding: 0.75rem 1.15rem; - border: 1px solid var(--border-strong); - border-radius: var(--radius); - background: var(--surface-raised); - box-shadow: 0 12px 30px var(--shadow); - font-size: 0.92rem; - color: var(--accent-text); - - &[data-type="error"] { - color: var(--danger); - border-color: color-mix(in srgb, var(--danger) 45%, transparent); - } - - &[data-type="success"] { - color: var(--success); - border-color: color-mix(in srgb, var(--success) 40%, transparent); - } - - .has-mini-player & { - bottom: calc(var(--mini-player-height) + 1.5rem); - } +.status { + padding: 0.85rem 1.25rem; + border-radius: 999px; + font-size: 0.95rem; + margin: 1rem 0 2rem; + max-width: 600px; } -/* ------------------------------------------------------------------------------------------------ - * Listes de morceaux (file d'attente, bibliothèque) - */ +.status--info { + background: rgba(178, 89, 255, 0.2); + color: var(--accent); +} + +.status--error { + background: rgba(255, 77, 109, 0.15); + color: var(--danger); +} + +.status--success { + background: rgba(89, 255, 167, 0.15); + color: var(--success); +} .list { list-style: none; @@ -953,397 +309,107 @@ select:focus-visible { margin: 0; } -.list--stack > li + li { - border-top: 1px solid var(--border); +.list--stack > li { + border-bottom: 1px solid rgba(255, 255, 255, 0.08); } .media-item { display: flex; - gap: 0.85rem; + gap: 1rem; + justify-content: space-between; align-items: center; - padding: 0.7rem 0; + padding: 0.9rem 0; } .media-item__info { flex: 1; - min-width: 0; } .media-item__title { font-weight: 600; - font-size: 0.95rem; - overflow-wrap: anywhere; + font-size: 1rem; } .media-item__meta { - color: var(--muted-dark); - font-size: 0.82rem; + color: var(--muted); + font-size: 0.9rem; } .media-item__actions { - display: flex; - align-items: center; - gap: 0.15rem; -} - -.media-item__actions .btn { - margin-right: 0.35rem; -} - -/* File d'attente : lignes plus serrées, numéro devant le titre. */ -.media-item--queue { - gap: 0.7rem; - padding: 0.55rem 0; - - & .cover { - width: 44px; - height: 44px; - border-radius: 10px; - } - - & .icon-btn { - width: 30px; - height: 30px; - font-size: 0.9rem; - } -} - -.media-item__position { - color: var(--muted-dark); - font-variant-numeric: tabular-nums; - margin-right: 0.25rem; -} - -/* Pochette d'un morceau : , ou
        vide (note de musique) ou à image de fond (aperçu). */ -.cover { - flex-shrink: 0; - width: 56px; - height: 56px; - border-radius: var(--radius); - object-fit: cover; - background: var(--surface-raised) center / cover no-repeat; - border: 1px solid var(--border); -} - -/* Lecteur et fenêtre de modification. */ -.cover--large { - width: 96px; - height: 96px; - border-radius: 16px; -} - -.cover--empty { - display: grid; - place-items: center; - color: var(--muted-dark); - - &::after { - content: "♪"; - font-size: 1.4rem; - } - - &.cover--large::after { - font-size: 2.6rem; - } -} - -/* ------------------------------------------------------------------------------------------------ - * Bibliothèque : outils, sections repliables, étiquettes, fenêtre de modification - */ - -.library-tools { display: flex; flex-wrap: wrap; - gap: 0.75rem; - align-items: center; - - & input[type="search"] { - flex: 1 1 300px; - width: auto; - } -} - -.library { - margin-top: 1rem; -} - -.library-section { - border: 1px solid var(--border); - border-radius: 16px; - padding: 0 1rem; - margin-bottom: 0.75rem; - background: color-mix(in srgb, var(--surface-raised) 55%, transparent); -} - -.library-section__summary { - display: flex; - align-items: center; - gap: 0.85rem; - padding: 0.85rem 0; - cursor: pointer; - list-style: none; - - &::-webkit-details-marker { - display: none; - } - - &::before { - content: "▸"; - color: var(--accent-text); - transition: transform 0.15s ease; - } - - [open] > &::before { - transform: rotate(90deg); - } -} - -/* Nom et nombre de morceaux : restent à côté de l'image, quitte à passer sur deux lignes. */ -.library-section__heading { - display: flex; - flex-wrap: wrap; - align-items: baseline; - gap: 0.15rem 0.75rem; - min-width: 0; -} - -/* Image de la section, entre la flèche et le nom. */ -.cover--section { - width: 80px; - height: 80px; - border-radius: 14px; -} - -.library-section__name { - font-weight: 700; - font-size: 1.05rem; -} - -.library-section__count { - color: var(--muted-dark); - font-size: 0.85rem; -} - -/* Ajout en bloc à gauche, gestion de la section (icônes) à droite. */ -.library-section__toolbar { - display: flex; - flex-wrap: wrap; - align-items: center; gap: 0.4rem; - padding-bottom: 0.6rem; - border-bottom: 1px solid var(--border); } -.library-section__manage { - display: flex; - gap: 0.1rem; - margin-left: auto; +.player-current { + background: rgba(0, 0, 0, 0.25); + border-radius: 16px; + padding: 1.2rem; + border: 1px solid rgba(255, 255, 255, 0.08); } -.library-section__empty { - padding: 0.75rem 0 1rem; +.player-current--empty { + color: var(--muted); + text-align: center; } -/* Étiquettes : sous un morceau, en barre de filtre au-dessus de la bibliothèque, ou en - suggestions dans la fenêtre de modification. Celle du filtre actif est pressée. */ -.tag-list { - display: flex; - flex-wrap: wrap; - gap: 0.35rem; - - &:not(:empty) { - margin-top: 0.35rem; - } -} - -.tag-list--filter:not(:empty) { - margin-top: 0.75rem; -} - -.tag { - display: inline-flex; - align-items: center; - gap: 0.35rem; - padding: 0.15rem 0.65rem; - border: 1px solid color-mix(in srgb, var(--accent) 30%, transparent); - border-radius: 999px; - background: color-mix(in srgb, var(--accent) 10%, transparent); - color: var(--text); - font: inherit; - font-size: 0.78rem; - cursor: pointer; - - &:hover { - background: color-mix(in srgb, var(--accent) 22%, transparent); - } - - &[aria-pressed="true"] { - background: var(--accent); - color: var(--on-accent); - border-color: transparent; - } - - &:focus-visible { - outline: 2px solid var(--accent-text); - outline-offset: 2px; - } -} - -.tag__count { - opacity: 0.7; - font-size: 0.72rem; -} - -.dialog { - width: min(520px, calc(100% - 2rem)); - padding: 1.5rem; - border-radius: var(--radius-lg); - border: 1px solid var(--border-strong); - background: var(--surface); - color: var(--text); - box-shadow: 0 20px 38px var(--shadow); - - &::backdrop { - background: color-mix(in srgb, var(--bg) 70%, transparent); - backdrop-filter: blur(4px); - } - - & h2 { - font-size: 1.25rem; - margin-bottom: 1.25rem; - } -} - -.cover-editor { - display: flex; +.feature-grid { + display: grid; gap: 1rem; - align-items: flex-start; + grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); } -.cover-editor__fields { - flex: 1; - min-width: 0; +.feature-grid__card { + text-decoration: none; + color: inherit; + display: block; + border: 1px solid var(--border); + border-radius: 18px; + padding: 1.25rem 1.5rem; + background: var(--bg-card); + transition: transform 0.15s ease, box-shadow 0.15s ease; } -/* ------------------------------------------------------------------------------------------------ - * Petits écrans - */ +.feature-grid__card:hover { + transform: translateY(-3px); + box-shadow: 0 15px 30px rgba(2, 0, 8, 0.45); +} -@media (max-width: 760px) { - .welcome { +.feature-grid__card .pill { + margin-bottom: 0.5rem; +} + +@media (max-width: 900px) { + .hero, + .hero--home { flex-direction: column; - gap: 1.5rem; - min-height: 0; text-align: center; } - .welcome__visual { - max-width: 170px; + .hero__content p { + margin: 0 auto; } - .welcome__content h1 { - font-size: 1.8rem; - } - - .key-login__form { - text-align: left; - } -} - -@media (max-width: 600px) { - .topbar__inner { - padding: 0 0.9rem; - gap: 0.6rem; - } - - .brand span, - .topbar__user { - display: none; - } - - .layout { - padding: 0.9rem 0.75rem 2rem; - gap: 0.9rem; - } - - .layout__side, - .layout__main { - gap: 0.9rem; - } - - .panel { - padding: 1rem; + .hero__actions { + justify-content: center; } .panel__header { flex-direction: column; + align-items: flex-start; + } +} + +@media (max-width: 600px) { + .btn, + input[type="text"], + input[type="file"], + select, + textarea { + width: 100%; } - /* File d'attente : le compteur reste à côté du titre. */ - .queue .panel__header { - flex-direction: row; - align-items: center; - } - - .url-form__row { - flex-direction: column; - } - - .upload-list__item { - grid-template-columns: 1fr; - gap: 0.25rem; - } - - .library-section { - padding: 0 0.75rem; - } - - .cover--section { - width: 64px; - height: 64px; - } - - .media-item { - gap: 0.7rem; - } - - /* Bibliothèque : titre sur toute la largeur, boutons en dessous. */ - .media-item--library { - flex-wrap: wrap; - - & .cover { - width: 48px; - height: 48px; - } - - & .media-item__info { - flex: 1 1 0; - } - - & .media-item__actions { - flex-basis: 100%; - justify-content: flex-end; - } - } - - .cover-editor { + .control-group { flex-direction: column; } } - -/* ------------------------------------------------------------------------------------------------ - * Utilitaires de mise en page - */ - -.grid { - display: grid; - gap: 0.75rem 1rem; -} - -.grid--two { - grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); -} - -.u-mt-1 { - margin-top: 1rem; -} diff --git a/scripts/check-syntax.js b/scripts/check-syntax.js index 18aca76..a50c2a7 100644 --- a/scripts/check-syntax.js +++ b/scripts/check-syntax.js @@ -1,8 +1,3 @@ -/** - * @file Vérifie la syntaxe de tous les fichiers JavaScript avec `node --check` (`npm run check:syntax`), - * y compris les scripts du front, que les tests n'importent pas. - */ - import fs from "node:fs"; import path from "node:path"; import { spawnSync } from "node:child_process"; diff --git a/src/commands/game/dice.js b/src/commands/game/dice.js index f1ac5a5..e9257fb 100644 --- a/src/commands/game/dice.js +++ b/src/commands/game/dice.js @@ -1,69 +1,67 @@ -/** - * @file Commande /dice : lance les dés un par un, avec une pause entre chacun, puis donne le total - * (ou pile et face pour un dé à deux faces). - */ - -import { SlashCommandBuilder, subtext } from "discord.js"; -import { setTimeout } from "node:timers/promises"; -import { getRandomInt } from "../../features/utilities.js"; - -const command = { - data: new SlashCommandBuilder() - .setName("dice") - .setDescription("Lance un ou plusieurs dés") - .addIntegerOption((option) => - option +import { SlashCommandBuilder, subtext } from "discord.js"; +import { setTimeout } from "node:timers/promises"; +import { getRandomInt } from "../../features/utilities.js"; + +const command = { + data: new SlashCommandBuilder() + .setName("dice") + .setDescription("Lance un ou plusieurs dés") + .addIntegerOption((option) => + option .setName("number") - .setDescription("Nombre de dés à lancer") + .setDescription("Nombre de dés a lancer") .setMinValue(1) .setMaxValue(20) .setRequired(true) - ) - .addIntegerOption((option) => - option + ) + .addIntegerOption((option) => + option .setName("faces") .setDescription("Nombre de faces sur le dé") .setMinValue(2) .setMaxValue(1000) .setRequired(true) - ), - async execute(interaction) { - const number = interaction.options.getInteger("number"); - const faces = interaction.options.getInteger("faces"); - let sum = 0; - let message = "Alors du coup... 🥁\n"; - let tails = 0; - let heads = 0; - - if (faces === 2) { - message += subtext("Pile = 1 et Face = 2\n"); - } - - await interaction.reply(message); - - for (let i = 0; i < number; i++) { - await setTimeout(1_500); - const random = getRandomInt(faces) + 1; - if (random === 1) tails++; - else heads++; - sum += random; - - message += `[ ${random} ] ${i === number - 1 ? "\n" : " "}`; + ), + async execute(interaction) { + const number = interaction.options.getInteger("number"); + const faces = interaction.options.getInteger("faces"); + var sum = 0; + var message = "Alors du coup... 🥁\n"; + var tails = 0; + var heads = 0; + + if (faces === 2) { + message = message + subtext(`Pile = 1 et Face = 2\n`); + } + + await interaction.reply(message); + + for (let i = 0; i < number; i++) { + await setTimeout(1_500); + let random = getRandomInt(faces) + 1; + random === 1 ? tails++ : heads++; + sum = sum + random; + + message = message + `[ ${random} ] ${i === number - 1 ? "\n" : " "}`; await interaction.editReply(message); - } - - if (number > 1 && faces > 2) { - await setTimeout(1_000); - message += subtext(`Soit au total : ${sum}`); - } - - if (number > 1 && faces === 2) { - await setTimeout(1_000); - message += subtext(`Soit au total : ${sum}, ou bien ${tails} piles et ${heads} faces\n`); - } - + } + + if (number > 1 && faces > 2) { + await setTimeout(1_000); + message = message + subtext(`Soit au total : ${sum}`); + } + + if (number > 1 && faces === 2) { + await setTimeout(1_000); + message = + message + + subtext( + `Soit au total : ${sum}, ou bien ${tails} piles et ${heads} faces \n` + ); + } + await interaction.editReply(message); - }, -}; - -export { command }; + }, +}; + +export { command }; diff --git a/src/commands/game/maketeam.js b/src/commands/game/maketeam.js index 6debb58..fb6c761 100644 --- a/src/commands/game/maketeam.js +++ b/src/commands/game/maketeam.js @@ -1,65 +1,63 @@ -/** - * @file Commande /maketeam : répartit une liste de joueurs au hasard en équipes. Les noms sont séparés - * par des espaces, ou seulement par des virgules dès qu'il y en a une. - */ - -import { MessageFlags, SlashCommandBuilder } from "discord.js"; -import { shuffle } from "../../features/utilities.js"; - -// « Alice Bob » ou « Jean Pierre, Marie » : dès qu'il y a une virgule, seules les virgules -// séparent les joueurs. -function parsePlayers(input) { - const separator = input.includes(",") ? "," : /\s+/; - return input - .split(separator) - .map((player) => player.trim()) - .filter(Boolean); -} - -const command = { - data: new SlashCommandBuilder() - .setName("maketeam") - .setDescription("Crée des équipes au hasard") - .addIntegerOption((option) => - option +import { 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'équipes") + .setDescription("Nombre d'équipe") .setMinValue(1) .setMaxValue(20) .setRequired(true) - ) - .addStringOption((option) => - option + ) + .addStringOption((option) => + option .setName("players") - .setDescription("Joueurs séparés par des espaces, ou par des virgules si un nom contient un espace") + .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"); - const playersArray = parsePlayers(players); + ), + async execute(interaction) { + const teamNumber = interaction.options.getInteger("number"); + const players = interaction.options.getString("players"); + const playersArray = players.trim().split(/\s+/); - if (playersArray.length === 0 || teamNumber > playersArray.length) { + if (teamNumber > playersArray.length) { await interaction.reply({ content: "Le nombre d'équipes ne peut pas dépasser le nombre de joueurs.", - flags: MessageFlags.Ephemeral, + ephemeral: true, }); return; } const teams = Array.from({ length: teamNumber }, () => []); - shuffle(playersArray).forEach((player, index) => { - const teamIndex = index % teamNumber; - teams[teamIndex].push(player); - }); - - const teamList = teams - .map((team, index) => `${index + 1}. ${team.join(", ")}`) - .join("\n"); - await interaction.reply(`Yop ! Voici les équipes proposées :\n\n${teamList}`); - }, -}; - -export { command, parsePlayers }; + const shuffledPlayers = [...playersArray]; + for (let index = shuffledPlayers.length - 1; index > 0; index--) { + const randomIndex = Math.floor(Math.random() * (index + 1)); + [shuffledPlayers[index], shuffledPlayers[randomIndex]] = [ + shuffledPlayers[randomIndex], + 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 }; diff --git a/src/commands/jukebox/play.js b/src/commands/jukebox/play.js deleted file mode 100644 index 6bb1e65..0000000 --- a/src/commands/jukebox/play.js +++ /dev/null @@ -1,131 +0,0 @@ -/** - * @file Commande /play : ajoute à la file un fichier joint, un lien direct ou un morceau de la - * bibliothèque (avec autocomplétion), en passant par le même ajout que la page web. - */ - -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 deleted file mode 100644 index 031f509..0000000 --- a/src/commands/jukebox/queue.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @file Commande /queue : montre, à la seule personne qui la lance, le morceau en cours et les dix - * suivants. - */ - -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 deleted file mode 100644 index b460b7a..0000000 --- a/src/commands/jukebox/skip.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @file Commande /skip : passe au morceau suivant du jukebox. - */ - -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 bce1251..dc7a194 100644 --- a/src/commands/utility/deletemsgs.js +++ b/src/commands/utility/deletemsgs.js @@ -1,15 +1,10 @@ -/** - * @file Commande /deletemsgs : supprime les 100 derniers messages du salon, sauf les messages épinglés - * et ceux de plus de 14 jours, que Discord refuse de supprimer en lot. - */ - -import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; +import { 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 les 100 derniers messages, sauf ceux épinglés") + .setDescription("Supprime tous les messages, sauf ceux épinglés") .setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages), async execute(interaction) { if (!(await requirePermission(interaction, PermissionFlagsBits.ManageMessages))) { @@ -20,29 +15,18 @@ const command = { if (!textChannel?.isTextBased() || !textChannel.messages) { await interaction.reply({ content: "Cette commande doit être utilisée dans un salon textuel.", - flags: MessageFlags.Ephemeral, + ephemeral: true, }); return; } - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + await interaction.deferReply({ ephemeral: true }); const fetched = await textChannel.messages.fetch({ limit: 100 }); const notPinned = fetched.filter((message) => !message.pinned); - // Discord refuse la suppression groupée des messages de plus de 14 jours : ils restent. const deleted = await textChannel.bulkDelete(notPinned, true); - const tooOld = notPinned.size - deleted.size; - await interaction.editReply( - [ - `Et voilà, ${deleted.size} message(s) supprimé(s) ! 🐱`, - tooOld > 0 - ? `${tooOld} message(s) de plus de 14 jours restent : Discord ne permet pas de les supprimer en lot.` - : null, - ] - .filter(Boolean) - .join("\n") - ); + 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 c8f62c0..649f2ae 100644 --- a/src/commands/utility/invitation.js +++ b/src/commands/utility/invitation.js @@ -1,9 +1,4 @@ -/** - * @file Commande /invitation : publie dans le salon le message d'invitation temporaire, après avoir - * vérifié le lien (option `lien` ou INVITE_LINK) et le droit du bot à y écrire. - */ - -import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; +import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { config } from "../../config.js"; import { requirePermission } from "../../features/permissions.js"; import { @@ -45,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.", - flags: MessageFlags.Ephemeral, + ephemeral: true, }); return; } @@ -54,12 +49,12 @@ const command = { if (!input) { await interaction.reply({ content: "Aucun lien : passe l'option `lien` ou définis `INVITE_LINK`.", - flags: MessageFlags.Ephemeral, + ephemeral: true, }); return; } - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + await interaction.deferReply({ ephemeral: true }); if (!botCanPost(interaction)) { await interaction.editReply(NO_ACCESS_MESSAGE); diff --git a/src/commands/utility/listcommand.js b/src/commands/utility/listcommand.js index 48fd5fd..ea192b3 100644 --- a/src/commands/utility/listcommand.js +++ b/src/commands/utility/listcommand.js @@ -1,36 +1,28 @@ -/** - * @file Commande /listcommand : liste les commandes chargées par catégorie, avec leur description ; - * une nouvelle commande y apparaît sans rien modifier ici. - */ - -import { MessageFlags, SlashCommandBuilder } from "discord.js"; - -// Liste construite à partir des commandes chargées : une commande ajoutée y apparaît d'office, -// avec sa description. -function buildCommandList(commands) { - const byCategory = new Map(); - for (const command of commands) { - const lines = byCategory.get(command.category) ?? []; - lines.push(`\`/${command.data.name}\` : ${command.data.description}`); - byCategory.set(command.category, lines); - } - - const sections = [...byCategory].map( - ([category, lines]) => `__${category}__\n${lines.join("\n")}` - ); - return `Voilà la liste des commandes que tu peux utiliser :\n\n${sections.join("\n\n")}`; -} - -const command = { - data: new SlashCommandBuilder() - .setName("listcommand") - .setDescription("Affiche la liste des commandes disponibles"), - async execute(interaction) { - await interaction.reply({ - content: buildCommandList(interaction.client.commands.values()), - flags: MessageFlags.Ephemeral, - }); - }, -}; - -export { buildCommandList, command }; +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 }; diff --git a/src/commands/utility/ping.js b/src/commands/utility/ping.js index fed5a10..46190ad 100644 --- a/src/commands/utility/ping.js +++ b/src/commands/utility/ping.js @@ -1,16 +1,12 @@ -/** - * @file Commande /ping : vérifie que le bot répond. - */ - -import { MessageFlags, SlashCommandBuilder } from "discord.js"; - -const command = { +import { SlashCommandBuilder } from "discord.js"; + +const command = { data: new SlashCommandBuilder() - .setName("ping") - .setDescription("Répond avec Pong"), + .setName("ping") + .setDescription("Reponds avec Pong"), async execute(interaction) { - await interaction.reply({ content: "Euh... Pong ! 🐱", flags: MessageFlags.Ephemeral }); - }, -}; - -export { command }; + await interaction.reply({ content: "Euh... Pong ! 🐱", ephemeral: true }); + }, +}; + +export { command }; diff --git a/src/commands/vocal/deafall.js b/src/commands/vocal/deafall.js index 081c0b0..9ec7ec5 100644 --- a/src/commands/vocal/deafall.js +++ b/src/commands/vocal/deafall.js @@ -1,24 +1,17 @@ -/** - * @file Commande /deafall : rend sourds tous les membres humains du salon vocal de la personne qui la - * lance (à défaut, du salon configuré). - */ - import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; -import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.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("Rend tout le monde sourd dans le salon vocal") + .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(commandVoiceChannel(interaction), "deaf"); - await interaction.editReply("On n'entends plus rien ! 🐱"); - }, -}; - -export { command }; + await changeVoiceStatus(interaction.client, "deaf", "all"); + await interaction.reply("On n'entends plus rien ! 🐱"); + }, +}; + +export { command }; diff --git a/src/commands/vocal/muteall.js b/src/commands/vocal/muteall.js index af9de79..86f5dda 100644 --- a/src/commands/vocal/muteall.js +++ b/src/commands/vocal/muteall.js @@ -1,24 +1,17 @@ -/** - * @file Commande /muteall : rend muets tous les membres humains du salon vocal de la personne qui la - * lance (à défaut, du salon configuré). - */ - import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; -import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.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("Rend tout le monde muet dans le salon vocal") + .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(commandVoiceChannel(interaction), "mute"); - await interaction.editReply("Voila, tout le monde est mioute ! 🐱"); - }, -}; - -export { command }; + await changeVoiceStatus(interaction.client, "mute", "all"); + await interaction.reply("Voila, tout le monde est mioute ! 🐱"); + }, +}; + +export { command }; diff --git a/src/commands/vocal/undeafall.js b/src/commands/vocal/undeafall.js index 7a1cf2e..878b82d 100644 --- a/src/commands/vocal/undeafall.js +++ b/src/commands/vocal/undeafall.js @@ -1,24 +1,17 @@ -/** - * @file Commande /undeafall : rend l'ouïe à tous les membres humains du salon vocal de la personne qui - * la lance (à défaut, du salon configuré). - */ - import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; -import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.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("Rend l'ouïe à tout le monde dans le salon vocal") + .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(commandVoiceChannel(interaction), "undeaf"); - await interaction.editReply("Voila, les oreilles sont réparées ! 🐱"); - }, -}; - -export { command }; + await changeVoiceStatus(interaction.client, "undeaf", "all"); + await interaction.reply("Voila, les oreilles sont réparées ! 🐱"); + }, +}; + +export { command }; diff --git a/src/commands/vocal/unmuteall.js b/src/commands/vocal/unmuteall.js index a66baff..cb83668 100644 --- a/src/commands/vocal/unmuteall.js +++ b/src/commands/vocal/unmuteall.js @@ -1,24 +1,17 @@ -/** - * @file Commande /unmuteall : rend la parole à tous les membres humains du salon vocal de la personne - * qui la lance (à défaut, du salon configuré). - */ - import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; -import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.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("Rend la parole à tout le monde dans le salon vocal") + .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(commandVoiceChannel(interaction), "unmute"); - await interaction.editReply("Et.... unmioute ! 🐱"); - }, -}; - -export { command }; + await changeVoiceStatus(interaction.client, "unmute", "all"); + await interaction.reply("Et.... unmioute ! 🐱"); + }, +}; + +export { command }; diff --git a/src/config.js b/src/config.js index 4f2edc1..0afe09d 100644 --- a/src/config.js +++ b/src/config.js @@ -1,19 +1,7 @@ -/** - * @file Lit et valide les variables d'environnement au chargement, puis expose la configuration figée. - * - * Utilisé par : la plupart des modules du bot et du serveur web, via `config`. - * Attention : une variable obligatoire manquante ou invalide fait échouer le démarrage ; les tests - * définissent donc process.env avant d'importer un module qui en dépend. - * @see README.md#configuration - */ - -// OWNER_USER_ID : la personne qui gère les serveurs de jeux (mentionnée dans leur message). -// Ancien nom, encore accepté : SHINUWA_USER_ID. -process.env.OWNER_USER_ID ||= process.env.SHINUWA_USER_ID; - const requiredVariables = [ + "NODE_ENV", "DISCORD_GUILD_ID", - "OWNER_USER_ID", + "SHINUWA_USER_ID", "WEB_SERVER_PORT", "WEB_API_KEY", "DISCORD_APPLICATION_ID", @@ -53,52 +41,19 @@ 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"); } const config = Object.freeze({ + environnement: process.env.NODE_ENV, discordGuildId: process.env.DISCORD_GUILD_ID, - ownerUserId: process.env.OWNER_USER_ID, + shinuwaUserId: process.env.SHINUWA_USER_ID, webServerPort, webApiKey: process.env.WEB_API_KEY, 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 2b430a3..435e7a1 100644 --- a/src/events/interactionCreate.js +++ b/src/events/interactionCreate.js @@ -1,53 +1,36 @@ -/** - * @file Aiguille les commandes slash et l'autocomplétion vers leur commande, et prévient la personne - * quand une commande échoue. - */ - -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); - 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); - - 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 }; +import { Events } from "discord.js"; + +const event = { + name: Events.InteractionCreate, + async execute(interaction) { + 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 }; diff --git a/src/events/ready.js b/src/events/ready.js index a1ed092..d45a1df 100644 --- a/src/events/ready.js +++ b/src/events/ready.js @@ -1,25 +1,20 @@ -/** - * @file Au démarrage du bot, relance la file du jukebox si quelqu'un est déjà dans le salon vocal et - * publie l'état des serveurs de jeux. - */ - 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}` - ); - - // File rechargée au démarrage : reprendre si quelqu'un est déjà dans le salon vocal. - client.musicQueue?.evaluateAloneStatus(); - - // Les erreurs sont journalisées et retentées par showGameServers lui-même. - await showGameServers(client); + console.log( + `[${new Date().toLocaleString()}] Logged in as ${client.user.tag}` + ); + + try { + await showGameServers(client); + } catch (error) { + console.error("Unable to initialize game server status", error); + } }, }; - -export { event }; + +export { event }; diff --git a/src/features/directMessages.js b/src/features/directMessages.js index 14fcdff..2b41404 100644 --- a/src/features/directMessages.js +++ b/src/features/directMessages.js @@ -1,20 +1,8 @@ -/** - * @file Envoie un message privé Discord à la demande d'une application de confiance (Sokko TCG : - * alertes d'expédition), avec un embed et un bouton de lien facultatifs. - * - * Utilisé par : web/routes/notifications.js. - * Attention : le texte est envoyé tel quel, sans aucune mention active. Les erreurs attendues sont - * des DirectMessageError, dont le statut HTTP est renvoyé à l'application. - * @see README.md#messages-privés-pour-les-applications - */ - -import { ButtonStyle, ComponentType } from "discord.js"; +// Envoie un message privé Discord à la demande d'une application de confiance (Sokko TCG : alertes d'expédition). +// Le texte est envoyé tel quel, sans aucune mention active. const USER_ID_PATTERN = /^\d{17,20}$/; const MAX_CONTENT_LENGTH = 2000; -// Limites des embeds Discord (titre, description, champs, pied, total des textes). -const EMBED_LIMITS = Object.freeze({ title: 256, description: 4096, fields: 25, fieldName: 256, fieldValue: 1024, footer: 2048, total: 6000 }); -const MAX_LINK_LABEL = 80; // Codes de l'API Discord : utilisateur inconnu, messages privés impossibles (aucun serveur commun ou messages fermés). const UNKNOWN_USER = 10013; const CANNOT_SEND = 50007; @@ -27,82 +15,16 @@ class DirectMessageError extends Error { } } -const invalid = (message) => new DirectMessageError(400, "INVALID_EMBED", message); - -function isHttpsUrl(value) { - try { - return typeof value === "string" && value.length <= 2048 && new URL(value).protocol === "https:"; - } catch { - return false; - } -} - -function text(value, max, label, { required = false } = {}) { - if (value == null && !required) return undefined; - if (typeof value !== "string" || !value.trim() || value.length > max) throw invalid(`${label} vide ou de plus de ${max} caractères`); - return value; -} - -// Embed accepté : titre obligatoire ; description, adresse, couleur, vignette, champs, pied et horodatage facultatifs. -function buildEmbed(embed) { - if (embed == null) return null; - if (typeof embed !== "object" || Array.isArray(embed)) throw invalid("Embed invalide"); - const result = { title: text(embed.title, EMBED_LIMITS.title, "Titre", { required: true }) }; - if (embed.description != null) result.description = text(embed.description, EMBED_LIMITS.description, "Description"); - if (embed.url != null) { - if (!isHttpsUrl(embed.url)) throw invalid("Adresse de l'embed invalide : https uniquement"); - result.url = embed.url; - } - if (embed.color != null) { - if (!Number.isInteger(embed.color) || embed.color < 0 || embed.color > 0xffffff) throw invalid("Couleur invalide"); - result.color = embed.color; - } - if (embed.thumbnail != null) { - if (!isHttpsUrl(embed.thumbnail)) throw invalid("Vignette invalide : https uniquement"); - result.thumbnail = { url: embed.thumbnail }; - } - if (embed.fields != null) { - if (!Array.isArray(embed.fields) || embed.fields.length > EMBED_LIMITS.fields) throw invalid(`${EMBED_LIMITS.fields} champs au plus`); - result.fields = embed.fields.map((field) => ({ - name: text(field?.name, EMBED_LIMITS.fieldName, "Nom de champ", { required: true }), - value: text(field?.value, EMBED_LIMITS.fieldValue, "Valeur de champ", { required: true }), - inline: field?.inline === true - })); - } - if (embed.footer != null) result.footer = { text: text(embed.footer, EMBED_LIMITS.footer, "Pied") }; - if (embed.timestamp != null) { - const date = new Date(embed.timestamp); - if (Number.isNaN(date.getTime())) throw invalid("Horodatage invalide"); - result.timestamp = date.toISOString(); - } - const total = [result.title, result.description, result.footer?.text, ...(result.fields || []).flatMap((field) => [field.name, field.value])].filter(Boolean).join("").length; - if (total > EMBED_LIMITS.total) throw invalid(`Embed de plus de ${EMBED_LIMITS.total} caractères`); - return result; -} - -// Bouton de lien sous le message : un libellé et une adresse https. -function buildLink(link) { - if (link == null) return null; - if (typeof link !== "object" || !isHttpsUrl(link.url)) throw invalid("Lien invalide : https uniquement"); - const label = text(link.label, MAX_LINK_LABEL, "Libellé du lien", { required: true }); - return { type: ComponentType.ActionRow, components: [{ type: ComponentType.Button, style: ButtonStyle.Link, label, url: link.url }] }; -} - -async function sendDirectMessage(client, { userId, content, embed = null, link = null } = {}) { +async function sendDirectMessage(client, { userId, content } = {}) { if (typeof userId !== "string" || !USER_ID_PATTERN.test(userId)) { throw new DirectMessageError(400, "INVALID_USER", "Identifiant Discord invalide"); } if (typeof content !== "string" || !content.trim() || content.length > MAX_CONTENT_LENGTH) { throw new DirectMessageError(400, "INVALID_CONTENT", `Message vide ou de plus de ${MAX_CONTENT_LENGTH} caractères`); } - const message = { content, allowedMentions: { parse: [] } }; - const builtEmbed = buildEmbed(embed); - const row = buildLink(link); - if (builtEmbed) message.embeds = [builtEmbed]; - if (row) message.components = [row]; try { const user = await client.users.fetch(userId); - await user.send(message); + await user.send({ content, allowedMentions: { parse: [] } }); } catch (error) { if (error?.code === UNKNOWN_USER) { throw new DirectMessageError(404, "UNKNOWN_USER", "Utilisateur Discord introuvable"); diff --git a/src/features/formatTrack.js b/src/features/formatTrack.js deleted file mode 100644 index 6e42919..0000000 --- a/src/features/formatTrack.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * @file Formate un morceau pour les messages Discord : titre, durée lisible et, pour un morceau - * interrompu, sa position de reprise. - * - * Utilisé par : les commandes /play, /queue et /skip. - * Attention : la page web a son propre formatDuration (public/scripts/common.js). - */ - -// 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 details = [formatDuration(track.duration)]; - if (track.resumeAt > 0) { - details.push(`reprise à ${formatDuration(track.resumeAt)}`); - } - const text = details.filter(Boolean).join(", "); - return text ? `${title} (${text})` : title; -} - -export { formatDuration, trackLabel }; diff --git a/src/features/invitation.js b/src/features/invitation.js index 0e79871..189da93 100644 --- a/src/features/invitation.js +++ b/src/features/invitation.js @@ -1,13 +1,5 @@ -/** - * @file Vérifie le lien et rédige le message d'invitation : les membres ne peuvent pas créer - * d'invitations, le bot publie un seul lien à adhésion temporaire. - * - * Utilisé par : la commande /invitation. - * Attention : une invitation permanente est refusée ; pour garder quelqu'un, on lui donne un rôle. - * Sans la permission « Gérer le serveur », le bot ne peut pas vérifier qu'elle est temporaire. - * @see README.md#invitations - */ - +// Message d'invitation : le serveur n'autorise pas ses membres à créer des invitations ; un seul +// lien à adhésion temporaire est partagé par le bot. Pour garder quelqu'un, on lui donne un rôle. import { codeBlock, DiscordjsErrorCodes } from "discord.js"; const INVITE_URL_PATTERN = diff --git a/src/features/permissions.js b/src/features/permissions.js index f6753be..268ad95 100644 --- a/src/features/permissions.js +++ b/src/features/permissions.js @@ -1,14 +1,3 @@ -/** - * @file Vérifie qu'une personne a une permission Discord avant une commande d'administration, et lui - * répond sinon. - * - * Utilisé par : /deletemsgs, /invitation et les commandes vocales. - * Attention : setDefaultMemberPermissions ne fait que masquer la commande, et les administrateurs du - * serveur peuvent changer ce réglage : cette vérification reste la vraie protection. - */ - -import { MessageFlags } from "discord.js"; - async function requirePermission(interaction, permission) { if (interaction.memberPermissions?.has(permission)) { return true; @@ -16,7 +5,7 @@ async function requirePermission(interaction, permission) { await interaction.reply({ content: "Tu n'as pas la permission d'utiliser cette commande.", - flags: MessageFlags.Ephemeral, + ephemeral: true, }); return false; } diff --git a/src/features/showGameServers.js b/src/features/showGameServers.js index 276e912..f037f00 100644 --- a/src/features/showGameServers.js +++ b/src/features/showGameServers.js @@ -1,116 +1,61 @@ -/** - * @file Tient à jour le message des serveurs de jeux dans le salon textuel configuré : état sondé en - * TCP ou saisi à la main, rafraîchi toutes les deux minutes. - * - * Utilisé par : events/ready.js, au démarrage. - * Attention : la liste est relue dans src/static/gameservers-list.json (absent du dépôt, modèle - * gameservers-list.example.json) à chaque rafraîchissement ; le message n'est réédité que si son - * contenu change. - * @see README.md#données-persistantes - */ - -import net from "node:net"; import { config } from "../config.js"; -import { getJSONData } from "./utilities.js"; - -const PROBE_TIMEOUT = 3_000; -const REFRESH_INTERVAL = 120_000; -// Couleurs ANSI des blocs « ```ansi » de Discord. Échappements écrits en \u001b : un caractère -// ESC brut est invisible dans l'éditeur et a déjà disparu lors d'une modification. -const ONLINE = "\u001b[2;32mOnline\u001b[0m"; -const OFFLINE = "\u001b[2;31mOffline\u001b[0m"; - -// Dernier message publié : on ne le réédite que si son contenu change (état d'un serveur, -// mais aussi serveur ajouté ou adresse modifiée dans la liste). -let publishedMessage = null; - -// 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 }; -} - -function buildMessage(data) { - const servers = data.servers - .map( - (server) => - "```ansi\n" + - `${server.game} : ${server.active ? ONLINE : OFFLINE}\n` + - `${server.address}\n` + - "```" - ) - .join(""); - - return ( - "Hello 😺 ! Voila les serveurs de jeux qu'on a chez nous :\n\n" + - servers + - `\nPour mettre en ligne un serveur, faut voir avec <@${config.ownerUserId}> , c'est lui qui gère ca !\n` - ); -} - -async function refreshMessage(client) { - const content = buildMessage(await readServers()); - if (content === publishedMessage) { - return false; - } - +import { getJSONData } from "./utilities.js"; + +var currentStatus = []; + +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; + } + + await updateMessage(client, data); + 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` + + "```"; + }); + + newMessage = + 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"); } const message = await channel.messages.fetch(config.gameServersMessageId); - await message.edit(content); - publishedMessage = content; + await message.edit(newMessage); console.log( `[${new Date().toLocaleString()}] showGameServers: Game servers message updated` ); - return true; } -// Un échec (salon ou message introuvable, liste illisible) est journalisé et retenté au -// rafraîchissement suivant, y compris au démarrage. -function showGameServers(client) { - const refresh = () => - refreshMessage(client).catch((error) => +async function showGameServers(client) { + const data = getJSONData("src/static/gameservers-list.json"); + 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) ); - setInterval(refresh, REFRESH_INTERVAL).unref(); - return refresh(); -} - -export { buildMessage, probeTcp, serverStatus, showGameServers }; + }, 120000); + interval.unref(); +} + +export { showGameServers }; diff --git a/src/features/tags.js b/src/features/tags.js deleted file mode 100644 index 042881d..0000000 --- a/src/features/tags.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @file Étiquettes des morceaux de la bibliothèque : nettoyage de la liste envoyée par la page et - * comparaison sans tenir compte des majuscules. - * - * Utilisé par : web/routes/library.js (modification d'un morceau, ajout à la file par étiquette). - * Attention : la virgule sépare les étiquettes dans la page ; elle est donc retirée d'une étiquette. - * « Calme » et « calme » sont la même étiquette : la première écriture reçue est gardée. - */ - -const MAX_TAGS = 15; -const MAX_TAG_LENGTH = 30; - -// Clé de comparaison d'une étiquette. -function tagKey(tag) { - return String(tag).toLocaleLowerCase("fr"); -} - -// Liste d'étiquettes propre (sans doublon, ni vide, ni caractère de contrôle), ou null si -// `value` n'est pas un tableau. -function cleanTags(value) { - if (!Array.isArray(value)) return null; - const tags = new Map(); - for (const raw of value) { - const tag = String(raw ?? "") - .replace(/[\u0000-\u001f,]/g, " ") - .replace(/\s+/g, " ") - .trim() - .slice(0, MAX_TAG_LENGTH) - .trim(); - if (tag && !tags.has(tagKey(tag))) { - tags.set(tagKey(tag), tag); - } - } - return [...tags.values()].slice(0, MAX_TAGS); -} - -function hasTag(entry, tag) { - const key = tagKey(tag); - return (entry.tags ?? []).some((item) => tagKey(item) === key); -} - -export { cleanTags, hasTag }; diff --git a/src/features/utilities.js b/src/features/utilities.js index 97ae8e9..9bd332d 100644 --- a/src/features/utilities.js +++ b/src/features/utilities.js @@ -1,75 +1,67 @@ -/** - * @file Petits outils partagés : salon vocal d'une commande, membres rendus muets ou sourds en groupe, - * lecture d'un JSON, tirage au hasard et mélange. - * - * Utilisé par : les commandes vocales, /dice, /maketeam, showGameServers.js, music/queue.js et - * web/routes/library.js. - */ - -import fs from "node:fs"; +import fs from "fs"; import { config } from "../config.js"; + +async function changeVoiceStatus(client, status, members) { + const changeStatus = async (type, value, selectedMembers) => { + const operations = []; + switch (type) { + case "mute": + for (const member of selectedMembers.values()) { + operations.push(member.voice.setMute(value)); + } + break; + case "deaf": + for (const member of selectedMembers.values()) { + operations.push(member.voice.setDeaf(value)); + } + break; + } + await Promise.all(operations); + }; -const VOICE_ACTIONS = { - mute: (member) => member.voice.setMute(true), - unmute: (member) => member.voice.setMute(false), - deaf: (member) => member.voice.setDeaf(true), - undeaf: (member) => member.voice.setDeaf(false), -}; - -// Salon vocal où se trouve la personne qui lance la commande, sinon celui de la configuration. -function commandVoiceChannel(interaction) { - const channel = - interaction.member?.voice?.channel ?? - interaction.client.channels.cache.get(config.voiceChannelId); - if (!channel?.isVoiceBased()) { + const voiceChannel = client.channels.cache.get(config.voiceChannelId); + if (!voiceChannel?.isVoiceBased()) { throw new Error("Salon vocal configuré introuvable"); } - return channel; -} + const connectedMembers = voiceChannel.members.filter( + (member) => !member.user.bot + ); -// Applique l'action à tous les membres humains du salon. -async function changeVoiceStatus(channel, action) { - const apply = VOICE_ACTIONS[action]; - if (!apply) { - throw new Error(`Statut vocal inconnu : ${action}`); + if (members === "all") { + members = connectedMembers; } - const members = channel.members.filter((member) => !member.user.bot); - // Un membre qui quitte le salon pendant l'opération ne doit pas faire échouer les autres. - const results = await Promise.allSettled(members.map(apply)); - 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 - ); + switch (status) { + case "mute": + await changeStatus("mute", true, members); + break; + case "unmute": + await changeStatus("mute", false, members); + break; + case "deaf": + await changeStatus("deaf", true, members); + break; + case "undeaf": + await changeStatus("deaf", false, members); + break; + default: + 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); -} - -// Mélange de Fisher-Yates, sur place ; renvoie le tableau. -function shuffle(array) { - for (let index = array.length - 1; index > 0; index--) { - const randomIndex = getRandomInt(index + 1); - [array[index], array[randomIndex]] = [array[randomIndex], array[index]]; - } - return array; -} - + +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, - commandVoiceChannel, getJSONData, getRandomInt, - shuffle, }; diff --git a/src/loadCommands.js b/src/loadCommands.js deleted file mode 100644 index 8551f8e..0000000 --- a/src/loadCommands.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * @file Charge les commandes slash de src/commands//*.js et leur donne leur catégorie. - * - * Utilisé par : index.js (exécution) et deployCommands.js (enregistrement auprès de Discord). - * Attention : un nouveau dossier de commandes s'ajoute à CATEGORY_LABELS pour avoir un nom lisible - * dans /listcommand. - */ - -import fs from "node:fs"; -import path from "node:path"; -import { fileURLToPath, pathToFileURL } from "node:url"; - -const COMMANDS_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "commands"); - -// Nom affiché de chaque dossier de src/commands (catégorie de /listcommand). -const CATEGORY_LABELS = { - utility: "Utilitaires", - jukebox: "Jukebox", - vocal: "Vocal", - game: "Jeux", -}; - -// Charge les commandes de src/commands//*.js. Chaque fichier exporte -// `command = { data, execute, autocomplete? }`. -async function loadCommands() { - const commands = []; - const folders = fs - .readdirSync(COMMANDS_DIR, { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) - .map((entry) => entry.name) - .sort(); - - for (const folder of folders) { - const files = fs - .readdirSync(path.join(COMMANDS_DIR, folder)) - .filter((file) => file.endsWith(".js")) - .sort(); - for (const file of files) { - const filePath = path.join(COMMANDS_DIR, folder, file); - const { command } = await import(pathToFileURL(filePath).href); - if (!command?.data || typeof command.execute !== "function") { - console.warn(`[WARNING] The command at ${filePath} is missing "data" or "execute".`); - continue; - } - commands.push({ ...command, category: CATEGORY_LABELS[folder] ?? folder }); - } - } - return commands; -} - -export { loadCommands }; diff --git a/src/media/coverArt.js b/src/media/coverArt.js deleted file mode 100644 index e24a965..0000000 --- a/src/media/coverArt.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @file Fabrique les pochettes des morceaux avec ffmpeg : une image envoyée, ou la pochette intégrée - * à un fichier audio, devient un JPEG d'au plus 512 px de côté. - * - * Utilisé par : web/storage/libraryCovers.js. - * Attention : une image envoyée n'est passée à ffmpeg qu'après lecture de sa signature (PNG, JPEG, - * WebP ou GIF), avec le décodeur de ce format imposé : ffmpeg ne doit jamais deviner le format - * d'un fichier inconnu (une liste de lecture HLS pourrait lui faire lire des fichiers locaux). Le - * réencodage retire aussi les métadonnées de l'image d'origine. - */ - -import { execFile } from "node:child_process"; -import fs from "node:fs/promises"; -import { promisify } from "node:util"; - -const execFileAsync = promisify(execFile); -const COVER_SIZE = 512; - -// Signature de début de fichier → décodeur ffmpeg à imposer. -const IMAGE_FORMATS = [ - { demuxer: "png_pipe", matches: (bytes) => bytes.subarray(0, 8).equals(Buffer.from("\x89PNG\r\n\x1a\n", "latin1")) }, - { demuxer: "jpeg_pipe", matches: (bytes) => bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff }, - { demuxer: "gif", matches: (bytes) => /^GIF8[79]a$/.test(bytes.toString("latin1", 0, 6)) }, - { - demuxer: "webp_pipe", - matches: (bytes) => - bytes.toString("latin1", 0, 4) === "RIFF" && bytes.toString("latin1", 8, 12) === "WEBP", - }, -]; - -// Décodeur ffmpeg correspondant à l'image, ou null si ce n'est pas un format accepté. -async function detectImageFormat(filePath) { - const handle = await fs.open(filePath, "r"); - try { - const bytes = Buffer.alloc(12); - const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0); - if (bytesRead < bytes.length) return null; - return IMAGE_FORMATS.find((format) => format.matches(bytes))?.demuxer ?? null; - } finally { - await handle.close(); - } -} - -// Écrit en JPEG la première image de inputPath (image seule, ou pochette d'un fichier audio). -// Échoue si le fichier n'en contient pas. inputFormat impose le décodeur ffmpeg. -async function createCoverImage(inputPath, outputPath, { inputFormat, run = execFileAsync } = {}) { - await run( - "ffmpeg", - [ - "-hide_banner", - "-loglevel", - "error", - ...(inputFormat ? ["-f", inputFormat] : []), - "-i", - inputPath, - "-map", - "0:v:0", - "-frames:v", - "1", - "-vf", - // Réduit à COVER_SIZE au plus, sans agrandir une image plus petite. - `scale='min(${COVER_SIZE},iw)':'min(${COVER_SIZE},ih)':force_original_aspect_ratio=decrease`, - "-c:v", - "mjpeg", - "-q:v", - "3", - "-f", - "image2", - "-y", - outputPath, - ], - { timeout: 15_000, maxBuffer: 1024 * 1024 } - ); -} - -export { createCoverImage, detectImageFormat }; diff --git a/src/media/downloadAudio.js b/src/media/downloadAudio.js deleted file mode 100644 index c9c4d75..0000000 --- a/src/media/downloadAudio.js +++ /dev/null @@ -1,207 +0,0 @@ -/** - * @file Télécharge un fichier audio depuis un lien donné par un utilisateur, en refusant les adresses - * internes (même après une redirection) et les fichiers de plus de 150 Mo. - * - * Utilisé par : /play et l'ajout par lien de la page web (web/routes/uploads.js). - * Attention : l'adresse est vérifiée pendant la résolution DNS de la connexion elle-même - * (safeLookup), pas avant : un autre client HTTP devrait lui aussi passer par safeLookup, sinon la - * protection disparaît. - */ - -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 b83182e..7cbb0aa 100644 --- a/src/media/validateAudioFile.js +++ b/src/media/validateAudioFile.js @@ -1,144 +1,35 @@ -/** - * @file Vérifie avec ffprobe qu'un fichier est de l'audio (durée, titre, artiste), et le convertit - * avec ffmpeg en Ogg Opus au volume normalisé, prêt pour Discord (depuis le début ou depuis une - * position donnée). - * - * Utilisé par : music/ingest.js et storage/libraryMetadata.js (probeAudioFile), music/queue.js - * (createOpusStream). - * Attention : ffmpeg et ffprobe doivent être installés sur la machine. Fermer le flux Opus arrête - * ffmpeg. - */ - -import { execFile, spawn } from "node:child_process"; +import { execFile } from "node:child_process"; import { promisify } from "node:util"; const execFileAsync = promisify(execFile); -// 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; +async function validateAudioFile(filePath) { try { const { stdout } = await execFileAsync( "ffprobe", [ "-v", "error", + "-select_streams", + "a:0", "-show_entries", - "format=duration:format_tags:stream=codec_type:stream_tags", + "stream=codec_type", "-of", - "json", + "default=noprint_wrappers=1:nokey=1", filePath, ], { timeout: 15_000, maxBuffer: 1024 * 1024 } ); - parsed = JSON.parse(stdout); + + if (stdout.trim() !== "audio") { + throw new Error("Aucune piste audio détectée"); + } } catch (error) { - throw invalidAudioError(error); + const validationError = new Error("Le fichier fourni n'est pas un audio valide"); + validationError.status = 400; + validationError.cause = error; + throw validationError; } - - 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), - }; } -function invalidAudioError(cause) { - const error = new Error("Le fichier fourni n'est pas un audio valide"); - error.status = 400; - error.cause = cause; - return error; -} - -// 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. -// startAt : position de départ en secondes, pour reprendre un morceau interrompu. -function createOpusStream(filePath, { spawnProcess = spawn, startAt = 0 } = {}) { - const ffmpeg = spawnProcess( - "ffmpeg", - [ - "-hide_banner", - "-loglevel", - "error", - // Placé avant -i : ffmpeg saute directement à la position au lieu de tout décoder. - ...(startAt > 0 ? ["-ss", String(startAt)] : []), - "-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 { createOpusStream, probeAudioFile }; +export { validateAudioFile }; diff --git a/src/music/ingest.js b/src/music/ingest.js deleted file mode 100644 index 41e9f7d..0000000 --- a/src/music/ingest.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @file Étape commune à tous les nouveaux morceaux (envoi web, lien, pièce jointe Discord) : vérifie - * que le fichier est de l'audio, l'enregistre, le met en file et, s'il rejoint la - * bibliothèque, reprend sa pochette intégrée. - * - * Utilisé par : /play et web/routes/uploads.js. - * Attention : le fichier doit déjà être dans storage/temp ; en cas d'échec, il est supprimé. La - * pochette est cherchée après la mise en file, pour ne pas retarder la lecture. - */ - -import { probeAudioFile } from "../media/validateAudioFile.js"; -import { fillEmbeddedCover } from "../web/storage/libraryCovers.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, sectionId = null } = {}, - { queue, probe = probeAudioFile, createCover } -) { - let track; - 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); - track = registerUploadedFile(file, { - permanent, - uploader: cleanText(uploader, 80) || "inconnu", - title: cleanText(title, 200) || defaultTitle(metadata, file.originalname), - duration: metadata.duration, - artist: metadata.artist, - sectionId, - }); - - if (enqueue) { - queue.enqueue(track); - } - } catch (error) { - discardUploadedFile(file); - throw error; - } - - if (permanent) { - await fillEmbeddedCover(track.libraryTrackId, track.path, { create: createCover }); - queue.emit("libraryUpdate"); - } - return track; -} - -export { defaultTitle, ingestAudioFile }; diff --git a/src/music/queue.js b/src/music/queue.js index 3b57729..db7692e 100644 --- a/src/music/queue.js +++ b/src/music/queue.js @@ -1,32 +1,8 @@ -/** - * @file File d'attente et lecteur du jukebox : joue les morceaux dans le salon vocal configuré et - * prévient les pages web à chaque changement. - * - * Contexte : une seule instance, créée par index.js et partagée par les commandes Discord - * (client.musicQueue) et le serveur web. - * Points d'entrée : enqueue, remove, move, skip, seek, stop, start, snapshot ; événements « queueUpdate » - * (état de la file, émis ici) et « libraryUpdate » (bibliothèque modifiée, émis par les routes). - * Utilisé par : index.js, /play, /queue, /skip, web/routes/ et music/ingest.js. - * Dépend de : @discordjs/voice, media/validateAudioFile.js (flux Opus), - * web/storage/storageManager.js (fichiers), une persistance passée au constructeur. - * Attention : - * - Sans morceau ou sans auditeur pendant 5 min, le bot quitte le salon. Parti faute d'auditeurs, - * il revient dès que quelqu'un le rejoint. - * - Un morceau temporaire est supprimé une fois joué, retiré ou en erreur, sauf en mode boucle. - * - Un morceau interrompu sans qu'on l'ait demandé (connexion vocale perdue, bot seul dans le - * salon, redémarrage) revient en tête de file avec `resumeAt` : il reprend 2 s avant l'endroit - * où il s'était arrêté. Le lecteur joue même sans connexion (NoSubscriberBehavior.Play) : la - * position d'une coupure est donc relevée dès la déconnexion, pas quand on abandonne. - * - Toute modification de la file émet « queueUpdate » : c'est aussi ce qui l'enregistre. - * @see README.md#jukebox - */ - +import fs from "fs"; import { EventEmitter } from "events"; -import { randomUUID } from "node:crypto"; import { AudioPlayerStatus, NoSubscriberBehavior, - StreamType, VoiceConnectionStatus, createAudioPlayer, createAudioResource, @@ -35,8 +11,6 @@ import { } from "@discordjs/voice"; import { Events } from "discord.js"; import { config } from "../config.js"; -import { shuffle } from "../features/utilities.js"; -import { createOpusStream } from "../media/validateAudioFile.js"; import { serializeTrack, serializeTracks } from "../web/serializers.js"; import { deleteTrackFile, @@ -44,41 +18,17 @@ 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]; - -// Secondes rejouées à la reprise d'un morceau interrompu, pour retrouver le fil. -const RESUME_REWIND = 2; -// Pendant la lecture, la position est enregistrée à cet intervalle : après un arrêt brutal du -// bot (sans arrêt propre), le morceau reprend à peu près où il en était. -const POSITION_SAVE_INTERVAL = 30_000; class MusicQueue extends EventEmitter { - // 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 } = {} - ) { + constructor(client) { 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; @@ -98,39 +48,24 @@ class MusicQueue extends EventEmitter { this.client.on(Events.VoiceStateUpdate, this.voiceStateListener); this.audioPlayer.on(AudioPlayerStatus.Idle, () => { - 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, du début, fichier conservé. - const { startedAt: _startedAt, resumeAt: _resumeAt, ...track } = finished; - this.queue.push({ ...track, id: randomUUID() }); - } else { - handleTrackCompletion(finished); - } + if (this.currentTrack) { + handleTrackCompletion(this.currentTrack); } - this.discardCurrent = false; + this.currentTrack = null; 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); - this.discardCurrent = true; + handleTrackCompletion(this.currentTrack); + this.currentTrack = null; + if (!this.shuttingDown) { + void this.playNext(); + } }); - this.on("queueUpdate", () => this.scheduleSave()); - this.restore(); - if (this.persistence) { - this.positionSaveInterval = setInterval(() => { - if (this.playbackStatus === AudioPlayerStatus.Playing) this.scheduleSave(); - }, POSITION_SAVE_INTERVAL); - this.positionSaveInterval.unref?.(); - } - this.audioPlayer.on("stateChange", (oldState, newState) => { this.playbackStatus = newState.status; this.emit("queueUpdate", this.snapshot()); @@ -142,37 +77,9 @@ class MusicQueue extends EventEmitter { current: serializeTrack(this.currentTrack), upcoming: serializeTracks(this.queue), status: this.playbackStatus, - loop: this.loop, - // Position dans le morceau en cours, en millisecondes (pauses exclues). - position: this.currentPosition(), }; } - // Position dans le fichier du morceau en cours (ms), reprise comprise : playbackDuration ne - // compte que ce qui a été joué depuis le départ du flux. - currentPosition() { - if (!this.currentTrack) return 0; - const played = this.audioPlayer?.state?.resource?.playbackDuration ?? 0; - return (this.currentTrack.resumeAt ?? 0) * 1000 + played; - } - - // Copie d'un morceau interrompu à `position` (ms), à remettre en file pour qu'il reprenne un - // peu avant cet endroit. - resumableTrack(track, position) { - const { startedAt: _startedAt, resumeAt: _resumeAt, ...rest } = track; - const resumeAt = Math.floor(position / 1000) - RESUME_REWIND; - return resumeAt > 0 ? { ...rest, resumeAt } : rest; - } - - // 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 ( @@ -215,8 +122,6 @@ class MusicQueue extends EventEmitter { this.connection = connection; connection.subscribe(this.audioPlayer); connection.on(VoiceConnectionStatus.Disconnected, async () => { - // Le lecteur continue sans connexion : la reprise se fera depuis l'instant de la coupure. - const position = this.currentPosition(); try { await Promise.race([ entersState(connection, VoiceConnectionStatus.Signalling, 5_000), @@ -224,7 +129,7 @@ class MusicQueue extends EventEmitter { ]); } catch { if (this.connection === connection) { - this.destroyConnection("voice connection lost", { requeue: true, position }); + this.destroyConnection("voice connection lost"); } } }); @@ -248,10 +153,6 @@ 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) { @@ -273,9 +174,7 @@ class MusicQueue extends EventEmitter { } async runPlayNext() { - this.cancelConnectRetry(); - - if (this.shuttingDown || this.suspendedForAlone) { + if (this.suspendedForAlone) { return; } @@ -290,27 +189,26 @@ 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) { + if ( + this.shuttingDown || + this.suspendedForAlone || + this.queue[0]?.id !== nextTrack.id + ) { 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 resource = this.createResource(nextTrack); + const stream = fs.createReadStream(nextTrack.path); + const resource = createAudioResource(stream, { + inlineVolume: true, + }); this.currentTrack = { ...nextTrack, @@ -327,48 +225,12 @@ class MusicQueue extends EventEmitter { } } - createResource(track) { - return createAudioResource(createOpusStream(track.path, { startAt: track.resumeAt }), { - 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; - } - } - - remove(trackId) { + 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 removed; + return this.currentTrack; } return null; } @@ -400,55 +262,12 @@ 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() { - shuffle(this.queue); - 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()); - } - - // Déplace la lecture du morceau en cours à `seconds`, bornée à sa durée connue. Un nouveau flux - // ffmpeg, qui démarre à cette position (resumeAt), remplace l'ancien : le lecteur ne passe pas - // par Idle, le morceau n'est donc ni terminé ni remis en boucle. En pause, la lecture repart. - // Renvoie null sans morceau en cours. - seek(seconds) { - if (!this.currentTrack) return null; - let position = Math.max(0, Math.floor(Number(seconds) || 0)); - const duration = Number(this.currentTrack.duration); - if (duration > 0) { - position = Math.min(position, Math.max(0, Math.floor(duration) - 1)); - } - const { resumeAt: _resumeAt, ...track } = this.currentTrack; - this.currentTrack = position > 0 ? { ...track, resumeAt: position } : track; - this.audioPlayer.play(this.createResource(this.currentTrack)); - this.emit("queueUpdate", this.snapshot()); - return this.snapshot(); - } - pause() { this.audioPlayer.pause(true); } @@ -459,7 +278,6 @@ class MusicQueue extends EventEmitter { start() { this.suspendedForAlone = false; - this.connectFailures = 0; this.cancelIdleDisconnect(); if (!this.currentTrack) { return this.playNext(); @@ -486,7 +304,6 @@ class MusicQueue extends EventEmitter { this.currentTrack && this.currentTrack.libraryTrackId === libraryTrackId ) { - this.discardCurrent = true; this.skip(); } @@ -497,10 +314,7 @@ class MusicQueue extends EventEmitter { return removed; } - // requeue : remet le morceau interrompu en tête de file, pour qu'il reprenne où il en était - // (à `position` ms si elle est donnée, sinon à la position actuelle), au lieu de le perdre, - // quand la coupure ne vient pas d'une demande d'arrêt. - destroyConnection(reason, { suspend = false, requeue = false, position } = {}) { + destroyConnection(reason, { suspend = false } = {}) { if (!this.connection && this.playbackStatus === AudioPlayerStatus.Idle) { return; } @@ -513,12 +327,7 @@ class MusicQueue extends EventEmitter { this.cancelAloneDisconnect(); const interruptedTrack = this.currentTrack; - const interruptedAt = position ?? this.currentPosition(); this.currentTrack = null; - const requeued = Boolean(requeue && interruptedTrack); - if (requeued) { - this.queue.unshift(this.resumableTrack(interruptedTrack, interruptedAt)); - } if (this.connection) { try { @@ -535,9 +344,7 @@ class MusicQueue extends EventEmitter { console.error("Failed to stop audio player", error); } - if (!requeued) { - handleTrackCompletion(interruptedTrack); - } + handleTrackCompletion(interruptedTrack); this.emit("queueUpdate", this.snapshot()); console.log( `[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})` @@ -577,7 +384,7 @@ class MusicQueue extends EventEmitter { this.aloneDisconnectTimeout = setTimeout(() => { this.aloneDisconnectTimeout = null; if (this.connection && this.isBotAlone()) { - this.destroyConnection("alone timeout", { suspend: true, requeue: true }); + this.destroyConnection("alone timeout", { suspend: true }); } }, AUTO_DISCONNECT_DELAY); } @@ -592,11 +399,6 @@ 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; } @@ -612,111 +414,35 @@ class MusicQueue extends EventEmitter { } } - // Membres humains du salon configuré, sans le bot lui-même ni les autres bots. - humanListeners() { - const channel = this.client.channels.cache.get(config.voiceChannelId); - const clientId = this.client.user?.id; - if (!channel || !clientId) { - return null; - } - - return [...channel.members.values()].filter( - (member) => member.id !== clientId && !member.user?.bot - ); - } - - hasListeners() { - return (this.humanListeners()?.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)) { + if (!channel) { return false; } - return this.humanListeners().length === 0; + const clientId = this.client.user?.id; + if (!clientId) { + return false; + } + + if (!channel.members.has(clientId)) { + return false; + } + + const others = channel.members.filter((member) => member.id !== clientId); + return others.size === 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); - clearInterval(this.positionSaveInterval); 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() { - const current = this.currentTrack - ? this.resumableTrack(this.currentTrack, this.currentPosition()) - : null; - return { - // Le morceau en cours reprendra en tête de file, à peu près où il en était. - queue: [current, ...this.queue].filter(Boolean), - 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 deleted file mode 100644 index 370f6fe..0000000 --- a/src/music/queuePersistence.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * @file Enregistre la file du jukebox dans storage/runtime/queue.json pour la retrouver au redémarrage. - * - * Utilisé par : index.js, qui le passe à MusicQueue (option `persistence`). - * Attention : l'écriture passe par un fichier temporaire renommé, pour ne jamais laisser un JSON à - * moitié écrit ; au chargement, les morceaux dont le fichier a disparu sont ignorés. - */ - -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 6fe4c99..a251775 100644 --- a/src/static/gameservers-list.example.json +++ b/src/static/gameservers-list.example.json @@ -1,23 +1,10 @@ { "servers": [ { - "game": "Nom du jeu (état saisi à la main)", + "game": "Nom du jeu", "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 deleted file mode 100644 index 0fe72fe..0000000 --- a/src/web/auth/session.js +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @file Sessions de la connexion avec Discord, sans stockage côté serveur : jeton signé par HMAC dans - * un cookie, et lecture et écriture des cookies. - * - * Utilisé par : web/routes/auth.js. - * Attention : changer SESSION_SECRET déconnecte tout le monde ; une session dure 30 jours et ne peut - * pas être révoquée avant. - * @see README.md#connexion-avec-discord - */ - -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 695c286..f6ed74a 100644 --- a/src/web/middlewares/auth.js +++ b/src/web/middlewares/auth.js @@ -1,12 +1,3 @@ -/** - * @file Contrôles d'accès des routes web : clé d'API (Bearer), clé ou session Discord pour le jukebox, - * connexions locales seulement pour les applications. - * - * Utilisé par : web/server.js. - * Attention : avec une session (cookie), une requête qui modifie quelque chose doit venir du site - * lui-même (en-tête Origin). localOnly lit l'adresse de la socket, pas req.ip. - */ - import { config } from "../../config.js"; import { createHash, timingSafeEqual } from "node:crypto"; @@ -39,25 +30,6 @@ 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) { @@ -73,4 +45,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, createJukeboxAuth, isLoopbackAddress, localOnly }; +export { authMiddleware, createBearerAuth, isLoopbackAddress, localOnly }; diff --git a/src/web/routes/auth.js b/src/web/routes/auth.js deleted file mode 100644 index fae3e58..0000000 --- a/src/web/routes/auth.js +++ /dev/null @@ -1,135 +0,0 @@ -/** - * @file Connexion avec Discord (OAuth2, portée « identify ») réservée aux membres du serveur, et - * lecture de la session à chaque requête. - * - * Utilisé par : web/server.js (routes /auth et sessionMiddleware). - * Attention : sans DISCORD_CLIENT_SECRET, WEB_PUBLIC_URL et SESSION_SECRET, les routes de connexion - * répondent 404 ; /auth/me répond toujours, pour que la page sache quoi proposer. - * @see README.md#connexion-avec-discord - */ - -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, `/?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, "/"); - } 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/coverUpload.js b/src/web/routes/coverUpload.js deleted file mode 100644 index f6d19af..0000000 --- a/src/web/routes/coverUpload.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @file Réception d'une image envoyée depuis la page (pochette d'un morceau, image d'une section) : - * middleware d'envoi et traitement commun aux deux routes. - * - * Utilisé par : web/routes/library.js et librarySections.js. - * Attention : le fichier reçu dans storage/temp est toujours supprimé, que l'image soit acceptée ou - * non ; seule sa conversion reste, dans storage/covers. - */ - -import multer from "multer"; -import { saveCoverFromImage } from "../storage/libraryCovers.js"; -import { deleteCoverFile, discardUploadedFile, TEMP_DIR } from "../storage/storageManager.js"; - -const MAX_COVER_SIZE = 10 * 1024 * 1024; - -// Champ « cover », une seule image. -const coverUpload = multer({ - dest: TEMP_DIR, - limits: { fileSize: MAX_COVER_SIZE, files: 1, fields: 0 }, -}).single("cover"); - -// Convertit l'image reçue, puis apply(nom) l'attache à son élément et renvoie la réponse JSON, -// ou null si l'élément n'existe plus (404, la nouvelle image est alors supprimée). -async function handleCoverUpload(req, res, apply) { - if (!req.file) { - return res.status(400).json({ error: "Aucune image reçue" }); - } - try { - const cover = await saveCoverFromImage(req.file.path); - const body = apply(cover); - if (!body) { - deleteCoverFile(cover); - return res.status(404).json({ error: "Élément introuvable" }); - } - return res.json(body); - } finally { - discardUploadedFile(req.file); - } -} - -export { coverUpload, handleCoverUpload }; diff --git a/src/web/routes/events.js b/src/web/routes/events.js deleted file mode 100644 index b35e035..0000000 --- a/src/web/routes/events.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @file Flux d'événements en direct (Server-Sent Events) vers la page du jukebox : état de la file à - * chaque changement, et signal quand la bibliothèque change. - * - * Utilisé par : web/server.js (/api/events) ; lu par public/scripts/jukebox.js. - * Attention : chaque page ouverte garde une connexion ; ses écoutes sur la file sont retirées à la - * fermeture. Un commentaire envoyé toutes les 25 s empêche le proxy de couper la connexion. - */ - -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 6469426..3087db3 100644 --- a/src/web/routes/library.js +++ b/src/web/routes/library.js @@ -1,45 +1,17 @@ -/** - * @file Routes /api/library : liste la bibliothèque et ses sections, modifie un morceau (titre, - * section, étiquettes, pochette), le supprime, et ajoute à la file un morceau, ou tous ceux - * d'une section et/ou d'une étiquette. - * - * Utilisé par : web/server.js ; appelé par la page du jukebox. - * Attention : chaque changement émet « libraryUpdate » sur la file, que le flux /api/events relaie - * aux pages ouvertes. - */ - import { Router } from "express"; -import { setTrackCover } from "../storage/libraryCovers.js"; -import { findSection, getSections } from "../storage/librarySections.js"; import { createQueueTrackFromLibrary, deletePermanentTrack, findPermanentTrack, getPermanentLibrary, - updatePermanentTracks, } from "../storage/storageManager.js"; -import { serializeSections, serializeTrack, serializeTracks } from "../serializers.js"; -import { cleanTags, hasTag } from "../../features/tags.js"; -import { shuffle } from "../../features/utilities.js"; -import { coverUpload, handleCoverUpload } from "./coverUpload.js"; -import { librarySectionsRouter } from "./librarySections.js"; - -function cleanTitle(value) { - return String(value ?? "") - .replace(/[\u0000-\u001f]/g, "") - .trim() - .slice(0, 200); -} +import { serializeTrack, serializeTracks } from "../serializers.js"; function libraryRouter({ queue }) { const router = Router(); - router.use("/sections", librarySectionsRouter({ queue })); router.get("/", (req, res) => { - res.json({ - tracks: serializeTracks(getPermanentLibrary()), - sections: serializeSections(getSections()), - }); + res.json({ tracks: serializeTracks(getPermanentLibrary()) }); }); router.delete("/:libraryId", (req, res) => { @@ -50,87 +22,9 @@ function libraryRouter({ queue }) { } queue.removeByLibraryId(track.id); - queue.emit("libraryUpdate"); res.json({ removed: serializeTrack(track) }); }); - // Corps : title, sectionId (null : sans section) et/ou tags (liste complète, [] pour aucune). - router.patch("/:libraryId", (req, res) => { - const fields = {}; - if (req.body?.title !== undefined) { - fields.title = cleanTitle(req.body.title); - if (!fields.title) { - return res.status(400).json({ error: "Titre manquant" }); - } - } - if (req.body?.sectionId !== undefined) { - const { sectionId } = req.body; - if (sectionId !== null && !findSection(sectionId)) { - return res.status(400).json({ error: "Section introuvable" }); - } - fields.sectionId = sectionId; - } - if (req.body?.tags !== undefined) { - fields.tags = cleanTags(req.body.tags); - if (!fields.tags) { - return res.status(400).json({ error: "Les étiquettes doivent être une liste" }); - } - } - if (Object.keys(fields).length === 0) { - return res.status(400).json({ error: "Rien à modifier" }); - } - - const [track] = updatePermanentTracks(new Map([[req.params.libraryId, fields]])); - if (!track) { - return res.status(404).json({ error: "Fichier permanent introuvable" }); - } - - if (fields.title) { - queue.renameLibraryTrack(track.id, fields.title); - } - queue.emit("libraryUpdate"); - res.json({ track: serializeTrack(track) }); - }); - - // Remplace la pochette par l'image envoyée (champ « cover »). - router.put("/:libraryId/cover", coverUpload, (req, res) => - handleCoverUpload(req, res, (cover) => { - const track = setTrackCover(req.params.libraryId, cover); - if (!track) return null; - queue.emit("libraryUpdate"); - return { track: serializeTrack(track) }; - }) - ); - - router.delete("/:libraryId/cover", (req, res) => { - const track = setTrackCover(req.params.libraryId, null); - if (!track) { - return res.status(404).json({ error: "Fichier permanent introuvable" }); - } - queue.emit("libraryUpdate"); - res.json({ track: serializeTrack(track) }); - }); - - // Ajoute la bibliothèque à la file, mélangée si shuffle vaut true. Avec sectionId, seulement - // cette section (null : les morceaux sans section) ; avec tag, seulement cette étiquette. - router.post("/enqueue-all", (req, res) => { - let entries = getPermanentLibrary(); - if (req.body?.sectionId !== undefined) { - entries = entries.filter((entry) => (entry.sectionId ?? null) === req.body.sectionId); - } - if (typeof req.body?.tag === "string" && req.body.tag) { - entries = entries.filter((entry) => hasTag(entry, req.body.tag)); - } - if (req.body?.shuffle === true) { - shuffle(entries); - } - - 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) { @@ -139,7 +33,7 @@ function libraryRouter({ queue }) { const queueTrack = createQueueTrackFromLibrary( baseTrack, - req.user?.name ?? req.body?.requestedBy + req.body?.requestedBy ); queue.enqueue(queueTrack); res.status(201).json({ track: serializeTrack(queueTrack) }); diff --git a/src/web/routes/librarySections.js b/src/web/routes/librarySections.js deleted file mode 100644 index 708a1c5..0000000 --- a/src/web/routes/librarySections.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * @file Routes /api/library/sections : crée, renomme, déplace et supprime les sections de la - * bibliothèque, et change leur image. - */ - -import { Router } from "express"; -import { - createSection, - deleteSection, - setSectionCover, - updateSection, -} from "../storage/librarySections.js"; -import { serializeSection } from "../serializers.js"; -import { coverUpload, handleCoverUpload } from "./coverUpload.js"; - -function librarySectionsRouter({ queue }) { - const router = Router(); - - router.post("/", (req, res) => { - const section = createSection(req.body?.name); - queue.emit("libraryUpdate"); - res.status(201).json({ section: serializeSection(section) }); - }); - - // Corps : name (nouveau nom) et/ou position (nouvel emplacement, 0 en tête). - router.patch("/:sectionId", (req, res) => { - const { name, position } = req.body ?? {}; - if (name === undefined && position === undefined) { - return res.status(400).json({ error: "Rien à modifier" }); - } - const section = updateSection(req.params.sectionId, { name, position }); - if (!section) { - return res.status(404).json({ error: "Section introuvable" }); - } - queue.emit("libraryUpdate"); - res.json({ section: serializeSection(section) }); - }); - - // Remplace l'image de la section par celle envoyée (champ « cover »). - router.put("/:sectionId/cover", coverUpload, (req, res) => - handleCoverUpload(req, res, (cover) => { - const section = setSectionCover(req.params.sectionId, cover); - if (!section) return null; - queue.emit("libraryUpdate"); - return { section: serializeSection(section) }; - }) - ); - - router.delete("/:sectionId/cover", (req, res) => { - const section = setSectionCover(req.params.sectionId, null); - if (!section) { - return res.status(404).json({ error: "Section introuvable" }); - } - queue.emit("libraryUpdate"); - res.json({ section: serializeSection(section) }); - }); - - router.delete("/:sectionId", (req, res) => { - const section = deleteSection(req.params.sectionId); - if (!section) { - return res.status(404).json({ error: "Section introuvable" }); - } - queue.emit("libraryUpdate"); - res.json({ removed: serializeSection(section) }); - }); - - return router; -} - -export { librarySectionsRouter }; diff --git a/src/web/routes/notifications.js b/src/web/routes/notifications.js index 8e2c7f3..52596fe 100644 --- a/src/web/routes/notifications.js +++ b/src/web/routes/notifications.js @@ -1,11 +1,3 @@ -/** - * @file Route /api/notifications/dm : envoie un message privé Discord pour une application de - * confiance (Sokko TCG) et journalise chaque demande sans son contenu. - * - * Utilisé par : web/server.js, derrière localOnly et la clé NOTIFICATIONS_API_KEY. - * @see README.md#messages-privés-pour-les-applications - */ - import { Router } from "express"; import { DirectMessageError, sendDirectMessage } from "../../features/directMessages.js"; @@ -17,7 +9,7 @@ function logDirectMessage(userId, status) { console.log(`[${new Date().toLocaleString()}] DM ${target} → ${status}`); } -// Messages privés envoyés pour une application de confiance (clé d'API) : `{ userId, content, embed?, link? }`. +// Messages privés envoyés pour une application de confiance (clé d'API) : `{ userId, content }`. function notificationsRouter({ client }) { const router = Router(); diff --git a/src/web/routes/player.js b/src/web/routes/player.js index 1dce6fc..011d383 100644 --- a/src/web/routes/player.js +++ b/src/web/routes/player.js @@ -1,8 +1,3 @@ -/** - * @file Routes /api/player : boutons du lecteur (lecture, pause, reprise, suivant, arrêt, mélange, - * boucle) et déplacement dans le morceau en cours ; chacune renvoie le nouvel état de la file. - */ - import { Router } from "express"; function playerRouter({ queue }) { @@ -28,35 +23,11 @@ function playerRouter({ queue }) { res.json(queue.snapshot()); }); - // Corps : position, en secondes depuis le début du morceau en cours. - router.post("/seek", (req, res) => { - const position = req.body?.position; - if (typeof position !== "number" || !Number.isFinite(position) || position < 0) { - return res.status(400).json({ error: "position doit être un nombre de secondes positif" }); - } - const snapshot = queue.seek(position); - if (!snapshot) { - return res.status(409).json({ error: "Aucun morceau en cours" }); - } - res.json(snapshot); - }); - router.post("/stop", (req, res) => { queue.stop(); 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 ca439e0..ef7c7a4 100644 --- a/src/web/routes/queue.js +++ b/src/web/routes/queue.js @@ -1,8 +1,3 @@ -/** - * @file Routes /api/queue : état de la file, ajout d'un morceau de la bibliothèque, retrait et - * déplacement d'un morceau. - */ - import { Router } from "express"; import { createQueueTrackFromLibrary, findPermanentTrack } from "../storage/storageManager.js"; import { serializeTrack } from "../serializers.js"; @@ -27,13 +22,13 @@ function queueRouter({ queue }) { return res.status(404).json({ error: "Fichier permanent introuvable" }); } - const track = createQueueTrackFromLibrary(libraryTrack, req.user?.name ?? requestedBy); + const track = createQueueTrackFromLibrary(libraryTrack, requestedBy); queue.enqueue(track); res.status(201).json({ track: serializeTrack(track) }); }); - router.delete("/:trackId", (req, res) => { - const removed = queue.remove(req.params.trackId); + router.delete("/:trackId", async (req, res) => { + const removed = await queue.remove(req.params.trackId); if (!removed) { return res.status(404).json({ error: "Piste introuvable" }); } diff --git a/src/web/routes/uploads.js b/src/web/routes/uploads.js index ed08fdd..1d69ef2 100644 --- a/src/web/routes/uploads.js +++ b/src/web/routes/uploads.js @@ -1,28 +1,31 @@ -/** - * @file Routes /api/uploads : ajout d'un morceau par envoi de fichier ou par lien direct, mis en file - * et, si demandé, gardé dans la bibliothèque (dans la section choisie). - * - * Utilisé par : web/server.js ; appelé par les formulaires d'ajout de la page du jukebox. - * Attention : le type MIME annoncé par le navigateur n'est pas filtré ; ffprobe vérifie le contenu - * réel après l'envoi (music/ingest.js). - */ - import { Router } from "express"; import multer from "multer"; -import { downloadAudio } from "../../media/downloadAudio.js"; -import { ingestAudioFile } from "../../music/ingest.js"; +import { validateAudioFile } from "../../media/validateAudioFile.js"; import { serializeTrack } from "../serializers.js"; -import { findSection } from "../storage/librarySections.js"; -import { TEMP_DIR } from "../storage/storageManager.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", +]); -// 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: { fileSize: 150 * 1024 * 1024, - fields: 5, + fields: 4, fieldSize: 512, }, fileFilter: (_req, file, callback) => { @@ -32,54 +35,55 @@ const upload = multer({ callback(error); return; } - callback(null, true); + callback(null, ALLOWED_AUDIO_TYPES.has(file.mimetype)); }, }); 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, - // Section inconnue (supprimée entre-temps) : le morceau est rangé sans section. - sectionId: findSection(body?.section)?.id ?? null, - }); - router.post("/", upload.single("file"), async (req, res, next) => { if (!req.file) { return res.status(400).json({ error: "Aucun fichier reçu" }); } - try { - const track = await ingestAudioFile(req.file, options(req), { queue }); - return res.status(201).json({ - track: serializeTrack(track), - 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" }); - } + 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 { - const file = await downloadAudio(url, { destinationDir: TEMP_DIR }); - const track = await ingestAudioFile(file, options(req), { queue }); + 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); + } + return res.status(201).json({ track: serializeTrack(track), - enqueued: options(req).enqueue, + enqueued: enqueue, }); } catch (error) { + discardUploadedFile(req.file); return next(error); } }); diff --git a/src/web/serializers.js b/src/web/serializers.js index 472eded..c861b8a 100644 --- a/src/web/serializers.js +++ b/src/web/serializers.js @@ -1,36 +1,14 @@ -/** - * @file Prépare les morceaux et les sections de la bibliothèque pour l'API : retire le chemin et le - * nom du fichier sur le disque, et remplace le nom de la pochette ou de l'image par son adresse. - * - * Utilisé par : music/queue.js (snapshot) et les routes web. - * Attention : tout morceau envoyé à une page ou à un client passe par ici. - */ - -// Remplace le nom de fichier `cover` (storage/covers) par l'adresse coverUrl, servie par -// web/server.js. -function withCoverUrl({ cover, ...item }) { - return cover ? { ...item, coverUrl: `/covers/${encodeURIComponent(cover)}` } : item; -} - function serializeTrack(track) { if (!track) { return null; } const { path: _path, storedName: _storedName, ...publicTrack } = track; - return withCoverUrl(publicTrack); + return publicTrack; } function serializeTracks(tracks = []) { return tracks.map(serializeTrack); } -function serializeSection(section) { - return section ? withCoverUrl(section) : null; -} - -function serializeSections(sections = []) { - return sections.map(serializeSection); -} - -export { serializeSection, serializeSections, serializeTrack, serializeTracks }; +export { serializeTrack, serializeTracks }; diff --git a/src/web/server.js b/src/web/server.js index 662ebd5..e180f7d 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -1,23 +1,3 @@ -/** - * @file Serveur web du jukebox : API protégée, connexion avec Discord, flux en direct, pages statiques - * et messages privés pour les applications locales. - * - * Contexte : démarré par index.js dans le même processus que le bot, derrière Caddy en production. - * Points d'entrée : createApp (application Express seule, utilisée par les tests) et startWebServer - * (écoute, nettoyage horaire de storage/temp, complément des métadonnées de la bibliothèque). - * Utilisé par : index.js et les tests web. - * Dépend de : routes/, middlewares/auth.js, storage/. - * Attention : - * - Chaque groupe de routes a sa propre limite de requêtes ; seules les réponses 401 comptent dans - * la limite contre la force brute. - * - /api/notifications n'accepte que les connexions locales et sa propre clé, distincte de celle du - * jukebox. - * - Les pochettes (/covers) sont servies sans authentification : une balise n'envoie pas la - * clé. Leurs noms aléatoires ne sont donnés que par l'API, et un nom ne change jamais de - * contenu (cache d'un an). - * @see README.md#jukebox - */ - import express from "express"; import helmet from "helmet"; import { rateLimit } from "express-rate-limit"; @@ -25,21 +5,17 @@ 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, - COVERS_DIR, ensureStorageLayout, } from "./storage/storageManager.js"; @@ -65,54 +41,18 @@ 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, - oauth = { - enabled: config.discordOAuthEnabled, - clientId: config.applicationId, - clientSecret: config.discordClientSecret, - publicUrl: config.webPublicUrl, - sessionSecret: config.sessionSecret, - }, - findMember = guildMemberFinder(dependencies.client), - fetchImpl = fetch, - } = {} + { notificationsApiKey = config.notificationsApiKey } = {} ) { 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", discord: discordReady() ? "ready" : "not-ready" }); - }); - app.get("/readyz", (_req, res) => { - const ready = discordReady(); - res.status(ready ? 200 : 503).json({ status: ready ? "ready" : "not-ready" }); + res.json({ status: "ok" }); }); // Messages privés pour les applications de confiance : connexions locales uniquement, @@ -126,38 +66,23 @@ 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(createJukeboxAuth({ publicUrl: oauth.publicUrl })); + apiRouter.use(authMiddleware); apiRouter.use( "/uploads", - // Envoi de plusieurs fichiers d'un coup : une requête par fichier. - apiRateLimit({ windowMs: 15 * 60_000, limit: 40 }), + apiRateLimit({ windowMs: 15 * 60_000, limit: 10 }), 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.use( - "/covers", - express.static(COVERS_DIR, { immutable: true, maxAge: "365d", index: false, redirect: false }) + app.get(["/jukebox", "/jukebox/"], (_req, res) => + res.sendFile(path.join(PUBLIC_DIR, "jukebox.html")) ); - // Ancienne adresse du jukebox, devenu la page d'accueil : les favoris continuent de marcher. - app.get(["/jukebox", "/jukebox/"], (req, res) => { - const query = req.originalUrl.indexOf("?"); - res.redirect(301, query === -1 ? "/" : `/${req.originalUrl.slice(query)}`); - }); app.use(express.static(PUBLIC_DIR)); app.use((error, _req, res, _next) => { @@ -176,38 +101,18 @@ function createApp( return app; } -const TEMP_CLEANUP_INTERVAL = 60 * 60_000; - function startWebServer(dependencies) { ensureStorageLayout(); - 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)); + cleanupTemporaryFiles(); const app = createApp(dependencies); - const port = config.webServerPort; + const port = Number(process.env.PORT || config.webServerPort || 3000); const server = app.listen(port, () => { console.log( `[${new Date().toLocaleString()}] Web control server listening on port ${port}` ); }); - server.on("close", () => clearInterval(cleanupInterval)); return { app, server }; } diff --git a/src/web/storage/libraryCovers.js b/src/web/storage/libraryCovers.js deleted file mode 100644 index 202a501..0000000 --- a/src/web/storage/libraryCovers.js +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @file Pochettes des morceaux de la bibliothèque : reprise de la pochette intégrée au fichier audio, - * remplacement par une image envoyée depuis la page, retrait. Convertit aussi les images des - * sections (saveCoverFromImage). - * - * Utilisé par : music/ingest.js (nouveau morceau), storage/libraryMetadata.js (morceaux plus - * anciens), web/routes/library.js (retrait depuis la page), web/routes/coverUpload.js (envoi). - * Attention : - * - Le champ `cover` d'une entrée vaut le nom du fichier dans storage/covers, null si le morceau - * n'a pas de pochette, et il est absent tant que la pochette intégrée n'a pas été cherchée. - * - Chaque pochette reçoit un nouveau nom aléatoire et l'ancienne est supprimée : le navigateur - * peut garder une pochette en cache indéfiniment (servie sous /covers par web/server.js). - */ - -import fs from "node:fs"; -import path from "node:path"; -import { randomUUID } from "node:crypto"; -import { createCoverImage, detectImageFormat } from "../../media/coverArt.js"; -import { - COVERS_DIR, - deleteCoverFile, - findPermanentTrack, - updatePermanentTracks, -} from "./storageManager.js"; - -function httpError(status, message, cause) { - return Object.assign(new Error(message, { cause }), { status }); -} - -// create : remplace createCoverImage (tests). -async function writeCover(inputPath, { create = createCoverImage, inputFormat } = {}) { - const name = `${randomUUID()}.jpg`; - try { - // Le dossier est créé au démarrage du serveur, mais peut avoir été supprimé depuis. - fs.mkdirSync(COVERS_DIR, { recursive: true }); - await create(inputPath, path.join(COVERS_DIR, name), { inputFormat }); - return name; - } catch (error) { - deleteCoverFile(name); - throw error; - } -} - -// Pochette intégrée au fichier audio, ou null s'il n'en a pas (ou si ffmpeg ne la lit pas). -async function saveCoverFromAudio(audioPath, options) { - try { - return await writeCover(audioPath, options); - } catch { - return null; - } -} - -// Pochette tirée d'une image envoyée. Erreur 400 si ce n'est pas une image PNG, JPEG, WebP ou GIF. -async function saveCoverFromImage(imagePath, options) { - const inputFormat = await detectImageFormat(imagePath); - if (!inputFormat) { - throw httpError(400, "Image non reconnue : PNG, JPEG, WebP ou GIF attendu"); - } - try { - return await writeCover(imagePath, { ...options, inputFormat }); - } catch (error) { - throw httpError(400, "Impossible de lire cette image", error); - } -} - -// Donne la pochette `name` (null : aucune) au morceau et supprime l'ancienne. Renvoie l'entrée, -// ou null si le morceau n'existe plus : la nouvelle pochette est alors supprimée. -function setTrackCover(trackId, name) { - const previous = findPermanentTrack(trackId); - if (!previous) { - deleteCoverFile(name); - return null; - } - const [track] = updatePermanentTracks(new Map([[trackId, { cover: name }]])); - if (previous.cover && previous.cover !== name) { - deleteCoverFile(previous.cover); - } - return track; -} - -// Cherche la pochette intégrée d'un morceau jamais examiné. Si une pochette lui a été donnée -// pendant la recherche, elle est gardée. Renvoie l'entrée mise à jour, ou null. -async function fillEmbeddedCover(trackId, audioPath, options) { - const name = await saveCoverFromAudio(audioPath, options); - const current = findPermanentTrack(trackId); - if (!current || current.cover !== undefined) { - deleteCoverFile(name); - return null; - } - return updatePermanentTracks(new Map([[trackId, { cover: name }]]))[0]; -} - -export { fillEmbeddedCover, saveCoverFromImage, setTrackCover }; diff --git a/src/web/storage/libraryMetadata.js b/src/web/storage/libraryMetadata.js deleted file mode 100644 index 707bcf2..0000000 --- a/src/web/storage/libraryMetadata.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @file Complète au démarrage la durée, l'artiste et la pochette intégrée des morceaux de la - * bibliothèque ajoutés avant que l'envoi ne les relève. - * - * Utilisé par : web/server.js (startWebServer). - * Attention : un fichier illisible est ignoré et retenté au démarrage suivant, sauf pour la - * pochette : un morceau examiné une fois sans pochette garde `cover: null`. - */ - -import { probeAudioFile } from "../../media/validateAudioFile.js"; -import { fillEmbeddedCover } from "./libraryCovers.js"; -import { getPermanentLibrary, updatePermanentTracks } from "./storageManager.js"; - -// Renvoie les entrées modifiées. probe et createCover remplacent ffprobe et ffmpeg (tests). -async function backfillLibraryMetadata({ probe = probeAudioFile, createCover } = {}) { - const library = getPermanentLibrary(); - const updates = new Map(); - - for (const entry of library.filter((item) => item.duration == null)) { - 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); - } - } - const updated = new Map(updatePermanentTracks(updates).map((entry) => [entry.id, entry])); - - for (const entry of library.filter((item) => item.cover === undefined)) { - const withCover = await fillEmbeddedCover(entry.id, entry.path, { create: createCover }); - if (withCover?.cover) { - updated.set(withCover.id, withCover); - } - } - - return [...updated.values()]; -} - -export { backfillLibraryMetadata }; diff --git a/src/web/storage/librarySections.js b/src/web/storage/librarySections.js deleted file mode 100644 index 4b06605..0000000 --- a/src/web/storage/librarySections.js +++ /dev/null @@ -1,140 +0,0 @@ -/** - * @file Sections de la bibliothèque : liste ordonnée de groupes nommés, avec une image facultative, - * enregistrée dans storage/runtime/sections.json. Chaque morceau désigne la sienne par son - * champ `sectionId`. - * - * Utilisé par : web/routes/librarySections.js, web/routes/library.js et uploads.js (section - * choisie pour un morceau). - * Attention : supprimer une section remet ses morceaux « sans section », sans les supprimer, et - * supprime son image. Un fichier absent vaut une liste vide. L'image (`cover`) est un nom de - * fichier de storage/covers, créé comme les pochettes des morceaux (libraryCovers.js). - */ - -import fs from "node:fs"; -import path from "node:path"; -import { randomUUID } from "node:crypto"; -import { - deleteCoverFile, - getPermanentLibrary, - RUNTIME_DIR, - updatePermanentTracks, -} from "./storageManager.js"; - -const SECTIONS_FILE = path.join(RUNTIME_DIR, "sections.json"); -const MAX_SECTIONS = 100; -const MAX_NAME_LENGTH = 80; - -function httpError(status, message) { - return Object.assign(new Error(message), { status }); -} - -function cleanName(value) { - const name = String(value ?? "") - .replace(/[\u0000-\u001f]/g, "") - .trim() - .slice(0, MAX_NAME_LENGTH); - if (!name) { - throw httpError(400, "Nom de section manquant"); - } - return name; -} - -function getSections() { - try { - const sections = JSON.parse(fs.readFileSync(SECTIONS_FILE, "utf8")); - if (!Array.isArray(sections)) { - throw new TypeError("sections.json doit contenir un tableau"); - } - return sections.filter( - (section) => typeof section?.id === "string" && typeof section.name === "string" - ); - } catch (error) { - if (error.code === "ENOENT") return []; - console.error("Failed to read sections file", error); - throw new Error("Impossible de lire les sections", { cause: error }); - } -} - -function writeSections(sections) { - fs.mkdirSync(RUNTIME_DIR, { recursive: true }); - const temporaryFile = `${SECTIONS_FILE}.${process.pid}.tmp`; - fs.writeFileSync(temporaryFile, JSON.stringify(sections, null, 2)); - fs.renameSync(temporaryFile, SECTIONS_FILE); -} - -function findSection(id) { - return typeof id === "string" ? getSections().find((section) => section.id === id) : undefined; -} - -function createSection(name) { - const sections = getSections(); - if (sections.length >= MAX_SECTIONS) { - throw httpError(409, `Pas plus de ${MAX_SECTIONS} sections`); - } - const section = { id: randomUUID(), name: cleanName(name) }; - sections.push(section); - writeSections(sections); - return section; -} - -// Renomme la section et/ou la déplace à `position` (0 : en tête). null si elle n'existe pas. -function updateSection(id, { name, position } = {}) { - const sections = getSections(); - const index = sections.findIndex((section) => section.id === id); - if (index === -1) return null; - - const section = sections[index]; - if (name !== undefined) { - section.name = cleanName(name); - } - if (position !== undefined) { - if (!Number.isInteger(position) || position < 0 || position >= sections.length) { - throw httpError(400, "Position invalide"); - } - sections.splice(index, 1); - sections.splice(position, 0, section); - } - writeSections(sections); - return section; -} - -// Supprime la section ; ses morceaux restent dans la bibliothèque, sans section. -function deleteSection(id) { - const sections = getSections(); - const index = sections.findIndex((section) => section.id === id); - if (index === -1) return null; - - const [removed] = sections.splice(index, 1); - writeSections(sections); - deleteCoverFile(removed.cover); - const orphans = getPermanentLibrary().filter((entry) => entry.sectionId === id); - updatePermanentTracks(new Map(orphans.map((entry) => [entry.id, { sectionId: null }]))); - return removed; -} - -// Donne l'image `name` (null : aucune) à la section et supprime l'ancienne. Renvoie la section, -// ou null si elle n'existe plus : la nouvelle image est alors supprimée. -function setSectionCover(id, name) { - const sections = getSections(); - const section = sections.find((item) => item.id === id); - if (!section) { - deleteCoverFile(name); - return null; - } - const previous = section.cover; - section.cover = name; - writeSections(sections); - if (previous && previous !== name) { - deleteCoverFile(previous); - } - return section; -} - -export { - createSection, - deleteSection, - findSection, - getSections, - setSectionCover, - updateSection, -}; diff --git a/src/web/storage/storageManager.js b/src/web/storage/storageManager.js index d82cc42..a6c7b18 100644 --- a/src/web/storage/storageManager.js +++ b/src/web/storage/storageManager.js @@ -1,25 +1,3 @@ -/** - * @file Stockage des fichiers audio : storage/temp pour les morceaux joués une seule fois, - * storage/permanent et sa liste storage/runtime/library.json pour la bibliothèque, et - * storage/covers pour les pochettes. - * - * Contexte : seul module qui crée, déplace ou supprime les fichiers audio et la liste de la - * bibliothèque. Les pochettes sont créées par libraryCovers.js et les sections rangées par - * librarySections.js ; une entrée n'en garde que le nom de fichier (`cover`) et l'identifiant - * (`sectionId`). - * Points d'entrée : registerUploadedFile (nouveau fichier), getPermanentLibrary, - * createQueueTrackFromLibrary, cleanupTemporaryFiles, deleteTrackFile. - * Utilisé par : music/ (ajout, file), web/routes/library.js et queue.js, /play, web/server.js. - * Attention : - * - Les dossiers sont fixés au chargement d'après le répertoire de travail : le bot se lance depuis - * la racine du projet, et les tests changent de répertoire avant d'importer ce module. - * - library.json ne garde que les noms de fichiers ; le chemin complet est recalculé à la lecture, - * pour que le dossier puisse être déplacé. - * - La bibliothèque est limitée à 2 Go. Les fichiers temporaires de plus de 24 h sont supprimés, - * sauf ceux encore dans la file. - * @see README.md#données-persistantes - */ - import fs from "fs"; import path from "path"; import { randomUUID } from "node:crypto"; @@ -28,15 +6,26 @@ const STORAGE_ROOT = path.join(process.cwd(), "storage"); const PERMANENT_DIR = path.join(STORAGE_ROOT, "permanent"); const TEMP_DIR = path.join(STORAGE_ROOT, "temp"); const RUNTIME_DIR = path.join(STORAGE_ROOT, "runtime"); -const COVERS_DIR = path.join(STORAGE_ROOT, "covers"); const LIBRARY_FILE = path.join(RUNTIME_DIR, "library.json"); const LEGACY_LIBRARY_FILE = path.join(STORAGE_ROOT, "library.json"); const TEMP_FILE_MAX_AGE = 24 * 60 * 60 * 1000; const MAX_LIBRARY_SIZE = 2 * 1024 * 1024 * 1024; function ensureStorageLayout() { - for (const directory of [PERMANENT_DIR, TEMP_DIR, RUNTIME_DIR, COVERS_DIR]) { - fs.mkdirSync(directory, { recursive: true }); + if (!fs.existsSync(STORAGE_ROOT)) { + fs.mkdirSync(STORAGE_ROOT, { recursive: true }); + } + + if (!fs.existsSync(PERMANENT_DIR)) { + fs.mkdirSync(PERMANENT_DIR, { recursive: true }); + } + + if (!fs.existsSync(TEMP_DIR)) { + fs.mkdirSync(TEMP_DIR, { recursive: true }); + } + + if (!fs.existsSync(RUNTIME_DIR)) { + fs.mkdirSync(RUNTIME_DIR, { recursive: true }); } if (!fs.existsSync(LIBRARY_FILE)) { @@ -98,14 +87,7 @@ function writeLibrary(entries) { function registerUploadedFile( file, - { - permanent, - uploader = "unknown", - title = file.originalname, - duration = null, - artist = null, - sectionId = null, - } + { permanent, uploader = "unknown", title = file.originalname } ) { ensureStorageLayout(); const createdAt = new Date().toISOString(); @@ -120,16 +102,14 @@ function registerUploadedFile( 0 ); if (librarySize + file.size > MAX_LIBRARY_SIZE) { - const error = new Error("La bibliothèque permanente a atteint sa limite de 2 Go"); - error.status = 413; - throw error; + throw new Error("La bibliothèque permanente a atteint sa limite de 2 Go"); } const rawExtension = path.extname(file.originalname).toLowerCase(); const extension = /^\.[a-z0-9]{1,10}$/.test(rawExtension) ? rawExtension : ""; - storedName = `${randomUUID()}${extension}`; + storedName = `${randomUUID()}${extension.toLowerCase()}`; finalPath = path.join(PERMANENT_DIR, storedName); fs.renameSync(file.path, finalPath); permanentEntry = { @@ -140,9 +120,6 @@ function registerUploadedFile( path: finalPath, size: file.size, mimetype: file.mimetype, - duration, - artist, - sectionId, uploader, createdAt, }; @@ -158,8 +135,6 @@ function registerUploadedFile( storedName, size: file.size, mimetype: file.mimetype, - duration, - artist, permanent, uploader, libraryTrackId: permanentEntry ? permanentEntry.id : null, @@ -189,21 +164,14 @@ 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: - String(requestedBy ?? "") - .replace(/[\u0000-\u001f]/g, "") - .trim() - .slice(0, 80) || "library", + uploader: requestedBy, libraryTrackId: libraryTrack.id, createdAt: new Date().toISOString(), }; } -// keep : chemins encore utilisés (file d'attente, morceau en cours), jamais supprimés. -function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE, { keep = new Set() } = {}) { +function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE) { ensureStorageLayout(); const cutoff = Date.now() - maxAge; @@ -213,9 +181,6 @@ function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE, { keep = new Set() } } const filePath = path.join(TEMP_DIR, entry.name); - if (keep.has(filePath)) { - continue; - } try { if (fs.statSync(filePath).mtimeMs < cutoff) { fs.unlinkSync(filePath); @@ -232,7 +197,7 @@ function deleteFileSafe(filePath) { } try { - fs.rmSync(filePath, { force: true }); + fs.existsSync(filePath) && fs.unlinkSync(filePath); } catch (error) { console.error(`Failed to delete file ${filePath}`, error); } @@ -242,31 +207,6 @@ function discardUploadedFile(file) { deleteFileSafe(file?.path); } -// Supprime une pochette d'après son nom de fichier (champ `cover` d'une entrée). -function deleteCoverFile(name) { - if (typeof name === "string" && name && path.basename(name) === name) { - deleteFileSafe(path.join(COVERS_DIR, name)); - } -} - -// 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); @@ -277,7 +217,6 @@ function deletePermanentTrack(id) { const [removed] = library.splice(index, 1); writeLibrary(library); deleteFileSafe(removed.path); - deleteCoverFile(removed.cover); return removed; } @@ -299,9 +238,7 @@ function deleteTrackFile(track) { } export { - COVERS_DIR, PERMANENT_DIR, - RUNTIME_DIR, TEMP_DIR, ensureStorageLayout, registerUploadedFile, @@ -310,9 +247,7 @@ export { createQueueTrackFromLibrary, cleanupTemporaryFiles, discardUploadedFile, - deleteCoverFile, deletePermanentTrack, - updatePermanentTracks, handleTrackCompletion, deleteTrackFile, }; diff --git a/test/audio.test.js b/test/audio.test.js deleted file mode 100644 index afed06e..0000000 --- a/test/audio.test.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @file Vérifie la lecture des tags et la conversion en Opus avec les vrais ffprobe et ffmpeg ; - * ignoré s'ils ne sont pas installés. - */ - -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("createOpusStream can start in the middle of a track", { skip }, async () => { - const resource = createAudioResource(createOpusStream(makeTone("three.mp3", 3), { startAt: 2 }), { - inputType: StreamType.OggOpus, - }); - - let packets = 0; - for await (const _packet of resource.playStream) { - packets += 1; - } - // Seule la dernière seconde est jouée : une cinquantaine de paquets de 20 ms, pas 150. - assert.ok(packets >= 40 && packets <= 70, `${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/auth.test.js b/test/auth.test.js index 00e9b42..c9b6722 100644 --- a/test/auth.test.js +++ b/test/auth.test.js @@ -1,7 +1,3 @@ -/** - * @file Vérifie que l'API du jukebox n'accepte que la clé exacte dans l'en-tête Authorization. - */ - import test from "node:test"; import assert from "node:assert/strict"; diff --git a/test/commands.test.js b/test/commands.test.js index d0ff2a0..e19f76f 100644 --- a/test/commands.test.js +++ b/test/commands.test.js @@ -1,10 +1,6 @@ -/** - * @file Vérifie que toutes les commandes se chargent, puis /listcommand, /maketeam, /queue, les - * commandes vocales et les permissions des commandes d'administration. - */ - import test from "node:test"; import assert from "node:assert/strict"; +import fs from "node:fs"; const ENVIRONMENT = { NODE_ENV: "test", @@ -20,37 +16,30 @@ const ENVIRONMENT = { }; Object.assign(process.env, ENVIRONMENT); -const { loadCommands } = await import("../src/loadCommands.js"); +async function loadCommands() { + const files = fs + .readdirSync("src/commands", { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .flatMap((directory) => + fs + .readdirSync(`src/commands/${directory.name}`) + .filter((file) => file.endsWith(".js")) + .map((file) => `../src/commands/${directory.name}/${file}`) + ); + return Promise.all(files.map((file) => import(file))); +} test("all Discord commands expose valid command data", async () => { - const commands = await loadCommands(); - assert.equal(commands.length, 13); - for (const command of commands) { - assert.doesNotThrow(() => command.data.toJSON()); - assert.equal(typeof command.execute, "function"); - assert.ok(command.category, command.data.name); + const modules = await loadCommands(); + assert.equal(modules.length, 10); + for (const module of modules) { + assert.doesNotThrow(() => module.command.data.toJSON()); + assert.equal(typeof module.command.execute, "function"); } }); -test("/listcommand lists every loaded command under its category", async () => { - const commands = await loadCommands(); - const { buildCommandList } = await import("../src/commands/utility/listcommand.js"); - const message = buildCommandList(commands); - for (const command of commands) { - assert.ok(message.includes(`\`/${command.data.name}\` : ${command.data.description}`)); - } - assert.match(message, /__Jukebox__\n`\/play`/); - assert.ok(message.length <= 2000); -}); - -test("/maketeam splits players on commas when there are any", async () => { - const { parsePlayers } = await import("../src/commands/game/maketeam.js"); - assert.deepEqual(parsePlayers(" Alice Bob\tChloé "), ["Alice", "Bob", "Chloé"]); - assert.deepEqual(parsePlayers("Jean Pierre, Marie,, Léo "), ["Jean Pierre", "Marie", "Léo"]); -}); - test("administrative commands require Discord permissions", async () => { - const commands = await loadCommands(); + const modules = await loadCommands(); const protectedCommands = new Set([ "deletemsgs", "invitation", @@ -60,61 +49,11 @@ test("administrative commands require Discord permissions", async () => { "undeafall", ]); - for (const command of commands) { - const data = command.data.toJSON(); + for (const module of modules) { + const data = module.command.data.toJSON(); if (protectedCommands.has(data.name)) { assert.notEqual(data.default_member_permissions, undefined, data.name); assert.notEqual(data.default_member_permissions, null, data.name); } } }); - -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 }, { title: "Mix", duration: 3600, resumeAt: 2955 }], - }); - assert.match(message, /En cours : \*\*Thème \\\*principal\\\* \(3:07\)\*\*/); - assert.match(message, /1\. Suite \(1:05:09\)/); - assert.match(message, /2\. Mix \(1:00:00, reprise à 49:15\)/); -}); - -test("vocal commands act on the caller's voice channel, skipping bots", async () => { - const { changeVoiceStatus, commandVoiceChannel } = await import("../src/features/utilities.js"); - const { Collection } = await import("discord.js"); - const muted = []; - const member = (id, { bot = false, fail = false } = {}) => ({ - id, - user: { bot }, - voice: { - setMute: async (value) => { - if (fail) throw new Error("left the channel"); - muted.push([id, value]); - }, - }, - }); - const callerChannel = { - isVoiceBased: () => true, - members: new Collection([ - ["a", member("a")], - ["bot", member("bot", { bot: true })], - ["gone", member("gone", { fail: true })], - ["b", member("b")], - ]), - }; - const configuredChannel = { isVoiceBased: () => true, members: new Collection() }; - const client = { channels: { cache: new Map([["1", configuredChannel]]) } }; - - assert.equal(commandVoiceChannel({ client, member: { voice: { channel: callerChannel } } }), callerChannel); - assert.equal(commandVoiceChannel({ client, member: { voice: { channel: null } } }), configuredChannel); - - const originalError = console.error; - console.error = () => {}; - try { - await changeVoiceStatus(callerChannel, "mute"); - } finally { - console.error = originalError; - } - assert.deepEqual(muted, [["a", true], ["b", true]]); -}); diff --git a/test/coverArt.test.js b/test/coverArt.test.js deleted file mode 100644 index 5b23291..0000000 --- a/test/coverArt.test.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @file Vérifie la fabrication des pochettes avec le vrai ffmpeg (image envoyée, pochette intégrée à - * un MP3) et le refus des fichiers qui ne sont pas des images ; ignoré sans ffmpeg. - */ - -import test from "node:test"; -import assert from "node:assert/strict"; -import { spawnSync } from "node:child_process"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { createCoverImage, detectImageFormat } from "../src/media/coverArt.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-cover-")); -test.after(() => fs.rmSync(directory, { recursive: true, force: true })); - -function ffmpeg(...args) { - const result = spawnSync("ffmpeg", ["-v", "error", "-y", ...args]); - assert.equal(result.status, 0, result.stderr?.toString()); -} - -function imageSize(file) { - const result = spawnSync("ffprobe", [ - "-v", "error", "-select_streams", "v:0", - "-show_entries", "stream=width,height,codec_name", "-of", "json", file, - ]); - return JSON.parse(result.stdout.toString()).streams[0]; -} - -test("image signatures are recognised, other files are not", async () => { - const samples = { - "a.png": Buffer.from("89504e470d0a1a0a0000000d", "hex"), - "a.jpg": Buffer.from("ffd8ffe000104a4649460001", "hex"), - "a.gif": Buffer.from("GIF89a\x01\x00\x01\x00\x00\x00", "latin1"), - "a.webp": Buffer.from("RIFF\x24\x00\x00\x00WEBPVP8 ", "latin1"), - "playlist.png": Buffer.from("#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:0\n"), - "short.png": Buffer.from("89504e47", "hex"), - }; - const formats = {}; - for (const [name, bytes] of Object.entries(samples)) { - const file = path.join(directory, name); - fs.writeFileSync(file, bytes); - formats[name] = await detectImageFormat(file); - } - assert.deepEqual(formats, { - "a.png": "png_pipe", - "a.jpg": "jpeg_pipe", - "a.gif": "gif", - "a.webp": "webp_pipe", - "playlist.png": null, - "short.png": null, - }); -}); - -test("an uploaded image becomes a JPEG of at most 512 px", { skip }, async () => { - const input = path.join(directory, "wide.png"); - ffmpeg("-f", "lavfi", "-i", "color=c=purple:s=1024x256", "-frames:v", "1", input); - const output = path.join(directory, "wide.jpg"); - - await createCoverImage(input, output, { inputFormat: await detectImageFormat(input) }); - - assert.deepEqual(imageSize(output), { codec_name: "mjpeg", width: 512, height: 128 }); -}); - -test("the cover embedded in an MP3 is extracted, and its absence is an error", { skip }, async () => { - const picture = path.join(directory, "picture.jpg"); - ffmpeg("-f", "lavfi", "-i", "color=c=orange:s=300x300", "-frames:v", "1", picture); - const withCover = path.join(directory, "with-cover.mp3"); - ffmpeg( - "-f", "lavfi", "-i", "sine=frequency=440:duration=1", "-i", picture, - "-map", "0:a", "-map", "1:v", "-c:a", "libmp3lame", "-c:v", "copy", - "-disposition:v", "attached_pic", withCover - ); - const withoutCover = path.join(directory, "without-cover.mp3"); - ffmpeg("-f", "lavfi", "-i", "sine=frequency=440:duration=1", "-c:a", "libmp3lame", withoutCover); - - const output = path.join(directory, "extracted.jpg"); - await createCoverImage(withCover, output); - assert.deepEqual(imageSize(output), { codec_name: "mjpeg", width: 300, height: 300 }); - - await assert.rejects(createCoverImage(withoutCover, path.join(directory, "none.jpg"))); -}); diff --git a/test/directMessages.test.js b/test/directMessages.test.js index f2c1b1c..77a6e27 100644 --- a/test/directMessages.test.js +++ b/test/directMessages.test.js @@ -1,8 +1,3 @@ -/** - * @file Vérifie l'envoi des messages privés : mentions désactivées, contrôle du texte, des embeds et - * des liens, erreurs Discord traduites en erreurs pour l'application. - */ - import test from "node:test"; import assert from "node:assert/strict"; import { DirectMessageError, sendDirectMessage } from "../src/features/directMessages.js"; @@ -49,50 +44,3 @@ test("sendDirectMessage maps unknown users and closed messages to client errors" await assert.rejects(sendDirectMessage(fakeClient({ sendError: { code: 50007 } }), { userId: USER_ID, content: "x" }), (error) => error.status === 422 && error.code === "DM_CLOSED"); await assert.rejects(sendDirectMessage(fakeClient({ sendError: new Error("network") }), { userId: USER_ID, content: "x" }), /network/); }); - -test("sendDirectMessage adds an embed and a link button when given", async () => { - const client = fakeClient(); - await sendDirectMessage(client, { - userId: USER_ID, - content: "Votre expédition est de retour !", - embed: { - title: "Votre expédition est de retour !", - description: "Les Glaces de la Longue Nuit · ★★★ · 6 h", - url: "https://sokko.example/#/cards/expeditions/abc", - color: 0xf6c453, - thumbnail: "https://sokko.example/static/img/cards/x.webp", - fields: [{ name: "Butin", value: "+16 Éclats" }], - footer: "Sokko TCG", - timestamp: 1_800_000_000_000, - }, - link: { label: "Voir l'expédition", url: "https://sokko.example/#/cards/expeditions/abc" }, - }); - const [message] = client.sent; - assert.equal(message.embeds[0].title, "Votre expédition est de retour !"); - assert.deepEqual(message.embeds[0].thumbnail, { url: "https://sokko.example/static/img/cards/x.webp" }); - assert.deepEqual(message.embeds[0].fields, [{ name: "Butin", value: "+16 Éclats", inline: false }]); - assert.deepEqual(message.embeds[0].footer, { text: "Sokko TCG" }); - assert.equal(message.embeds[0].timestamp, new Date(1_800_000_000_000).toISOString()); - assert.deepEqual(message.components, [{ type: 1, components: [{ type: 2, style: 5, label: "Voir l'expédition", url: "https://sokko.example/#/cards/expeditions/abc" }] }]); - assert.deepEqual(message.allowedMentions, { parse: [] }); -}); - -test("sendDirectMessage refuses embeds and links that Discord would reject", async () => { - const client = fakeClient(); - const send = (extra) => sendDirectMessage(client, { userId: USER_ID, content: "x", ...extra }); - for (const extra of [ - { embed: { description: "sans titre" } }, - { embed: { title: "x".repeat(257) } }, - { embed: { title: "t", url: "http://sokko.example" } }, - { embed: { title: "t", thumbnail: "javascript:alert(1)" } }, - { embed: { title: "t", color: 0x1000000 } }, - { embed: { title: "t", fields: Array.from({ length: 26 }, () => ({ name: "n", value: "v" })) } }, - { embed: { title: "t", fields: [{ name: "n", value: "" }] } }, - { embed: { title: "t", description: "x".repeat(4096), fields: Array.from({ length: 2 }, () => ({ name: "n", value: "x".repeat(1024) })) } }, - { link: { label: "Voir", url: "ftp://sokko.example" } }, - { link: { url: "https://sokko.example" } }, - ]) { - await assert.rejects(send(extra), (error) => error instanceof DirectMessageError && error.status === 400 && error.code === "INVALID_EMBED"); - } - assert.equal(client.sent.length, 0); -}); diff --git a/test/discordAuth.test.js b/test/discordAuth.test.js deleted file mode 100644 index 4924b81..0000000 --- a/test/discordAuth.test.js +++ /dev/null @@ -1,170 +0,0 @@ -/** - * @file Couvre la connexion avec Discord : membres et non-membres, état OAuth, origine des requêtes, - * jetons falsifiés ou expirés, et le mot de passe quand OAuth est désactivé. - */ - -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"), "/"); - 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"), "/?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"), "/?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 deleted file mode 100644 index 754d453..0000000 --- a/test/downloadAudio.test.js +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @file Vérifie le téléchargement par lien avec un serveur local : nom du fichier, adresses internes - * refusées (même après une redirection), taille maximale et protocoles acceptés. - */ - -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/fileHeaders.test.js b/test/fileHeaders.test.js deleted file mode 100644 index 28ad36b..0000000 --- a/test/fileHeaders.test.js +++ /dev/null @@ -1,68 +0,0 @@ -/** - * @file Vérifie que chaque fichier JavaScript et la feuille de style commencent par leur en-tête, et que - * les fichiers centraux ont un en-tête complet. - * - * Attention : le test ne lit que la présence des rubriques ; leur contenu reste à écrire avec soin. - * @see CONTRIBUTING.md#en-têtes-de-fichiers - */ - -import test from "node:test"; -import assert from "node:assert/strict"; -import fs from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); -const JS_ROOTS = ["index.js", "deployCommands.js", "src", "public/scripts", "scripts", "test"]; -// Fichiers centraux : en-tête complet exigé. Un fichier qui le devient s'ajoute ici. -const CENTRAL_FILES = [ - "index.js", - "public/scripts/jukebox.js", - "src/music/queue.js", - "src/web/server.js", - "src/web/storage/storageManager.js", -]; -const LONG_FILE_LINES = 300; - -function collectJavaScriptFiles(entry) { - const absolutePath = path.join(ROOT, entry); - if (fs.statSync(absolutePath).isFile()) { - return entry.endsWith(".js") ? [entry] : []; - } - return fs - .readdirSync(absolutePath) - .flatMap((child) => collectJavaScriptFiles(path.posix.join(entry, child))); -} - -function header(content) { - const end = content.indexOf("*/"); - return end === -1 ? "" : content.slice(0, end); -} - -const jsFiles = JS_ROOTS.flatMap(collectJavaScriptFiles); - -test("every JavaScript file starts with a @file header", () => { - const missing = jsFiles.filter((file) => { - const content = fs.readFileSync(path.join(ROOT, file), "utf8"); - return !content.startsWith("/**\n * @file "); - }); - assert.deepEqual(missing, []); -}); - -test("central and long files have a complete header", () => { - const long = jsFiles.filter( - (file) => - !file.startsWith("test/") && - fs.readFileSync(path.join(ROOT, file), "utf8").split("\n").length > LONG_FILE_LINES - ); - const incomplete = [...new Set([...CENTRAL_FILES, ...long])].filter((file) => { - const text = header(fs.readFileSync(path.join(ROOT, file), "utf8")); - return !["Contexte :", "Utilisé par :", "@see "].every((rubric) => text.includes(rubric)); - }); - assert.deepEqual(incomplete, []); -}); - -test("the stylesheet starts with its role", () => { - const content = fs.readFileSync(path.join(ROOT, "public/style/styles.css"), "utf8"); - assert.ok(content.startsWith("/*\n * Rôle : ")); -}); diff --git a/test/gameServers.test.js b/test/gameServers.test.js deleted file mode 100644 index f09b82c..0000000 --- a/test/gameServers.test.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @file Vérifie le sondage TCP des serveurs de jeux, l'état saisi à la main et le message publié. - */ - -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 { buildMessage, 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); -}); - -test("the status message is coloured and mentions the owner", () => { - const message = buildMessage({ - servers: [ - { game: "Minecraft", address: "games.example.com:25565", active: true }, - { game: "Palworld", address: "games.example.com:8211", active: false }, - ], - }); - // Les couleurs des blocs ansi de Discord demandent le caractère ESC lui-même. - assert.ok(message.includes("Minecraft : \u001b[2;32mOnline\u001b[0m")); - assert.ok(message.includes("Palworld : \u001b[2;31mOffline\u001b[0m")); - // OWNER_USER_ID absent : l'ancien nom SHINUWA_USER_ID est encore accepté. - assert.match(message, /<@1>/); -}); diff --git a/test/ingest.test.js b/test/ingest.test.js deleted file mode 100644 index 878d98c..0000000 --- a/test/ingest.test.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @file Vérifie l'ajout d'un fichier : titre par défaut, mise en file avec ses métadonnées et - * suppression d'un fichier qui n'est pas de l'audio. - */ - -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/invitation.test.js b/test/invitation.test.js index acf5244..a7aed2d 100644 --- a/test/invitation.test.js +++ b/test/invitation.test.js @@ -1,8 +1,3 @@ -/** - * @file Vérifie la lecture des liens d'invitation, le refus des invitations permanentes ou inconnues - * et les avertissements joints au message. - */ - import test from "node:test"; import assert from "node:assert/strict"; import { DiscordjsErrorCodes } from "discord.js"; diff --git a/test/invitationCommand.test.js b/test/invitationCommand.test.js index 3971c62..7eae0c9 100644 --- a/test/invitationCommand.test.js +++ b/test/invitationCommand.test.js @@ -1,8 +1,3 @@ -/** - * @file Vérifie que /invitation publie le lien vérifié, ou explique pourquoi le bot ne peut pas écrire - * dans le salon. - */ - import test from "node:test"; import assert from "node:assert/strict"; diff --git a/test/libraryCovers.test.js b/test/libraryCovers.test.js deleted file mode 100644 index 57c392a..0000000 --- a/test/libraryCovers.test.js +++ /dev/null @@ -1,118 +0,0 @@ -/** - * @file Vérifie le stockage des pochettes sans ffmpeg : pochette intégrée reprise à l'ajout, - * remplacement, refus d'un fichier qui n'est pas une image, suppression avec le morceau, et - * adresse donnée par l'API. - */ - -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-covers-")); -process.chdir(temporaryDirectory); -const storage = await import("../src/web/storage/storageManager.js"); -const covers = await import("../src/web/storage/libraryCovers.js"); -const { ingestAudioFile } = await import("../src/music/ingest.js"); -const { backfillLibraryMetadata } = await import("../src/web/storage/libraryMetadata.js"); -const { serializeTrack } = await import("../src/web/serializers.js"); -storage.ensureStorageLayout(); -test.after(() => { - process.chdir(originalDirectory); - fs.rmSync(temporaryDirectory, { recursive: true, force: true }); -}); - -// Remplace ffmpeg : écrit un faux JPEG, ou échoue comme pour un fichier sans pochette. -const fakeCreate = async (_input, output) => fs.writeFileSync(output, "jpeg"); -const noCover = async () => { - throw new Error("Output file does not contain any stream"); -}; -const probe = async () => ({ duration: 10, title: null, artist: null }); - -function tempFile(name, content = "audio") { - const filePath = path.join(storage.TEMP_DIR, `upload-${name}`); - fs.writeFileSync(filePath, Buffer.from(content, "latin1")); - return { path: filePath, originalname: name, size: content.length, mimetype: "audio/mpeg" }; -} - -function fakeQueue() { - const queue = new EventEmitter(); - queue.enqueue = () => {}; - return queue; -} - -const coverPath = (name) => path.join(storage.COVERS_DIR, name); - -test("a kept track takes the cover embedded in its file", async () => { - const track = await ingestAudioFile( - tempFile("with.mp3"), - { permanent: true }, - { queue: fakeQueue(), probe, createCover: fakeCreate } - ); - const entry = storage.findPermanentTrack(track.libraryTrackId); - assert.match(entry.cover, /^[0-9a-f-]{36}\.jpg$/); - assert.equal(fs.existsSync(coverPath(entry.cover)), true); - assert.equal(serializeTrack(entry).coverUrl, `/covers/${entry.cover}`); - assert.equal("cover" in serializeTrack(entry), false); - - const without = await ingestAudioFile( - tempFile("without.mp3"), - { permanent: true }, - { queue: fakeQueue(), probe, createCover: noCover } - ); - const withoutEntry = storage.findPermanentTrack(without.libraryTrackId); - // Examiné une fois : null, pour ne pas être retenté à chaque démarrage. - assert.equal(withoutEntry.cover, null); - assert.equal("coverUrl" in serializeTrack(withoutEntry), false); -}); - -test("a new cover replaces the old file, and only images are accepted", async () => { - const id = ( - await ingestAudioFile(tempFile("c.mp3"), { permanent: true }, { - queue: fakeQueue(), probe, createCover: fakeCreate, - }) - ).libraryTrackId; - const oldCover = storage.findPermanentTrack(id).cover; - - const png = tempFile("cover.png", "\x89PNG\r\n\x1a\n0000"); - const newCover = await covers.saveCoverFromImage(png.path, { create: fakeCreate }); - covers.setTrackCover(id, newCover); - assert.equal(storage.findPermanentTrack(id).cover, newCover); - assert.equal(fs.existsSync(coverPath(oldCover)), false); - - const text = tempFile("cover.txt", "#EXTM3U\nfile:///etc/passwd\n"); - await assert.rejects(covers.saveCoverFromImage(text.path, { create: fakeCreate }), { - status: 400, - }); - - covers.setTrackCover(id, null); - assert.equal(storage.findPermanentTrack(id).cover, null); - assert.equal(fs.existsSync(coverPath(newCover)), false); -}); - -test("deleting a track deletes its cover", async () => { - const { libraryTrackId } = await ingestAudioFile(tempFile("d.mp3"), { permanent: true }, { - queue: fakeQueue(), probe, createCover: fakeCreate, - }); - const { cover } = storage.findPermanentTrack(libraryTrackId); - storage.deletePermanentTrack(libraryTrackId); - assert.equal(fs.existsSync(coverPath(cover)), false); -}); - -test("the startup backfill looks once for the covers of older tracks", async () => { - const older = storage.registerUploadedFile(tempFile("old.mp3"), { - permanent: true, - duration: 10, - }).libraryTrackId; - assert.equal(storage.findPermanentTrack(older).cover, undefined); - - const updated = await backfillLibraryMetadata({ probe, createCover: fakeCreate }); - assert.deepEqual(updated.map((entry) => entry.id), [older]); - assert.ok(storage.findPermanentTrack(older).cover); - - assert.deepEqual(await backfillLibraryMetadata({ probe, createCover: fakeCreate }), []); -}); diff --git a/test/librarySections.test.js b/test/librarySections.test.js deleted file mode 100644 index 760b95f..0000000 --- a/test/librarySections.test.js +++ /dev/null @@ -1,91 +0,0 @@ -/** - * @file Vérifie les sections de la bibliothèque : création, renommage, déplacement, image, et - * suppression qui remet ses morceaux sans section. - */ - -import test from "node:test"; -import assert from "node:assert/strict"; -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-sections-")); -process.chdir(temporaryDirectory); -const storage = await import("../src/web/storage/storageManager.js"); -const sections = await import("../src/web/storage/librarySections.js"); -const { serializeSection } = await import("../src/web/serializers.js"); -storage.ensureStorageLayout(); -test.after(() => { - process.chdir(originalDirectory); - fs.rmSync(temporaryDirectory, { recursive: true, force: true }); -}); - -function addTrack(name, sectionId) { - const filePath = path.join(storage.TEMP_DIR, `upload-${name}`); - fs.writeFileSync(filePath, "audio"); - return storage.registerUploadedFile( - { path: filePath, originalname: name, size: 5, mimetype: "audio/mpeg" }, - { permanent: true, uploader: "test", sectionId } - ).libraryTrackId; -} - -test("sections are created, renamed and reordered", () => { - assert.deepEqual(sections.getSections(), []); - const chill = sections.createSection(" Chill\u0007 "); - const boss = sections.createSection("Combats de boss"); - const menu = sections.createSection("Menus"); - assert.equal(chill.name, "Chill"); - - sections.updateSection(menu.id, { name: "Écrans titres", position: 0 }); - assert.deepEqual( - sections.getSections().map((section) => section.name), - ["Écrans titres", "Chill", "Combats de boss"] - ); - assert.equal(sections.findSection(boss.id).name, "Combats de boss"); - assert.equal(sections.updateSection("unknown", { name: "x" }), null); -}); - -test("invalid names and positions are refused", () => { - const [first] = sections.getSections(); - assert.throws(() => sections.createSection(" "), { status: 400 }); - assert.throws(() => sections.updateSection(first.id, { position: 99 }), { status: 400 }); - assert.throws(() => sections.updateSection(first.id, { position: "1" }), { status: 400 }); -}); - -test("deleting a section keeps its tracks, without a section", () => { - const doomed = sections.createSection("À supprimer"); - const kept = sections.createSection("Gardée"); - const inDoomed = addTrack("a.mp3", doomed.id); - const inKept = addTrack("b.mp3", kept.id); - - assert.equal(sections.deleteSection(doomed.id).id, doomed.id); - - assert.equal(sections.findSection(doomed.id), undefined); - assert.equal(storage.findPermanentTrack(inDoomed).sectionId, null); - assert.equal(storage.findPermanentTrack(inKept).sectionId, kept.id); - assert.equal(sections.deleteSection(doomed.id), null); -}); - -test("a section image is replaced, removed, and deleted with its section", () => { - const section = sections.createSection("Avec image"); - const coverFile = (name) => path.join(storage.COVERS_DIR, name); - fs.writeFileSync(coverFile("first.jpg"), "jpeg"); - fs.writeFileSync(coverFile("second.jpg"), "jpeg"); - - sections.setSectionCover(section.id, "first.jpg"); - assert.equal(serializeSection(sections.findSection(section.id)).coverUrl, "/covers/first.jpg"); - assert.equal("cover" in serializeSection(sections.findSection(section.id)), false); - - sections.setSectionCover(section.id, "second.jpg"); - assert.equal(fs.existsSync(coverFile("first.jpg")), false); - - // Section disparue : la nouvelle image est supprimée au lieu de rester orpheline. - fs.writeFileSync(coverFile("orphan.jpg"), "jpeg"); - assert.equal(sections.setSectionCover("unknown", "orphan.jpg"), null); - assert.equal(fs.existsSync(coverFile("orphan.jpg")), false); - - sections.deleteSection(section.id); - assert.equal(fs.existsSync(coverFile("second.jpg")), false); -}); diff --git a/test/musicQueue.test.js b/test/musicQueue.test.js index 726c9b0..2b56a77 100644 --- a/test/musicQueue.test.js +++ b/test/musicQueue.test.js @@ -1,12 +1,5 @@ -/** - * @file Couvre la file du jukebox sans Discord : lecture, reconnexion, départ et retour du bot dans le - * salon, reprise d'un morceau interrompu à sa position, mode boucle, mélange et reprise après - * un redémarrage, déplacement dans le morceau en cours. - */ - import test from "node:test"; import assert from "node:assert/strict"; -import { EventEmitter } from "node:events"; Object.assign(process.env, { NODE_ENV: "test", @@ -50,275 +43,10 @@ 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)); - -// Simule un morceau en cours dont `playedMs` millisecondes ont été jouées depuis le départ du flux. -function setPlayed(queue, playedMs) { - Object.defineProperty(queue.audioPlayer, "state", { - value: { status: "playing", resource: { playbackDuration: playedMs } }, - writable: true, - configurable: true, - }); -} - -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")); - 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((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("an interrupted track resumes a little before where it stopped", () => { - const { client } = fakeClient([BOT_ID]); - const { queue } = fakeQueue(client); - - // Déjà repris à 100 s, puis 25,4 s jouées : il était à 125,4 s, et reprendra à 123 s. - queue.connection = { destroy() {} }; - queue.currentTrack = { ...track("a"), resumeAt: 100, startedAt: "2026-01-01T00:00:00.000Z" }; - setPlayed(queue, 25_400); - assert.equal(queue.snapshot().position, 125_400); - queue.destroyConnection("alone timeout", { suspend: true, requeue: true }); - assert.equal(queue.queue[0].resumeAt, 123); - assert.equal("startedAt" in queue.queue[0], false); - - // Connexion perdue : la position est celle relevée à la coupure, pas celle de l'abandon. - queue.queue = []; - queue.connection = { destroy() {} }; - queue.currentTrack = track("b"); - setPlayed(queue, 65_000); - queue.destroyConnection("voice connection lost", { requeue: true, position: 60_000 }); - assert.equal(queue.queue[0].resumeAt, 58); - - // Interrompu dans ses premières secondes : il repart du début. - queue.queue = []; - queue.connection = { destroy() {} }; - queue.currentTrack = track("c"); - setPlayed(queue, 1_500); - queue.destroyConnection("voice connection lost", { requeue: true }); - assert.equal("resumeAt" in queue.queue[0], false); - queue.shutdown(); -}); - -test("seeking restarts the current track at the chosen position", () => { - const { client } = fakeClient(); - const { queue, played } = fakeQueue(client); - assert.equal(queue.seek(30), null); - - queue.currentTrack = { ...track("a"), duration: 200, resumeAt: 10, startedAt: "x" }; - setPlayed(queue, 0); - assert.equal(queue.seek(95.7).position, 95_000); - assert.equal(queue.currentTrack.resumeAt, 95); - assert.equal(queue.currentTrack.startedAt, "x"); - assert.deepEqual(played, ["a"]); - - // Au-delà de la fin : juste avant la fin. Au début : sans position de reprise. - queue.seek(500); - assert.equal(queue.currentTrack.resumeAt, 199); - queue.seek(0); - assert.equal("resumeAt" in queue.currentTrack, false); - 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"), resumeAt: 50 }; - queue.queue.push(track("b")); - queue.playNext = () => {}; - - queue.audioPlayer.emit("idle"); - assert.deepEqual(queue.queue.map(({ path }) => path), ["/nonexistent/b", "/nonexistent/a"]); - // Le morceau repris en cours de route repart du début au tour suivant. - assert.equal("resumeAt" in queue.queue[1], false); - - // 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); - setPlayed(first, 90_000); - - // Enregistrement pendant la lecture (couvre un arrêt brutal) : la position y figure déjà. - first.save(); - assert.equal(saved.queue[0].resumeAt, 88); - - first.shutdown(); - assert.deepEqual(saved.queue.map(({ id }) => id), ["a", "b"]); - assert.equal("startedAt" in saved.queue[0], false); - assert.equal(saved.queue[0].resumeAt, 88); - - const second = new MusicQueue(client, { persistence }); - assert.deepEqual(second.queue.map(({ id }) => id), ["a", "b"]); - assert.equal(second.queue[0].resumeAt, 88); - assert.equal(second.loop, true); - assert.equal(second.suspendedForAlone, true); - second.shutdown(); -}); diff --git a/test/serializers.test.js b/test/serializers.test.js index 8bd42af..595d8c2 100644 --- a/test/serializers.test.js +++ b/test/serializers.test.js @@ -1,7 +1,3 @@ -/** - * @file Vérifie que les morceaux envoyés par l'API ne montrent pas leurs chemins sur le disque. - */ - import test from "node:test"; import assert from "node:assert/strict"; import { serializeTrack, serializeTracks } from "../src/web/serializers.js"; diff --git a/test/storageManager.test.js b/test/storageManager.test.js index 07cb5e9..15bb48a 100644 --- a/test/storageManager.test.js +++ b/test/storageManager.test.js @@ -1,8 +1,3 @@ -/** - * @file Vérifie la bibliothèque dans un dossier temporaire : chemins portables, migration de l'ancien - * fichier et complément des durées manquantes. - */ - import test from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; @@ -86,36 +81,3 @@ 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/tags.test.js b/test/tags.test.js deleted file mode 100644 index 3c94cc0..0000000 --- a/test/tags.test.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * @file Vérifie le nettoyage des étiquettes (espaces, virgules, doublons, limites) et leur comparaison - * sans tenir compte des majuscules. - */ - -import test from "node:test"; -import assert from "node:assert/strict"; -import { cleanTags, hasTag } from "../src/features/tags.js"; - -test("tags are trimmed, deduplicated and kept in their first spelling", () => { - assert.deepEqual( - cleanTags([" Épique ", "calme", "épique", "", "a,b", "Monster\u0007 Hunter", null]), - ["Épique", "calme", "a b", "Monster Hunter"] - ); - assert.deepEqual(cleanTags([]), []); - assert.equal(cleanTags("épique, calme"), null); -}); - -test("tags are limited in number and length", () => { - const many = Array.from({ length: 20 }, (_, index) => `tag${index}`); - assert.equal(cleanTags(many).length, 15); - assert.equal(cleanTags(["x".repeat(50)])[0].length, 30); -}); - -test("tag matching ignores case", () => { - assert.equal(hasTag({ tags: ["Épique"] }, "épique"), true); - assert.equal(hasTag({ tags: ["calme"] }, "épique"), false); - assert.equal(hasTag({}, "épique"), false); -}); diff --git a/test/webServer.test.js b/test/webServer.test.js index d78d077..da68460 100644 --- a/test/webServer.test.js +++ b/test/webServer.test.js @@ -1,9 +1,3 @@ -/** - * @file Couvre l'application web : route des messages privés (clé, limite, connexions locales), - * /readyz, ancienne adresse du jukebox, déplacement dans le morceau en cours et flux - * d'événements. - */ - import test from "node:test"; import assert from "node:assert/strict"; @@ -48,8 +42,6 @@ function fakeClient() { const fakeQueue = { snapshot: () => ({ current: null, upcoming: [], status: "idle" }), - // Aucun morceau en cours, sauf quand la position demandée vaut 42. - seek: (seconds) => (seconds === 42 ? { position: 42_000 } : null), }; async function withServer(options, run) { @@ -122,116 +114,3 @@ 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 old jukebox address redirects to the home page", async () => { - await withServer({}, async ({ base }) => { - const get = (path) => fetch(`${base}${path}`, { redirect: "manual" }); - const plain = await get("/jukebox/"); - assert.equal(plain.status, 301); - assert.equal(plain.headers.get("location"), "/"); - assert.equal((await get("/jukebox?login=denied")).headers.get("location"), "/?login=denied"); - const home = await get("/"); - assert.equal(home.status, 200); - assert.match(await home.text(), /Palico Jukebox<\/title>/); - }); -}); - -test("seeking needs a position in seconds and a track playing", async () => { - await withServer({}, async ({ base }) => { - const seek = (body) => - fetch(`${base}/api/player/seek`, { - method: "POST", - headers: { authorization: "Bearer web-key", "content-type": "application/json" }, - body: JSON.stringify(body), - }); - assert.equal((await seek({ position: 42 })).status, 200); - assert.equal((await seek({ position: 10 })).status, 409); - assert.equal((await seek({ position: "42" })).status, 400); - assert.equal((await seek({ position: -1 })).status, 400); - assert.equal((await seek({})).status, 400); - }); -}); - -test("the events stream requires the jukebox key", async () => { - await withServer({}, async ({ base }) => { - assert.equal((await fetch(`${base}/api/events`)).status, 401); - }); -});