Compare commits

..

No commits in common. "main" and "develop" have entirely different histories.

89 changed files with 1585 additions and 7778 deletions

View file

@ -1,6 +1,6 @@
NODE_ENV=test
DISCORD_GUILD_ID= DISCORD_GUILD_ID=
# Personne qui gère les serveurs de jeux, mentionnée dans leur message (ancien nom : SHINUWA_USER_ID). SHINUWA_USER_ID=
OWNER_USER_ID=
WEB_SERVER_PORT=3000 WEB_SERVER_PORT=3000
WEB_API_KEY= WEB_API_KEY=
DISCORD_APPLICATION_ID= DISCORD_APPLICATION_ID=
@ -14,11 +14,3 @@ WEB_TRUSTED_PROXIES=
NOTIFICATIONS_API_KEY= NOTIFICATIONS_API_KEY=
# Facultatif : lien d'invitation temporaire publié par /invitation sans option « lien ». # Facultatif : lien d'invitation temporaire publié par /invitation sans option « lien ».
INVITE_LINK= 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 <adresse>/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=

View file

@ -1,40 +1,22 @@
name: Deploy Palico Bot 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: on:
push: push:
branches:
- main
jobs: jobs:
check: deploy:
runs-on: docker runs-on: docker
# Image fixée ici : celle du label « docker » (node:20-bullseye) n'est plus maintenue, # 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). # et son miroir de sécurité renvoie 404 (échec du run 4).
container: container:
image: node:24-bookworm 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: steps:
- name: Deploy on WebApps - name: Deploy on WebApps
env: env:
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }} 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: | run: |
# L'image contient déjà le client SSH ; ne l'installer que s'il manque. # L'image contient déjà le client SSH ; ne l'installer que s'il manque.
if ! command -v ssh >/dev/null; then if ! command -v ssh >/dev/null; then
@ -42,17 +24,11 @@ jobs:
apt-get install -y --no-install-recommends openssh-client apt-get install -y --no-install-recommends openssh-client
fi 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 mkdir -p ~/.ssh
printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_ed25519 printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_ed25519
printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > ~/.ssh/known_hosts
chmod 600 ~/.ssh/id_ed25519 chmod 600 ~/.ssh/id_ed25519
ssh -o StrictHostKeyChecking=yes \ ssh -o StrictHostKeyChecking=no \
-i ~/.ssh/id_ed25519 \ -i ~/.ssh/id_ed25519 \
-p 2911 \ -p 2911 \
shinuwa@192.168.0.100 \ shinuwa@192.168.0.100 \

1
.gitignore vendored
View file

@ -17,7 +17,6 @@ storage/permanent/*
!storage/permanent/.gitkeep !storage/permanent/.gitkeep
storage/temp/* storage/temp/*
!storage/temp/.gitkeep !storage/temp/.gitkeep
storage/covers/
# Operating system files # Operating system files
.DS_Store .DS_Store

View file

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

View file

@ -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 <Ce que fait le fichier et pourquoi il existe, en une ou deux phrases.>
*
* Contexte : <sa place dans l'ensemble (bot, serveur web, page).>
* Points d'entrée : <les 2 à 4 exports ou méthodes importants, pas la liste complète.>
* Utilisé par : <appelants principaux.>
* Dépend de : <modules clés.>
* Attention : <invariants, pièges, effets de bord.>
* @see <section du README ou document de référence>
*/
```
### 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.

140
README.md
View file

@ -1,20 +1,5 @@
# palico-bot # 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 ## Configuration
La configuration sensible est stockée dans un fichier `.env` exclu de Git. La configuration sensible est stockée dans un fichier `.env` exclu de Git.
@ -38,14 +23,30 @@ npm start
npm run deploy 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 ## Données persistantes
Le dossier `storage/` est une donnée applicative et ne doit pas être remplacé Le dossier `storage/` est une donnée applicative et ne doit pas être remplacé
pendant un déploiement. Sauvegarder régulièrement : pendant un déploiement. Sauvegarder régulièrement :
- `storage/runtime/library.json`, `storage/runtime/sections.json` (sections de - `storage/runtime/library.json` ;
la bibliothèque) et `storage/runtime/queue.json` (la file en cours) ; - `storage/permanent/`.
- `storage/permanent/` (fichiers audio) et `storage/covers/` (pochettes).
Les fichiers placés dans `storage/temp/` sont temporaires et nettoyés après Les fichiers placés dans `storage/temp/` sont temporaires et nettoyés après
24 heures. 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 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 ## Déploiement
`.forgejo/workflows/deploy.yml` lance `npm ci` puis `npm run check` (syntaxe et Un push sur `main` lance `.forgejo/workflows/deploy.yml`, qui se connecte en SSH
tests) à chaque push, sur toutes les branches. Sur `main`, et seulement si ces à la VM et exécute `/usr/local/bin/deploy-palico-bot` (mise à jour du dépôt,
contrôles réussissent, il se connecte ensuite en SSH à la VM et exécute dépendances, redémarrage du service `palico-bot`). Le workflow ne lance ni les
`/usr/local/bin/deploy-palico-bot` (mise à jour du dépôt, dépendances, redémarrage contrôles ni les tests : lancer `npm run check` avant de pousser.
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.
Variables facultatives : Variables facultatives :
@ -91,73 +75,6 @@ Variables facultatives :
- `INVITE_LINK` : lien publié par `/invitation` quand la commande ne reçoit pas - `INVITE_LINK` : lien publié par `/invitation` quand la commande ne reçoit pas
de lien. 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": <secondes> }`) :
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 `<WEB_PUBLIC_URL>/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 ## Invitations
Les membres ne peuvent pas créer d'invitation : un seul lien, à adhésion 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 `NOTIFICATIONS_API_KEY` en `Authorization: Bearer …` ; sans cette variable, elle
répond `503`. répond `503`.
Corps : `{ "userId": "<identifiant Discord>", "content": "<texte, 2000 caractères au plus>" }`, Corps : `{ "userId": "<identifiant Discord>", "content": "<texte, 2000 caractères au plus>" }`.
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.
Réponses : `204` envoyé, `400` corps invalide, `401` mauvaise clé, `403` Réponses : `204` envoyé, `400` corps invalide, `401` mauvaise clé, `403`
connexion non locale, `404` utilisateur inconnu (`UNKNOWN_USER`), `422` messages connexion non locale, `404` utilisateur inconnu (`UNKNOWN_USER`), `422` messages
privés impossibles (`DM_CLOSED` : aucun serveur en commun avec le bot, ou messages privés impossibles (`DM_CLOSED` : aucun serveur en commun avec le bot, ou messages

View file

@ -1,13 +1,35 @@
/**
* @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 { config } from "./src/config.js";
import { loadCommands } from "./src/loadCommands.js";
const commands = (await loadCommands()).map((command) => command.data.toJSON()); 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); const rest = new REST().setToken(config.token);

View file

@ -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 { Client, Collection, GatewayIntentBits } from "discord.js";
import fs from "fs"; import fs from "fs";
import path from "path"; import path from "path";
import { fileURLToPath } from "url"; import { fileURLToPath } from "url";
import { config } from "./src/config.js"; import { config } from "./src/config.js";
import { loadCommands } from "./src/loadCommands.js";
import { MusicQueue } from "./src/music/queue.js"; import { MusicQueue } from "./src/music/queue.js";
import { createQueuePersistence } from "./src/music/queuePersistence.js";
import { startWebServer } from "./src/web/server.js"; import { startWebServer } from "./src/web/server.js";
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
@ -30,9 +13,29 @@ const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates], intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates],
}); });
client.commands = new Collection( client.commands = new Collection();
(await loadCommands()).map((command) => [command.data.name, command]) 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 eventsPath = path.join(__dirname, "src/events");
const eventFiles = fs const eventFiles = fs
@ -53,13 +56,7 @@ for (const file of eventFiles) {
} }
} }
const musicQueue = new MusicQueue(client, { const musicQueue = new MusicQueue(client);
persistence: createQueuePersistence(
path.join(process.cwd(), "storage", "runtime", "queue.json")
),
});
// Les commandes du jukebox (/play, /skip, /queue) y accèdent par interaction.client.
client.musicQueue = musicQueue;
await client.login(config.token); await client.login(config.token);
const { server } = startWebServer({ queue: musicQueue, client }); const { server } = startWebServer({ queue: musicQueue, client });
@ -83,9 +80,6 @@ async function shutdown(signal) {
server.close(() => { server.close(() => {
clearTimeout(forceExit); 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")); process.once("SIGTERM", () => void shutdown("SIGTERM"));

476
package-lock.json generated
View file

@ -22,15 +22,15 @@
} }
}, },
"node_modules/@discordjs/builders": { "node_modules/@discordjs/builders": {
"version": "1.15.0", "version": "1.14.1",
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.15.0.tgz", "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz",
"integrity": "sha512-AifaDWTw6WUDhKBn8E6mwwoyjDAcfsYq+ZE0nKSu1dMH1NLR22D3hGkNx+ctEv8NqHEHdAZnP5REteHDmn1lkA==", "integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@discordjs/formatters": "^0.6.2", "@discordjs/formatters": "^0.6.2",
"@discordjs/util": "^1.2.0", "@discordjs/util": "^1.2.0",
"@sapphire/shapeshift": "^4.0.0", "@sapphire/shapeshift": "^4.0.0",
"discord-api-types": "^0.38.50", "discord-api-types": "^0.38.40",
"fast-deep-equal": "^3.1.3", "fast-deep-equal": "^3.1.3",
"ts-mixer": "^6.0.4", "ts-mixer": "^6.0.4",
"tslib": "^2.6.3" "tslib": "^2.6.3"
@ -67,9 +67,9 @@
} }
}, },
"node_modules/@discordjs/rest": { "node_modules/@discordjs/rest": {
"version": "2.6.3", "version": "2.6.1",
"resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.3.tgz", "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.1.tgz",
"integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==", "integrity": "sha512-wwQdgjeaoYFiaG+atbqx6aJDpqW7JHAo0HrQkBTbYzM3/PJ3GweQIpgElNcGZ26DCUOXMyawYd0YF7vtr+fZXg==",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@discordjs/collection": "^2.1.1", "@discordjs/collection": "^2.1.1",
@ -77,10 +77,10 @@
"@sapphire/async-queue": "^1.5.3", "@sapphire/async-queue": "^1.5.3",
"@sapphire/snowflake": "^3.5.5", "@sapphire/snowflake": "^3.5.5",
"@vladfrangu/async_event_emitter": "^2.4.6", "@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", "magic-bytes.js": "^1.13.0",
"tslib": "^2.6.3", "tslib": "^2.6.3",
"undici": "^6.27.0" "undici": "6.24.1"
}, },
"engines": { "engines": {
"node": ">=18" "node": ">=18"
@ -101,6 +101,16 @@
"url": "https://github.com/discordjs/discord.js?sponsor" "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": { "node_modules/@discordjs/util": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz", "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz",
@ -172,21 +182,21 @@
} }
}, },
"node_modules/@emnapi/core": { "node_modules/@emnapi/core": {
"version": "1.11.3", "version": "1.11.1",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
"integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==", "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==",
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"peer": true, "peer": true,
"dependencies": { "dependencies": {
"@emnapi/wasi-threads": "1.2.3", "@emnapi/wasi-threads": "1.2.2",
"tslib": "^2.4.0" "tslib": "^2.4.0"
} }
}, },
"node_modules/@emnapi/runtime": { "node_modules/@emnapi/runtime": {
"version": "1.11.3", "version": "1.11.1",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz",
"integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==",
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"peer": true, "peer": true,
@ -195,9 +205,9 @@
} }
}, },
"node_modules/@emnapi/wasi-threads": { "node_modules/@emnapi/wasi-threads": {
"version": "1.2.3", "version": "1.2.2",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz", "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",
"integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==", "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==",
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"peer": true, "peer": true,
@ -206,24 +216,21 @@
} }
}, },
"node_modules/@napi-rs/wasm-runtime": { "node_modules/@napi-rs/wasm-runtime": {
"version": "1.2.7", "version": "1.1.6",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.7.tgz", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz",
"integrity": "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==", "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==",
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"dependencies": { "dependencies": {
"@tybys/wasm-util": "^0.10.3" "@tybys/wasm-util": "^0.10.3"
}, },
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
},
"funding": { "funding": {
"type": "github", "type": "github",
"url": "https://github.com/sponsors/Brooooooklyn" "url": "https://github.com/sponsors/Brooooooklyn"
}, },
"peerDependencies": { "peerDependencies": {
"@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", "@emnapi/core": "^1.7.1",
"@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" "@emnapi/runtime": "^1.7.1"
} }
}, },
"node_modules/@sapphire/async-queue": { "node_modules/@sapphire/async-queue": {
@ -250,9 +257,9 @@
} }
}, },
"node_modules/@sapphire/snowflake": { "node_modules/@sapphire/snowflake": {
"version": "3.5.5", "version": "3.5.3",
"resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz", "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.3.tgz",
"integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==", "integrity": "sha512-jjmJywLAFoWeBi1W7994zZyiNWPIiqRRNAmSERxyg93xRGzNYvGjlZ0gR6x0F4gPRi2+0O6S71kOZYyr3cxaIQ==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=v14.0.0", "node": ">=v14.0.0",
@ -524,9 +531,9 @@
} }
}, },
"node_modules/@tybys/wasm-util": { "node_modules/@tybys/wasm-util": {
"version": "0.10.5", "version": "0.10.3",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
"integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==",
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"dependencies": { "dependencies": {
@ -534,18 +541,18 @@
} }
}, },
"node_modules/@types/node": { "node_modules/@types/node": {
"version": "26.6.11", "version": "24.10.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz",
"integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==", "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"undici-types": "~8.9.0" "undici-types": "~7.16.0"
} }
}, },
"node_modules/@types/ws": { "node_modules/@types/ws": {
"version": "8.18.2", "version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@types/node": "*" "@types/node": "*"
@ -581,18 +588,18 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/body-parser": { "node_modules/body-parser": {
"version": "2.4.0", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
"integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"bytes": "^3.1.2", "bytes": "^3.1.2",
"content-type": "^2.1.0", "content-type": "^2.0.0",
"debug": "^4.4.3", "debug": "^4.4.3",
"http-errors": "^2.0.1", "http-errors": "^2.0.1",
"iconv-lite": "^0.7.3", "iconv-lite": "^0.7.2",
"on-finished": "^2.4.1", "on-finished": "^2.4.1",
"qs": "^6.16.1", "qs": "^6.15.2",
"raw-body": "^3.0.2", "raw-body": "^3.0.2",
"type-is": "^2.1.0" "type-is": "^2.1.0"
}, },
@ -604,6 +611,25 @@
"url": "https://opencollective.com/express" "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": { "node_modules/busboy": {
"version": "1.6.0", "version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
@ -653,30 +679,40 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/content-disposition": { "node_modules/concat-stream": {
"version": "2.0.1", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
"integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
"engines": [
"node >= 6.0"
],
"license": "MIT", "license": "MIT",
"engines": { "dependencies": {
"node": ">=18" "buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^3.0.2",
"typedarray": "^0.0.6"
}
}, },
"funding": { "node_modules/content-disposition": {
"type": "opencollective", "version": "1.0.0",
"url": "https://opencollective.com/express" "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"
},
"engines": {
"node": ">= 0.6"
} }
}, },
"node_modules/content-type": { "node_modules/content-type": {
"version": "2.1.0", "version": "1.0.5",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
"integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=18" "node": ">= 0.6"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
} }
}, },
"node_modules/cookie": { "node_modules/cookie": {
@ -724,30 +760,33 @@
} }
}, },
"node_modules/discord-api-types": { "node_modules/discord-api-types": {
"version": "0.38.60", "version": "0.38.49",
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.60.tgz", "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.49.tgz",
"integrity": "sha512-2xPScuQP3WOf3H4EKWLzvnhlfNl8sBMD+krT8CcjMVJa6o9D/6ssOSgKPTvHyIhQDKUX+gvUJZ43U4HqE+6tsA==", "integrity": "sha512-XnqcWmnFZFAE8ZM8SHAw9DIV8D3Or00rMQ8iQLotrEA2PmXhl+ykaf6L6q4l474hrSUH1JaYcv+iOMRWp2p6Tg==",
"license": "MIT" "license": "MIT",
"workspaces": [
"scripts/actions/documentation"
]
}, },
"node_modules/discord.js": { "node_modules/discord.js": {
"version": "14.28.1", "version": "14.26.4",
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.28.1.tgz", "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.26.4.tgz",
"integrity": "sha512-Je5OcqgurnIUQK4vR+gQnmzOf/lNQsD6d/UkV8ZOj+bFa5zJXPyiGXlbywp2EagwshVT18y7YNQNSRd3FjYkDw==", "integrity": "sha512-4oBp8tc6Kf8IDBwAHhbsMaAqx1b5fob9SNasZT7V6yyyUydoO5i5fGuX7TmvRtR+q/WgKRnRViRoAWnG7fNyvA==",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@discordjs/builders": "^1.15.0", "@discordjs/builders": "^1.14.1",
"@discordjs/collection": "1.5.3", "@discordjs/collection": "1.5.3",
"@discordjs/formatters": "^0.6.2", "@discordjs/formatters": "^0.6.2",
"@discordjs/rest": "^2.6.3", "@discordjs/rest": "^2.6.1",
"@discordjs/util": "^1.2.0", "@discordjs/util": "^1.2.0",
"@discordjs/ws": "^1.2.3", "@discordjs/ws": "^1.2.3",
"@sapphire/snowflake": "3.5.5", "@sapphire/snowflake": "3.5.3",
"discord-api-types": "^0.38.50", "discord-api-types": "^0.38.40",
"fast-deep-equal": "3.1.3", "fast-deep-equal": "3.1.3",
"lodash.snakecase": "4.1.1", "lodash.snakecase": "4.1.1",
"magic-bytes.js": "^1.13.0", "magic-bytes.js": "^1.13.0",
"tslib": "^2.6.3", "tslib": "^2.6.3",
"undici": "^6.27.0" "undici": "6.24.1"
}, },
"engines": { "engines": {
"node": ">=18" "node": ">=18"
@ -777,16 +816,12 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/encodeurl": { "node_modules/encodeurl": {
"version": "2.0.3", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 0.8" "node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
} }
}, },
"node_modules/es-define-property": { "node_modules/es-define-property": {
@ -835,15 +870,15 @@
} }
}, },
"node_modules/express": { "node_modules/express": {
"version": "5.3.0", "version": "5.2.1",
"resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
"integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"accepts": "^2.0.0", "accepts": "^2.0.0",
"body-parser": "^2.3.0", "body-parser": "^2.2.1",
"content-disposition": "^2.0.1", "content-disposition": "^1.0.0",
"content-type": "^2.0.0", "content-type": "^1.0.5",
"cookie": "^0.7.1", "cookie": "^0.7.1",
"cookie-signature": "^1.2.1", "cookie-signature": "^1.2.1",
"debug": "^4.4.0", "debug": "^4.4.0",
@ -859,14 +894,14 @@
"on-finished": "^2.4.1", "on-finished": "^2.4.1",
"once": "^1.4.0", "once": "^1.4.0",
"parseurl": "^1.3.3", "parseurl": "^1.3.3",
"proxy-addr": "^2.0.8", "proxy-addr": "^2.0.7",
"qs": "^6.16.0", "qs": "^6.14.0",
"range-parser": "^1.2.1", "range-parser": "^1.2.1",
"router": "^2.2.0", "router": "^2.2.0",
"send": "^1.1.0", "send": "^1.1.0",
"serve-static": "^2.2.0", "serve-static": "^2.2.0",
"statuses": "^2.0.1", "statuses": "^2.0.1",
"type-is": "^2.1.0", "type-is": "^2.0.1",
"vary": "^1.1.2" "vary": "^1.1.2"
}, },
"engines": { "engines": {
@ -878,12 +913,11 @@
} }
}, },
"node_modules/express-rate-limit": { "node_modules/express-rate-limit": {
"version": "8.7.5", "version": "8.5.2",
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.5.tgz", "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz",
"integrity": "sha512-wi+v38cx2EqD0JnhE/e74o5tFqKWUOAPFJIgyEiqJ8v2MNpoOAA3kI2hXYOI+YM+HE5yqbdAlVxm2GqOIeYOgA==", "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"debug": "^4.4.3",
"ip-address": "^10.2.0" "ip-address": "^10.2.0"
}, },
"engines": { "engines": {
@ -903,9 +937,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/finalhandler": { "node_modules/finalhandler": {
"version": "2.1.1", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz",
"integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"debug": "^4.4.0", "debug": "^4.4.0",
@ -916,11 +950,7 @@
"statuses": "^2.0.1" "statuses": "^2.0.1"
}, },
"engines": { "engines": {
"node": ">= 18.0.0" "node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
} }
}, },
"node_modules/forwarded": { "node_modules/forwarded": {
@ -1024,9 +1054,9 @@
} }
}, },
"node_modules/helmet": { "node_modules/helmet": {
"version": "8.3.0", "version": "8.2.0",
"resolved": "https://registry.npmjs.org/helmet/-/helmet-8.3.0.tgz", "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.2.0.tgz",
"integrity": "sha512-Qgpiaws3Sm30Av8Eah6sjMCZZwjlBu+E68rhpCWBshY1lb09HtLwj5GviX0OyQIn+ulUS0iX0AxN5n3tLZzz1w==", "integrity": "sha512-DRgTIUgnWcJ62KyarxxziuqYxKGnR6Rgg19BlbucN/dpmJbl1XOit6qvoOX0ZT+HhWe5OUVhU/a1zpGyc1xA0Q==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=18.0.0" "node": ">=18.0.0"
@ -1056,9 +1086,9 @@
} }
}, },
"node_modules/iconv-lite": { "node_modules/iconv-lite": {
"version": "0.7.3", "version": "0.7.2",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",
"integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0" "safer-buffer": ">= 2.1.2 < 3.0.0"
@ -1078,9 +1108,9 @@
"license": "ISC" "license": "ISC"
}, },
"node_modules/ip-address": { "node_modules/ip-address": {
"version": "10.7.7", "version": "10.2.0",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.7.tgz", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
"integrity": "sha512-He15rAs4jip5AEAz7XM9L+S6Y8LBMIDj6YewbYuJfmDnOCKWb+3TLOGnHFBTAIW7wpm5ohtZ+Xyo5PEaG+O2vQ==", "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 12" "node": ">= 12"
@ -1114,9 +1144,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/magic-bytes.js": { "node_modules/magic-bytes.js": {
"version": "1.13.1", "version": "1.13.0",
"resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.1.tgz", "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.0.tgz",
"integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==", "integrity": "sha512-afO2mnxW7GDTXMm5/AoN1WuOcdoKhtgXjIvHmobqTD1grNplhGdv3PFOyjCVmrnOZBIT/gD/koDKpYG+0mvHcg==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/math-intrinsics": { "node_modules/math-intrinsics": {
@ -1129,16 +1159,12 @@
} }
}, },
"node_modules/media-typer": { "node_modules/media-typer": {
"version": "1.1.1", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
"integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 0.8" "node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
} }
}, },
"node_modules/merge-descriptors": { "node_modules/merge-descriptors": {
@ -1163,19 +1189,15 @@
} }
}, },
"node_modules/mime-types": { "node_modules/mime-types": {
"version": "3.0.2", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz",
"integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"mime-db": "^1.54.0" "mime-db": "^1.54.0"
}, },
"engines": { "engines": {
"node": ">=18" "node": ">= 0.6"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
} }
}, },
"node_modules/ms": { "node_modules/ms": {
@ -1185,13 +1207,14 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/multer": { "node_modules/multer": {
"version": "2.5.0", "version": "2.2.0",
"resolved": "https://registry.npmjs.org/multer/-/multer-2.5.0.tgz", "resolved": "https://registry.npmjs.org/multer/-/multer-2.2.0.tgz",
"integrity": "sha512-BsqOzYGVq49JcW2IzoSAxeKYRevb+dGGPPWleOR8Lrlk4igwxu1/9pwSXlByhCb7MVZDrNJFC0IBP5/O5nLYRw==", "integrity": "sha512-6rdyFg2kLrMh9Jee7/BMPuV9lEAd7lLW2YUpF9/YxR7njyoUwwQ0ZPh3TaIY50Sw6vlyD2HW3wGOkTS4P79xrQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"append-field": "^1.0.0", "append-field": "^1.0.0",
"busboy": "^1.6.0", "busboy": "^1.6.0",
"concat-stream": "^2.0.0",
"type-is": "^1.6.18" "type-is": "^1.6.18"
}, },
"engines": { "engines": {
@ -1246,25 +1269,18 @@
} }
}, },
"node_modules/negotiator": { "node_modules/negotiator": {
"version": "1.1.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
"integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",
"license": "MIT", "license": "MIT",
"dependencies": {
"content-type": "^2.1.0"
},
"engines": { "engines": {
"node": ">=18" "node": ">= 0.6"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
} }
}, },
"node_modules/object-inspect": { "node_modules/object-inspect": {
"version": "1.14.0", "version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
"integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==", "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 0.4" "node": ">= 0.4"
@ -1274,19 +1290,15 @@
} }
}, },
"node_modules/on-finished": { "node_modules/on-finished": {
"version": "2.4.2", "version": "2.4.1",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
"integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"ee-first": "1.1.1" "ee-first": "1.1.1"
}, },
"engines": { "engines": {
"node": ">= 0.8" "node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
} }
}, },
"node_modules/once": { "node_modules/once": {
@ -1350,9 +1362,9 @@
} }
}, },
"node_modules/proxy-addr": { "node_modules/proxy-addr": {
"version": "2.0.8", "version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
"integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"forwarded": "0.2.0", "forwarded": "0.2.0",
@ -1360,16 +1372,12 @@
}, },
"engines": { "engines": {
"node": ">= 0.10" "node": ">= 0.10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
} }
}, },
"node_modules/qs": { "node_modules/qs": {
"version": "6.17.1", "version": "6.15.3",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
"integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"dependencies": { "dependencies": {
"es-define-property": "^1.0.1", "es-define-property": "^1.0.1",
@ -1383,16 +1391,12 @@
} }
}, },
"node_modules/range-parser": { "node_modules/range-parser": {
"version": "1.3.0", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 0.6" "node": ">= 0.6"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
} }
}, },
"node_modules/raw-body": { "node_modules/raw-body": {
@ -1410,10 +1414,24 @@
"node": ">= 0.10" "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": { "node_modules/router": {
"version": "2.3.0", "version": "2.2.0",
"resolved": "https://registry.npmjs.org/router/-/router-2.3.0.tgz", "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
"integrity": "sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w==", "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"debug": "^4.4.0", "debug": "^4.4.0",
@ -1424,12 +1442,28 @@
}, },
"engines": { "engines": {
"node": ">= 18" "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": { "node_modules/safer-buffer": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
@ -1437,35 +1471,31 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/send": { "node_modules/send": {
"version": "1.2.1", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz",
"integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"debug": "^4.4.3", "debug": "^4.3.5",
"encodeurl": "^2.0.0", "encodeurl": "^2.0.0",
"escape-html": "^1.0.3", "escape-html": "^1.0.3",
"etag": "^1.8.1", "etag": "^1.8.1",
"fresh": "^2.0.0", "fresh": "^2.0.0",
"http-errors": "^2.0.1", "http-errors": "^2.0.0",
"mime-types": "^3.0.2", "mime-types": "^3.0.1",
"ms": "^2.1.3", "ms": "^2.1.3",
"on-finished": "^2.4.1", "on-finished": "^2.4.1",
"range-parser": "^1.2.1", "range-parser": "^1.2.1",
"statuses": "^2.0.2" "statuses": "^2.0.1"
}, },
"engines": { "engines": {
"node": ">= 18" "node": ">= 18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
} }
}, },
"node_modules/serve-static": { "node_modules/serve-static": {
"version": "2.2.1", "version": "2.2.0",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz",
"integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"encodeurl": "^2.0.0", "encodeurl": "^2.0.0",
@ -1475,10 +1505,6 @@
}, },
"engines": { "engines": {
"node": ">= 18" "node": ">= 18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
} }
}, },
"node_modules/setprototypeof": { "node_modules/setprototypeof": {
@ -1576,6 +1602,15 @@
"node": ">=10.0.0" "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": { "node_modules/toidentifier": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
@ -1592,9 +1627,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/tslib": { "node_modules/tslib": {
"version": "2.9.1", "version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD" "license": "0BSD"
}, },
"node_modules/type-is": { "node_modules/type-is": {
@ -1615,19 +1650,38 @@
"url": "https://opencollective.com/express" "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": { "node_modules/undici": {
"version": "6.29.1", "version": "6.27.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz", "resolved": "https://registry.npmjs.org/undici/-/undici-6.27.0.tgz",
"integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==", "integrity": "sha512-YmfV3YnEDzXRC5lZ2jWtWWHKGUm1zIt8AhesR1tens+HTNv+YZlN/dp6G727LOvMJ8xjP9Be7Y2Sdr96LDm+pg==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=18.17" "node": ">=18.17"
} }
}, },
"node_modules/undici-types": { "node_modules/undici-types": {
"version": "8.9.0", "version": "7.16.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/unpipe": { "node_modules/unpipe": {
@ -1639,6 +1693,12 @@
"node": ">= 0.8" "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": { "node_modules/vary": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
@ -1655,9 +1715,9 @@
"license": "ISC" "license": "ISC"
}, },
"node_modules/ws": { "node_modules/ws": {
"version": "8.23.1", "version": "8.21.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.23.1.tgz", "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
"integrity": "sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA==", "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=10.0.0" "node": ">=10.0.0"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

View file

@ -1,43 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<defs>
<!-- Silhouette commune : sert au liseré blanc « autocollant » et au contour sombre. -->
<path id="ears" d="M9 34 L10 5 L28 22 Z M55 34 L54 5 L36 22 Z"/>
<path id="head" d="M32 20 C49 20 60 32 60 50 C60 56 58 58 54 58 L10 58 C6 58 4 56 4 50 C4 32 15 20 32 20 Z"/>
</defs>
<!-- liseré blanc -->
<g fill="#fff" stroke="#fff" stroke-width="7" stroke-linejoin="round">
<use href="#ears"/><use href="#head"/>
<rect x="0.5" y="33" width="10" height="17" rx="4.5"/><rect x="53.5" y="33" width="10" height="17" rx="4.5"/>
</g>
<!-- oreilles et tête -->
<g stroke="#2b2118" stroke-width="3.5" stroke-linejoin="round">
<use href="#ears" fill="#d9a35f"/>
</g>
<path d="M13 26 L13.5 12 L22 20 Z M51 26 L50.5 12 L42 20 Z" fill="#c8c3be"/>
<use href="#head" fill="#d9a35f"/>
<!-- rayures tigrées -->
<g stroke="#7a4a22" stroke-width="3" stroke-linecap="round">
<path d="M32 23 V29"/><path d="M25 24 L26.5 29.5"/><path d="M39 24 L37.5 29.5"/>
</g>
<!-- bas du visage clair -->
<path d="M14 58 C14 48 22 45 32 45 C42 45 50 48 50 58 Z" fill="#f4e6d0"/>
<!-- yeux : anneau sombre, iris ambré, pupille -->
<g stroke="#2b2118" stroke-width="2.5">
<circle cx="20.5" cy="40" r="8" fill="#fff"/>
<circle cx="43.5" cy="40" r="8" fill="#fff"/>
</g>
<circle cx="20.5" cy="40" r="5.2" fill="#2b2118"/>
<circle cx="43.5" cy="40" r="5.2" fill="#2b2118"/>
<circle cx="22.3" cy="38.2" r="1.7" fill="#fff"/>
<circle cx="45.3" cy="38.2" r="1.7" fill="#fff"/>
<!-- nez et bouche -->
<path d="M30 47.5 H34 L32 50 Z" fill="#2b2118" stroke="#2b2118" stroke-width="1.2" stroke-linejoin="round"/>
<path d="M28 52 Q30 54.5 32 51 Q34 54.5 36 52" fill="none" stroke="#2b2118" stroke-width="2" stroke-linecap="round"/>
<!-- contour de la tête, tracé après les détails pour ne jamais être recouvert -->
<use href="#head" fill="none" stroke="#2b2118" stroke-width="3.5" stroke-linejoin="round"/>
<!-- écouteurs -->
<g stroke="#2b2118" stroke-width="3" stroke-linejoin="round">
<rect x="0.5" y="33" width="10" height="17" rx="4.5" fill="#b259ff"/>
<rect x="53.5" y="33" width="10" height="17" rx="4.5" fill="#b259ff"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.2 KiB

BIN
public/img/palico-index.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

View file

@ -2,277 +2,36 @@
<html lang="fr"> <html lang="fr">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<title>Palico Jukebox</title> <title>Palico Bot</title>
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="Le jukebox du Palico Bot : la musique du salon vocal Discord." />
<meta name="theme-color" content="#0b0712" />
<link rel="icon" type="image/svg+xml" href="/img/favicon.svg" />
<link rel="icon" type="image/png" sizes="32x32" href="/img/favicon.png" />
<link rel="apple-touch-icon" href="/img/apple-touch-icon.png" />
<link rel="stylesheet" href="/style/styles.css" /> <link rel="stylesheet" href="/style/styles.css" />
</head> </head>
<body> <body>
<header class="topbar"> <div class="hero hero--home">
<div class="topbar__inner"> <div class="hero__visual">
<a class="brand" href="/"> <img src="/img/palico-index.png" alt="Palico Bot" />
<img src="/img/favicon.svg" alt="" width="32" height="32" />
<span>Palico Jukebox</span>
</a>
<span id="liveIndicator" class="live-indicator" data-live="false" hidden>Hors ligne</span>
<div id="loggedIn" class="topbar__account" hidden>
<span id="userName" class="topbar__user"></span>
<button id="logoutBtn" class="btn btn--ghost btn--small" type="button">Se déconnecter</button>
</div> </div>
</div>
</header>
<!-- Écran de connexion : affiché tant que la page n'a ni session Discord ni mot de passe. --> <div class="hero__content">
<section id="welcome" class="welcome" aria-labelledby="welcomeTitle" hidden> <p class="pill">Palico Bot</p>
<img class="welcome__visual" src="/img/palico-index.webp" alt="" width="640" height="960" /> <h1>Bienvenue sur la webapp</h1>
<div class="welcome__content"> <p>
<p class="eyebrow">Le jukebox du Palico Bot</p> Lance de la musique sur le Discord et pilote la playlist du salon vocal.
<h1 id="welcomeTitle">Un peu de son pour le Discord !</h1>
<p class="welcome__text">
Ajoute des morceaux et gère la playlist du salon vocal depuis cette page, ou avec
<code>/play</code> sur Discord. Tout est synchronisé en direct.
</p> </p>
<div id="discordLogin" hidden>
<a class="btn btn--discord" href="/auth/discord">
<svg viewBox="0 0 24 24" width="24" height="24" aria-hidden="true" focusable="false">
<path
fill="currentColor"
d="M18.59 5.89a15.6 15.6 0 0 0-3.92-1.23c-.17.3-.37.71-.5 1.04a14.5 14.5 0 0 0-4.34 0 10.6 10.6 0 0 0-.51-1.04c-1.38.24-2.69.66-3.92 1.23-2.48 3.74-3.15 7.39-2.82 10.98a15.7 15.7 0 0 0 4.81 2.46c.39-.53.73-1.1 1.03-1.69a10 10 0 0 1-1.62-.79l.4-.31c3.13 1.46 6.52 1.46 9.61 0l.4.31c-.51.31-1.06.57-1.62.79.3.59.64 1.16 1.03 1.69a15.6 15.6 0 0 0 4.81-2.46c.39-4.17-.67-7.78-2.82-10.98ZM8.84 14.67c-.94 0-1.71-.87-1.71-1.94s.75-1.94 1.71-1.94 1.72.87 1.71 1.94c0 1.06-.75 1.94-1.71 1.94Zm6.31 0c-.94 0-1.71-.87-1.71-1.94s.75-1.94 1.71-1.94 1.72.87 1.71 1.94c0 1.06-.75 1.94-1.71 1.94Z"
/>
</svg>
<span>Se connecter avec Discord</span>
</a>
<p class="hint">Réservé aux membres du serveur Discord.</p>
</div>
<details id="keyLogin" class="key-login" hidden>
<summary id="keyLoginSummary">Utiliser le mot de passe</summary>
<form id="settingsForm" class="key-login__form">
<div class="grid grid--two">
<div>
<label for="displayName">Nom affiché</label>
<input
type="text"
id="displayName"
name="displayName"
placeholder="Shinuwa"
autocomplete="nickname"
maxlength="80"
/>
</div>
<div>
<label for="apiKey">Mot de passe</label>
<input
type="password"
id="apiKey"
name="apiKey"
placeholder="Mot de passe"
autocomplete="current-password"
/>
</div>
</div>
<label class="form-checkbox u-mt-1">
<input type="checkbox" id="rememberKey" class="form-checkbox__input" />
<span>Se souvenir de moi sur cet appareil (sinon, oublié à la fermeture de l'onglet)</span>
</label>
<div class="form-actions">
<button type="submit" class="btn btn--primary">Entrer</button>
</div>
</form>
</details>
</div>
</section>
<main id="app" class="layout" hidden>
<!-- Lecteur et file : à droite sur grand écran, restent visibles en faisant défiler. -->
<aside class="layout__side">
<section id="playerSection" class="panel player" aria-labelledby="playerTitle">
<h2 id="playerTitle" class="panel__title">Lecture en cours</h2>
<div id="currentTrack" class="player__track player__track--empty"></div>
<div id="progress" class="seek" hidden>
<label for="seekInput" class="visually-hidden">Position dans le morceau</label>
<input type="range" id="seekInput" class="seek__input" min="0" max="0" step="1" value="0" />
<div class="seek__times">
<span id="progressElapsed">0:00</span>
<span id="progressTotal"></span>
</div> </div>
</div> </div>
<div class="player__controls"> <main>
<button class="icon-btn" type="button" data-player-action="shuffle" data-icon="shuffle" aria-label="Mélanger la file" title="Mélanger la file"></button> <section class="panel panel--glass">
<button class="icon-btn icon-btn--primary icon-btn--large js-play-pause" type="button" data-icon="play" aria-label="Lecture" title="Lecture"></button> <div class="feature-grid">
<button class="icon-btn" type="button" data-player-action="skip" data-icon="next" aria-label="Morceau suivant" title="Morceau suivant"></button> <a class="feature-grid__card" href="/jukebox/">
<button id="loopBtn" class="icon-btn" type="button" data-icon="loop" aria-pressed="false" aria-label="Boucle" title="Boucle : la file rejoue en continu"></button> <p class="pill">Le Jukebox du Palico Bot</p>
</div>
<button class="btn btn--danger btn--small player__stop" type="button" data-player-action="stop">
Stop et vider la file
</button>
</section>
<section id="queueSection" class="panel queue" aria-labelledby="queueTitle">
<div class="panel__header">
<h2 id="queueTitle" class="panel__title">File d'attente</h2>
<span id="queueSummary" class="badge" hidden></span>
</div>
<ul id="queueList" class="list list--stack"></ul>
<p id="queueEmpty" class="empty">Aucun morceau en attente. Ajoute-en depuis la bibliothèque.</p>
</section>
</aside>
<div class="layout__main">
<section class="panel" aria-labelledby="libraryTitle">
<div class="panel__header">
<div>
<h2 id="libraryTitle" class="panel__title">Bibliothèque</h2>
<p class="panel__subtitle">Les morceaux conservés, rangés en sections.</p>
</div>
<button id="goToUploadBtn" class="btn btn--primary btn--small" type="button" data-icon-before="plus">
Ajouter de la musique
</button>
</div>
<div class="library-tools">
<label for="librarySearch" class="visually-hidden">Rechercher dans la bibliothèque</label>
<input
type="search"
id="librarySearch"
placeholder="Rechercher un titre, une étiquette…"
autocomplete="off"
/>
<div class="toolbar">
<button id="enqueueAllBtn" class="btn btn--small" type="button">Tout ajouter</button>
<button id="enqueueAllShuffledBtn" class="btn btn--small" type="button">Tout ajouter, mélangé</button>
<button id="newSectionBtn" class="btn btn--ghost btn--small" type="button">Nouvelle section</button>
</div>
</div>
<div id="libraryTags" class="tag-list tag-list--filter" role="group" aria-label="Filtrer par étiquette" hidden></div>
<div id="libraryList" class="library"></div>
<p id="libraryEmpty" class="empty">Aucun fichier permanent enregistré.</p>
</section>
<section id="uploadSection" class="panel" aria-labelledby="uploadTitle">
<h2 id="uploadTitle" class="panel__title">Ajouter de la musique</h2>
<p class="panel__subtitle"> <p class="panel__subtitle">
Fichiers audio (150 Mo au plus chacun) ou lien direct vers un fichier. Les morceaux Upload, gère et pilote la playlist du salon vocal en direct.
temporaires sont supprimés après lecture.
</p> </p>
</a>
<div class="grid grid--two">
<label class="form-checkbox">
<input type="checkbox" id="permanentFile" class="form-checkbox__input" />
<span>Conserver dans la bibliothèque</span>
</label>
<label class="form-checkbox">
<input type="checkbox" id="enqueueFile" checked class="form-checkbox__input" />
<span>Ajouter directement à la file d'attente</span>
</label>
</div> </div>
<div id="uploadSectionField" class="u-mt-1" hidden>
<label for="uploadSectionSelect">Section de la bibliothèque</label>
<select id="uploadSectionSelect"></select>
</div>
<form id="uploadForm" class="u-mt-1">
<input type="file" id="musicFile" name="musicFile" class="visually-hidden" accept="audio/*,video/*" multiple />
<label class="dropzone" for="musicFile">
<span class="dropzone__icon" data-icon="upload"></span>
<span id="dropzoneText" class="dropzone__text">
<strong>Choisis des fichiers</strong> ou glisse-les ici
</span>
</label>
<label for="uploadNotes" class="u-mt-1">Titre (facultatif, pour un seul fichier)</label>
<input
type="text"
id="uploadNotes"
name="notes"
maxlength="200"
placeholder="Par défaut : les tags du fichier, sinon son nom"
/>
<div class="form-actions">
<button type="submit" class="btn btn--primary">Envoyer</button>
</div>
</form>
<ul id="uploadList" class="list upload-list" aria-live="polite"></ul>
<form id="urlForm" class="url-form">
<label for="musicUrl">Lien direct vers un fichier audio</label>
<div class="url-form__row">
<input
type="url"
id="musicUrl"
name="url"
required
maxlength="2000"
placeholder="https://exemple.com/morceau.mp3"
/>
<button type="submit" class="btn btn--primary">Ajouter</button>
</div>
<p class="hint">YouTube et Spotify ne sont pas pris en charge.</p>
</form>
</section> </section>
</div>
</main> </main>
<!-- Petits écrans : rappel du morceau en cours quand le lecteur est hors de vue. -->
<div id="miniPlayer" class="mini-player" hidden>
<button id="miniPlayerInfo" class="mini-player__info" type="button" aria-label="Aller au lecteur">
<span id="miniPlayerCover"></span>
<span id="miniPlayerTitle" class="mini-player__title"></span>
</button>
<button class="icon-btn icon-btn--primary js-play-pause" type="button" data-icon="play" aria-label="Lecture"></button>
<button class="icon-btn" type="button" data-player-action="skip" data-icon="next" aria-label="Morceau suivant"></button>
<div class="mini-player__progress"><div id="miniProgressBar"></div></div>
</div>
<div id="status" class="toast" role="status" aria-live="polite" hidden></div>
<dialog id="editDialog" class="dialog" aria-labelledby="editDialogTitle">
<form id="editForm">
<h2 id="editDialogTitle">Modifier le morceau</h2>
<div class="cover-editor">
<div id="editCoverPreview" class="cover cover--large cover--empty" aria-hidden="true"></div>
<div class="cover-editor__fields">
<label id="editCoverLabel" for="editCoverInput">Pochette</label>
<input type="file" id="editCoverInput" accept="image/png,image/jpeg,image/webp,image/gif" />
<p class="hint">PNG, JPEG, WebP ou GIF, 10 Mo au plus. Réduite à 512 px.</p>
<button id="editCoverRemoveBtn" class="btn btn--ghost btn--small u-mt-1" type="button">
Retirer la pochette
</button>
</div>
</div>
<label id="editNameLabel" for="editNameInput" class="u-mt-1">Titre</label>
<input type="text" id="editNameInput" maxlength="200" required />
<div id="editSectionField">
<label for="editSectionSelect" class="u-mt-1">Section</label>
<select id="editSectionSelect"></select>
</div>
<div id="editTagsField">
<label for="editTagsInput" class="u-mt-1">Étiquettes</label>
<input type="text" id="editTagsInput" maxlength="500" autocomplete="off" placeholder="épique, calme, combat…" />
<p class="hint">Sépare-les par des virgules. Clique sur une étiquette existante pour l'ajouter.</p>
<div id="editTagSuggestions" class="tag-list"></div>
</div>
<div class="form-actions toolbar">
<button id="editCancelBtn" class="btn btn--ghost" type="button">Annuler</button>
<button id="editSaveBtn" class="btn btn--primary" type="submit">Enregistrer</button>
</div>
</form>
</dialog>
<script type="module" src="/scripts/jukebox.js"></script>
</body> </body>
</html> </html>

182
public/jukebox.html Normal file
View file

@ -0,0 +1,182 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<title>Palico Jukebox</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/style/styles.css" />
</head>
<body>
<div class="hero">
<div class="hero__visual">
<img src="/img/palico-jukebox.png" alt="Palico Jukebox" />
</div>
<div class="hero__content">
<p class="pill">Le Jukebox du Palico Bot</p>
<h1>Un peu de son pour le Discord !</h1>
<p>
Tu veux chill avec les autres sur un petit fond musical ?<br />
T'inquietes pas, je peux m'occuper de ca !<br />
<br />
Uploade des fichiers et gère la playlist depuis cette interface web.
Tout est synchronisé avec le salon vocal.
</p>
<div class="hero__actions">
<button id="heroUploadBtn" class="btn">Ajouter une musique</button>
<button id="heroQueueBtn" class="btn btn--ghost">Voir la file</button>
</div>
</div>
<div class="hero__auth">
<div class="panel panel--glass">
<h2>Authentification</h2>
<p class="panel__subtitle">
La clé reste dans cet onglet jusqu'à sa fermeture.
</p>
<form id="settingsForm">
<div class="grid grid--two">
<div>
<label for="displayName">Nom affiché</label>
<input
type="text"
id="displayName"
name="displayName"
placeholder="Shinuwa"
autocomplete="nickname"
/>
</div>
<div>
<label for="apiKey">Mot de passe</label>
<input
type="password"
id="apiKey"
name="apiKey"
placeholder="Mot de passe"
autocomplete="current-password"
/>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn">Sauvegarder</button>
</div>
</form>
</div>
</div>
</div>
<main>
<div id="status" class="status status--info" hidden></div>
<section class="panel panel--glass">
<div class="panel__header">
<div>
<h2>Lecture en cours</h2>
<p class="panel__subtitle">
État en temps réel du player Discord. Contrôle instantané.
</p>
</div>
<button id="refreshBtn" class="btn btn--ghost btn--small">Rafraîchir</button>
</div>
<div id="currentTrack" class="player-current player-current--empty">
En attente de lecture...
</div>
<div class="control-group">
<button class="btn" data-player-action="play">Play</button>
<button
id="pauseResumeBtn"
class="btn btn--secondary"
data-player-action="pause"
>
Pause
</button>
<button class="btn" data-player-action="skip">Suivante</button>
<button class="btn btn--danger" data-player-action="stop">
Stop & vider la file
</button>
</div>
</section>
<section class="panel panel--glass" id="queueSection">
<div class="panel__header">
<div>
<h2>File d'attente</h2>
<p class="panel__subtitle">
Réorganise les morceaux, supprime-les ou ajoute ceux de la
bibliothèque.
</p>
</div>
</div>
<ul id="queueList" class="list list--stack"></ul>
<p id="queueEmpty" class="text--muted">Aucun morceau en attente.</p>
</section>
<section class="panel panel--glass">
<h2>Bibliothèque permanente</h2>
<p class="panel__subtitle">
Les fichiers conservés sont listés ici. Ajoute-les à la file ou
supprime-les.
</p>
<ul id="libraryList" class="list list--stack"></ul>
<p id="libraryEmpty" class="text--muted">
Aucun fichier permanent enregistré.
</p>
</section>
<section class="panel panel--glass" id="uploadSection">
<div class="panel__header">
<div>
<h2>Uploader une musique</h2>
<p class="panel__subtitle">
Formats audio supportés par FFmpeg. Les fichiers temporaires sont
supprimés automatiquement après lecture.
</p>
</div>
<div class="badge">Drag & drop supporté</div>
</div>
<form id="uploadForm">
<label for="musicFile">Fichier audio</label>
<input
type="file"
id="musicFile"
name="musicFile"
accept="audio/*"
required
/>
<label for="uploadNotes" class="u-mt-1">Commentaire (optionnel)</label>
<input
type="text"
id="uploadNotes"
name="notes"
placeholder="Titre personnalisé"
/>
<div class="grid grid--two u-mt-1">
<label class="form-checkbox">
<input type="checkbox" id="permanentFile" class="form-checkbox__input" />
<span>Conserver dans la bibliothèque après lecture</span>
</label>
<label class="form-checkbox">
<input type="checkbox" id="enqueueFile" checked class="form-checkbox__input" />
<span>Ajouter directement à la file d'attente</span>
</label>
</div>
<button type="submit" class="btn u-mt-1">Uploader</button>
</form>
</section>
</main>
<div class="hero__actions hero__actions--centered">
<button
type="button"
class="btn btn--ghost btn--small"
id="backHomeBtn"
>
Retour à l'accueil
</button>
</div>
<script type="module" src="/scripts/jukebox.js"></script>
</body>
</html>

View file

@ -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 API_KEY_STORAGE_KEY = "palico-api-key";
const DISPLAY_NAME_STORAGE_KEY = "palico-display-name"; 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() { export function getStoredApiKey() {
return ( return sessionStorage.getItem(API_KEY_STORAGE_KEY) || "";
storageGet(sessionStorage, API_KEY_STORAGE_KEY) ||
storageGet(localStorage, API_KEY_STORAGE_KEY) ||
""
);
} }
export function isApiKeyRemembered() { export function setStoredApiKey(value) {
return Boolean(storageGet(localStorage, API_KEY_STORAGE_KEY)); sessionStorage.setItem(API_KEY_STORAGE_KEY, value || "");
}
// remember : garde la clé sur l'appareil (localStorage) au lieu de l'onglet (sessionStorage).
export function setStoredApiKey(value, { remember = false } = {}) {
storageSet(remember ? localStorage : sessionStorage, API_KEY_STORAGE_KEY, value);
storageSet(remember ? sessionStorage : localStorage, API_KEY_STORAGE_KEY, "");
} }
export function getStoredDisplayName() { export function getStoredDisplayName() {
return storageGet(localStorage, DISPLAY_NAME_STORAGE_KEY) || ""; return localStorage.getItem(DISPLAY_NAME_STORAGE_KEY) || "";
} }
export function setStoredDisplayName(value) { export function setStoredDisplayName(value) {
storageSet(localStorage, DISPLAY_NAME_STORAGE_KEY, value); localStorage.setItem(DISPLAY_NAME_STORAGE_KEY, value || "");
} }
export function createStatusManager(statusElement) { export function createStatusManager(statusElement) {
@ -64,8 +23,7 @@ export function createStatusManager(statusElement) {
function setStatus(message, type = "info", autoHide = true) { function setStatus(message, type = "info", autoHide = true) {
if (!statusElement) return; if (!statusElement) return;
statusElement.textContent = message; statusElement.textContent = message;
// Le type (info, success, error) passe par un attribut : la classe reste celle de la page. statusElement.className = `status status--${type}`;
statusElement.dataset.type = type;
statusElement.hidden = false; statusElement.hidden = false;
if (autoHide) { if (autoHide) {
@ -103,37 +61,13 @@ export function formatBytes(bytes = 0) {
return `${(bytes / Math.pow(1024, index)).toFixed(1)} ${units[index]}`; 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) { export function formatDate(value) {
return formatWith(DATE_FORMAT, value); if (!value) return "?";
} try {
return new Date(value).toLocaleString();
export function formatDay(value) { } catch (_) {
return formatWith(DAY_FORMAT, value); return value;
}
} }
export function createApiClient({ getApiKey, basePath = "" } = {}) { export function createApiClient({ getApiKey, basePath = "" } = {}) {

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -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 fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { spawnSync } from "node:child_process"; import { spawnSync } from "node:child_process";

View file

@ -1,8 +1,3 @@
/**
* @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 { SlashCommandBuilder, subtext } from "discord.js";
import { setTimeout } from "node:timers/promises"; import { setTimeout } from "node:timers/promises";
import { getRandomInt } from "../../features/utilities.js"; import { getRandomInt } from "../../features/utilities.js";
@ -14,7 +9,7 @@ const command = {
.addIntegerOption((option) => .addIntegerOption((option) =>
option option
.setName("number") .setName("number")
.setDescription("Nombre de dés à lancer") .setDescription("Nombre de dés a lancer")
.setMinValue(1) .setMinValue(1)
.setMaxValue(20) .setMaxValue(20)
.setRequired(true) .setRequired(true)
@ -30,36 +25,39 @@ const command = {
async execute(interaction) { async execute(interaction) {
const number = interaction.options.getInteger("number"); const number = interaction.options.getInteger("number");
const faces = interaction.options.getInteger("faces"); const faces = interaction.options.getInteger("faces");
let sum = 0; var sum = 0;
let message = "Alors du coup... 🥁\n"; var message = "Alors du coup... 🥁\n";
let tails = 0; var tails = 0;
let heads = 0; var heads = 0;
if (faces === 2) { if (faces === 2) {
message += subtext("Pile = 1 et Face = 2\n"); message = message + subtext(`Pile = 1 et Face = 2\n`);
} }
await interaction.reply(message); await interaction.reply(message);
for (let i = 0; i < number; i++) { for (let i = 0; i < number; i++) {
await setTimeout(1_500); await setTimeout(1_500);
const random = getRandomInt(faces) + 1; let random = getRandomInt(faces) + 1;
if (random === 1) tails++; random === 1 ? tails++ : heads++;
else heads++; sum = sum + random;
sum += random;
message += `[ ${random} ] ${i === number - 1 ? "\n" : " "}`; message = message + `[ ${random} ] ${i === number - 1 ? "\n" : " "}`;
await interaction.editReply(message); await interaction.editReply(message);
} }
if (number > 1 && faces > 2) { if (number > 1 && faces > 2) {
await setTimeout(1_000); await setTimeout(1_000);
message += subtext(`Soit au total : ${sum}`); message = message + subtext(`Soit au total : ${sum}`);
} }
if (number > 1 && faces === 2) { if (number > 1 && faces === 2) {
await setTimeout(1_000); await setTimeout(1_000);
message += subtext(`Soit au total : ${sum}, ou bien ${tails} piles et ${heads} faces\n`); message =
message +
subtext(
`Soit au total : ${sum}, ou bien ${tails} piles et ${heads} faces \n`
);
} }
await interaction.editReply(message); await interaction.editReply(message);

View file

@ -1,29 +1,13 @@
/** import { SlashCommandBuilder } from "discord.js";
* @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 = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("maketeam") .setName("maketeam")
.setDescription("Crée des équipes au hasard") .setDescription("Crée des equipes au hasard")
.addIntegerOption((option) => .addIntegerOption((option) =>
option option
.setName("number") .setName("number")
.setDescription("Nombre d'équipes") .setDescription("Nombre d'équipe")
.setMinValue(1) .setMinValue(1)
.setMaxValue(20) .setMaxValue(20)
.setRequired(true) .setRequired(true)
@ -31,7 +15,7 @@ const command = {
.addStringOption((option) => .addStringOption((option) =>
option option
.setName("players") .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) .setMinLength(1)
.setMaxLength(1000) .setMaxLength(1000)
.setRequired(true) .setRequired(true)
@ -39,27 +23,41 @@ const command = {
async execute(interaction) { async execute(interaction) {
const teamNumber = interaction.options.getInteger("number"); const teamNumber = interaction.options.getInteger("number");
const players = interaction.options.getString("players"); const players = interaction.options.getString("players");
const playersArray = parsePlayers(players); const playersArray = players.trim().split(/\s+/);
if (playersArray.length === 0 || teamNumber > playersArray.length) { if (teamNumber > playersArray.length) {
await interaction.reply({ await interaction.reply({
content: "Le nombre d'équipes ne peut pas dépasser le nombre de joueurs.", content: "Le nombre d'équipes ne peut pas dépasser le nombre de joueurs.",
flags: MessageFlags.Ephemeral, ephemeral: true,
}); });
return; return;
} }
const teams = Array.from({ length: teamNumber }, () => []); const teams = Array.from({ length: teamNumber }, () => []);
shuffle(playersArray).forEach((player, index) => { 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; const teamIndex = index % teamNumber;
teams[teamIndex].push(player); teams[teamIndex].push(player);
}); });
const teamList = teams let message = "";
.map((team, index) => `${index + 1}. ${team.join(", ")}`) let teamList = "";
.join("\n");
await interaction.reply(`Yop ! Voici les équipes proposées :\n\n${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, parsePlayers }; export { command };

View file

@ -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 };

View file

@ -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 };

View file

@ -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 };

View file

@ -1,15 +1,10 @@
/** import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
* @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 { requirePermission } from "../../features/permissions.js"; import { requirePermission } from "../../features/permissions.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("deletemsgs") .setName("deletemsgs")
.setDescription("Supprime les 100 derniers messages, sauf ceux épinglés") .setDescription("Supprime tous les messages, sauf ceux épinglés")
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages), .setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages),
async execute(interaction) { async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.ManageMessages))) { if (!(await requirePermission(interaction, PermissionFlagsBits.ManageMessages))) {
@ -20,28 +15,17 @@ const command = {
if (!textChannel?.isTextBased() || !textChannel.messages) { if (!textChannel?.isTextBased() || !textChannel.messages) {
await interaction.reply({ await interaction.reply({
content: "Cette commande doit être utilisée dans un salon textuel.", content: "Cette commande doit être utilisée dans un salon textuel.",
flags: MessageFlags.Ephemeral, ephemeral: true,
}); });
return; return;
} }
await interaction.deferReply({ flags: MessageFlags.Ephemeral }); await interaction.deferReply({ ephemeral: true });
const fetched = await textChannel.messages.fetch({ limit: 100 }); const fetched = await textChannel.messages.fetch({ limit: 100 });
const notPinned = fetched.filter((message) => !message.pinned); 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 deleted = await textChannel.bulkDelete(notPinned, true);
const tooOld = notPinned.size - deleted.size;
await interaction.editReply( await interaction.editReply(`Et voilà, ${deleted.size} message(s) supprimé(s) ! 🐱`);
[
`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")
);
}, },
}; };

View file

@ -1,9 +1,4 @@
/** import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
* @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 { config } from "../../config.js"; import { config } from "../../config.js";
import { requirePermission } from "../../features/permissions.js"; import { requirePermission } from "../../features/permissions.js";
import { import {
@ -45,7 +40,7 @@ const command = {
if (!interaction.guild || !channel?.isTextBased()) { if (!interaction.guild || !channel?.isTextBased()) {
await interaction.reply({ await interaction.reply({
content: "Cette commande doit être utilisée dans un salon textuel du serveur.", content: "Cette commande doit être utilisée dans un salon textuel du serveur.",
flags: MessageFlags.Ephemeral, ephemeral: true,
}); });
return; return;
} }
@ -54,12 +49,12 @@ const command = {
if (!input) { if (!input) {
await interaction.reply({ await interaction.reply({
content: "Aucun lien : passe l'option `lien` ou définis `INVITE_LINK`.", content: "Aucun lien : passe l'option `lien` ou définis `INVITE_LINK`.",
flags: MessageFlags.Ephemeral, ephemeral: true,
}); });
return; return;
} }
await interaction.deferReply({ flags: MessageFlags.Ephemeral }); await interaction.deferReply({ ephemeral: true });
if (!botCanPost(interaction)) { if (!botCanPost(interaction)) {
await interaction.editReply(NO_ACCESS_MESSAGE); await interaction.editReply(NO_ACCESS_MESSAGE);

View file

@ -1,36 +1,28 @@
/** import { SlashCommandBuilder } from "discord.js";
* @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 = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("listcommand") .setName("listcommand")
.setDescription("Affiche la liste des commandes disponibles"), .setDescription("Affiche la liste des commandes disponibles"),
async execute(interaction) { async execute(interaction) {
await interaction.reply({ let message = `Voila la liste des commandes que tu peux utiliser :
content: buildCommandList(interaction.client.commands.values()), __Categorie Utililaires__ :
flags: MessageFlags.Ephemeral, \`/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 { buildCommandList, command }; export { command };

View file

@ -1,15 +1,11 @@
/** import { SlashCommandBuilder } from "discord.js";
* @file Commande /ping : vérifie que le bot répond.
*/
import { MessageFlags, SlashCommandBuilder } from "discord.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("ping") .setName("ping")
.setDescription("Répond avec Pong"), .setDescription("Reponds avec Pong"),
async execute(interaction) { async execute(interaction) {
await interaction.reply({ content: "Euh... Pong ! 🐱", flags: MessageFlags.Ephemeral }); await interaction.reply({ content: "Euh... Pong ! 🐱", ephemeral: true });
}, },
}; };

View file

@ -1,23 +1,16 @@
/**
* @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 { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.js"; import { changeVoiceStatus } from "../../features/utilities.js";
import { requirePermission } from "../../features/permissions.js"; import { requirePermission } from "../../features/permissions.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("deafall") .setName("deafall")
.setDescription("Rend tout le monde sourd dans le salon vocal") .setDescription("Deaf tout le monde dans le lounge")
.setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers), .setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers),
async execute(interaction) { async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.DeafenMembers))) return; 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 changeVoiceStatus(interaction.client, "deaf", "all");
await interaction.deferReply(); await interaction.reply("On n'entends plus rien ! 🐱");
await changeVoiceStatus(commandVoiceChannel(interaction), "deaf");
await interaction.editReply("On n'entends plus rien ! 🐱");
}, },
}; };

View file

@ -1,23 +1,16 @@
/**
* @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 { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.js"; import { changeVoiceStatus } from "../../features/utilities.js";
import { requirePermission } from "../../features/permissions.js"; import { requirePermission } from "../../features/permissions.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("muteall") .setName("muteall")
.setDescription("Rend tout le monde muet dans le salon vocal") .setDescription("Mute tout le monde dans le lounge")
.setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers), .setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers),
async execute(interaction) { async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.MuteMembers))) return; 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 changeVoiceStatus(interaction.client, "mute", "all");
await interaction.deferReply(); await interaction.reply("Voila, tout le monde est mioute ! 🐱");
await changeVoiceStatus(commandVoiceChannel(interaction), "mute");
await interaction.editReply("Voila, tout le monde est mioute ! 🐱");
}, },
}; };

View file

@ -1,23 +1,16 @@
/**
* @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 { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.js"; import { changeVoiceStatus } from "../../features/utilities.js";
import { requirePermission } from "../../features/permissions.js"; import { requirePermission } from "../../features/permissions.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("undeafall") .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), .setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers),
async execute(interaction) { async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.DeafenMembers))) return; 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 changeVoiceStatus(interaction.client, "undeaf", "all");
await interaction.deferReply(); await interaction.reply("Voila, les oreilles sont réparées ! 🐱");
await changeVoiceStatus(commandVoiceChannel(interaction), "undeaf");
await interaction.editReply("Voila, les oreilles sont réparées ! 🐱");
}, },
}; };

View file

@ -1,23 +1,16 @@
/**
* @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 { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.js"; import { changeVoiceStatus } from "../../features/utilities.js";
import { requirePermission } from "../../features/permissions.js"; import { requirePermission } from "../../features/permissions.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("unmuteall") .setName("unmuteall")
.setDescription("Rend la parole à tout le monde dans le salon vocal") .setDescription("Unmute tout le monde dans le lounge")
.setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers), .setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers),
async execute(interaction) { async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.MuteMembers))) return; 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 changeVoiceStatus(interaction.client, "unmute", "all");
await interaction.deferReply(); await interaction.reply("Et.... unmioute ! 🐱");
await changeVoiceStatus(commandVoiceChannel(interaction), "unmute");
await interaction.editReply("Et.... unmioute ! 🐱");
}, },
}; };

View file

@ -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 = [ const requiredVariables = [
"NODE_ENV",
"DISCORD_GUILD_ID", "DISCORD_GUILD_ID",
"OWNER_USER_ID", "SHINUWA_USER_ID",
"WEB_SERVER_PORT", "WEB_SERVER_PORT",
"WEB_API_KEY", "WEB_API_KEY",
"DISCORD_APPLICATION_ID", "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. // INVITE_LINK : lien publié par /invitation quand la commande ne reçoit pas de lien.
const inviteLink = process.env.INVITE_LINK?.trim() || null; 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) { if (notificationsApiKey && notificationsApiKey === process.env.WEB_API_KEY) {
throw new Error("NOTIFICATIONS_API_KEY doit être différente de WEB_API_KEY"); throw new Error("NOTIFICATIONS_API_KEY doit être différente de WEB_API_KEY");
} }
const config = Object.freeze({ const config = Object.freeze({
environnement: process.env.NODE_ENV,
discordGuildId: process.env.DISCORD_GUILD_ID, discordGuildId: process.env.DISCORD_GUILD_ID,
ownerUserId: process.env.OWNER_USER_ID, shinuwaUserId: process.env.SHINUWA_USER_ID,
webServerPort, webServerPort,
webApiKey: process.env.WEB_API_KEY, webApiKey: process.env.WEB_API_KEY,
webTrustedProxies, webTrustedProxies,
notificationsApiKey, notificationsApiKey,
inviteLink, inviteLink,
discordOAuthEnabled,
discordClientSecret,
webPublicUrl,
sessionSecret,
applicationId: process.env.DISCORD_APPLICATION_ID, applicationId: process.env.DISCORD_APPLICATION_ID,
token: process.env.DISCORD_TOKEN, token: process.env.DISCORD_TOKEN,
voiceChannelId: process.env.VOICE_CHANNEL_ID, voiceChannelId: process.env.VOICE_CHANNEL_ID,

View file

@ -1,28 +1,11 @@
/** import { Events } from "discord.js";
* @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 = { const event = {
name: Events.InteractionCreate, name: Events.InteractionCreate,
async execute(interaction) { 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; if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName); const command = interaction.client.commands.get(interaction.commandName)?.command;
if (!command) { if (!command) {
console.error( console.error(
@ -34,17 +17,17 @@ const event = {
try { try {
await command.execute(interaction); await command.execute(interaction);
} catch (error) { } catch (error) {
console.error(`Command ${interaction.commandName} failed`, error); console.error(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) { if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: ERROR_MESSAGE, flags: MessageFlags.Ephemeral }); await interaction.followUp({
content: "There was an error while executing this command!",
ephemeral: true,
});
} else { } else {
await interaction.reply({ content: ERROR_MESSAGE, flags: MessageFlags.Ephemeral }); await interaction.reply({
} content: "There was an error while executing this command!",
} catch (replyError) { ephemeral: true,
console.error("Unable to report the command error to the user", replyError); });
} }
} }
}, },

View file

@ -1,8 +1,3 @@
/**
* @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 { Events } from "discord.js";
import { showGameServers } from "../features/showGameServers.js"; import { showGameServers } from "../features/showGameServers.js";
@ -14,11 +9,11 @@ const event = {
`[${new Date().toLocaleString()}] Logged in as ${client.user.tag}` `[${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. try {
client.musicQueue?.evaluateAloneStatus();
// Les erreurs sont journalisées et retentées par showGameServers lui-même.
await showGameServers(client); await showGameServers(client);
} catch (error) {
console.error("Unable to initialize game server status", error);
}
}, },
}; };

View file

@ -1,20 +1,8 @@
/** // Envoie un message privé Discord à la demande d'une application de confiance (Sokko TCG : alertes d'expédition).
* @file Envoie un message privé Discord à la demande d'une application de confiance (Sokko TCG : // Le texte est envoyé tel quel, sans aucune mention active.
* 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";
const USER_ID_PATTERN = /^\d{17,20}$/; const USER_ID_PATTERN = /^\d{17,20}$/;
const MAX_CONTENT_LENGTH = 2000; 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). // Codes de l'API Discord : utilisateur inconnu, messages privés impossibles (aucun serveur commun ou messages fermés).
const UNKNOWN_USER = 10013; const UNKNOWN_USER = 10013;
const CANNOT_SEND = 50007; const CANNOT_SEND = 50007;
@ -27,82 +15,16 @@ class DirectMessageError extends Error {
} }
} }
const invalid = (message) => new DirectMessageError(400, "INVALID_EMBED", message); async function sendDirectMessage(client, { userId, content } = {}) {
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 } = {}) {
if (typeof userId !== "string" || !USER_ID_PATTERN.test(userId)) { if (typeof userId !== "string" || !USER_ID_PATTERN.test(userId)) {
throw new DirectMessageError(400, "INVALID_USER", "Identifiant Discord invalide"); throw new DirectMessageError(400, "INVALID_USER", "Identifiant Discord invalide");
} }
if (typeof content !== "string" || !content.trim() || content.length > MAX_CONTENT_LENGTH) { 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`); 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 { try {
const user = await client.users.fetch(userId); const user = await client.users.fetch(userId);
await user.send(message); await user.send({ content, allowedMentions: { parse: [] } });
} catch (error) { } catch (error) {
if (error?.code === UNKNOWN_USER) { if (error?.code === UNKNOWN_USER) {
throw new DirectMessageError(404, "UNKNOWN_USER", "Utilisateur Discord introuvable"); throw new DirectMessageError(404, "UNKNOWN_USER", "Utilisateur Discord introuvable");

View file

@ -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 };

View file

@ -1,13 +1,5 @@
/** // Message d'invitation : le serveur n'autorise pas ses membres à créer des invitations ; un seul
* @file Vérifie le lien et rédige le message d'invitation : les membres ne peuvent pas créer // lien à adhésion temporaire est partagé par le bot. Pour garder quelqu'un, on lui donne un rôle.
* 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
*/
import { codeBlock, DiscordjsErrorCodes } from "discord.js"; import { codeBlock, DiscordjsErrorCodes } from "discord.js";
const INVITE_URL_PATTERN = const INVITE_URL_PATTERN =

View file

@ -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) { async function requirePermission(interaction, permission) {
if (interaction.memberPermissions?.has(permission)) { if (interaction.memberPermissions?.has(permission)) {
return true; return true;
@ -16,7 +5,7 @@ async function requirePermission(interaction, permission) {
await interaction.reply({ await interaction.reply({
content: "Tu n'as pas la permission d'utiliser cette commande.", content: "Tu n'as pas la permission d'utiliser cette commande.",
flags: MessageFlags.Ephemeral, ephemeral: true,
}); });
return false; return false;
} }

View file

@ -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 { config } from "../config.js";
import { getJSONData } from "./utilities.js"; import { getJSONData } from "./utilities.js";
const PROBE_TIMEOUT = 3_000; var currentStatus = [];
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, async function checkServersStatus(client) {
// 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 data = getJSONData("src/static/gameservers-list.json");
const servers = await Promise.all( const newStatus = data.servers.map((server) => server.active);
data.servers.map(async (server) => ({
...server,
active: await serverStatus(server, probe),
}))
);
return { ...data, servers };
}
function buildMessage(data) { if (JSON.stringify(newStatus) === JSON.stringify(currentStatus)) {
const servers = data.servers return;
.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;
} }
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); const channel = client.channels.cache.get(config.textChannelId);
if (!channel?.isTextBased()) { if (!channel?.isTextBased()) {
throw new Error("Salon textuel configuré introuvable"); throw new Error("Salon textuel configuré introuvable");
} }
const message = await channel.messages.fetch(config.gameServersMessageId); const message = await channel.messages.fetch(config.gameServersMessageId);
await message.edit(content); await message.edit(newMessage);
publishedMessage = content;
console.log( console.log(
`[${new Date().toLocaleString()}] showGameServers: Game servers message updated` `[${new Date().toLocaleString()}] showGameServers: Game servers message updated`
); );
return true;
} }
// Un échec (salon ou message introuvable, liste illisible) est journalisé et retenté au async function showGameServers(client) {
// rafraîchissement suivant, y compris au démarrage. const data = getJSONData("src/static/gameservers-list.json");
function showGameServers(client) { currentStatus = data.servers.map((server) => server.active);
const refresh = () =>
refreshMessage(client).catch((error) => await updateMessage(client, data);
const interval = setInterval(() => {
checkServersStatus(client).catch((error) =>
console.error("Unable to update game server status", error) console.error("Unable to update game server status", error)
); );
setInterval(refresh, REFRESH_INTERVAL).unref(); }, 120000);
return refresh(); interval.unref();
} }
export { buildMessage, probeTcp, serverStatus, showGameServers }; export { showGameServers };

View file

@ -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 };

View file

@ -1,48 +1,51 @@
/** import fs from "fs";
* @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 { config } from "../config.js"; import { config } from "../config.js";
const VOICE_ACTIONS = { async function changeVoiceStatus(client, status, members) {
mute: (member) => member.voice.setMute(true), const changeStatus = async (type, value, selectedMembers) => {
unmute: (member) => member.voice.setMute(false), const operations = [];
deaf: (member) => member.voice.setDeaf(true), switch (type) {
undeaf: (member) => member.voice.setDeaf(false), 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);
};
// Salon vocal où se trouve la personne qui lance la commande, sinon celui de la configuration. const voiceChannel = client.channels.cache.get(config.voiceChannelId);
function commandVoiceChannel(interaction) { if (!voiceChannel?.isVoiceBased()) {
const channel =
interaction.member?.voice?.channel ??
interaction.client.channels.cache.get(config.voiceChannelId);
if (!channel?.isVoiceBased()) {
throw new Error("Salon vocal configuré introuvable"); 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. if (members === "all") {
async function changeVoiceStatus(channel, action) { members = connectedMembers;
const apply = VOICE_ACTIONS[action];
if (!apply) {
throw new Error(`Statut vocal inconnu : ${action}`);
} }
const members = channel.members.filter((member) => !member.user.bot); switch (status) {
// Un membre qui quitte le salon pendant l'opération ne doit pas faire échouer les autres. case "mute":
const results = await Promise.allSettled(members.map(apply)); await changeStatus("mute", true, members);
const failures = results.filter((result) => result.status === "rejected"); break;
if (failures.length > 0) { case "unmute":
console.error( await changeStatus("mute", false, members);
`changeVoiceStatus: ${failures.length} member(s) could not be updated`, break;
failures[0].reason case "deaf":
); await changeStatus("deaf", true, members);
break;
case "undeaf":
await changeStatus("deaf", false, members);
break;
default:
throw new Error(`Statut vocal inconnu : ${status}`);
} }
} }
@ -57,19 +60,8 @@ function getRandomInt(max) {
return Math.floor(Math.random() * 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;
}
export { export {
changeVoiceStatus, changeVoiceStatus,
commandVoiceChannel,
getJSONData, getJSONData,
getRandomInt, getRandomInt,
shuffle,
}; };

View file

@ -1,51 +0,0 @@
/**
* @file Charge les commandes slash de src/commands/<catégorie>/*.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/<catégorie>/*.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 };

View file

@ -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 };

View file

@ -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 };

View file

@ -1,144 +1,35 @@
/** import { execFile } from "node:child_process";
* @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 { promisify } from "node:util"; import { promisify } from "node:util";
const execFileAsync = promisify(execFile); const execFileAsync = promisify(execFile);
// Normalisation du volume (EBU R128, mode dynamique en une passe) : tous les morceaux sortent async function validateAudioFile(filePath) {
// au même niveau, quel que soit le fichier d'origine.
const LOUDNORM_FILTER = "loudnorm=I=-16:TP=-1.5:LRA=11";
const MAX_STDERR_LENGTH = 4_000;
function cleanTag(value) {
if (typeof value !== "string") return null;
const cleaned = value.replace(/[\u0000-\u001f]/g, "").trim().slice(0, 200);
return cleaned || null;
}
// Les noms des tags varient selon le format (« title » en ID3, « TITLE » en Vorbis) : on les
// met en minuscules. Les tags Ogg sont portés par le flux, les autres par le conteneur.
function lowerCaseTags(...tagSets) {
const tags = {};
for (const set of tagSets) {
for (const [key, value] of Object.entries(set || {})) {
tags[key.toLowerCase()] ??= value;
}
}
return tags;
}
// Vérifie qu'un fichier contient une piste audio et lit sa durée (secondes) et ses tags.
async function probeAudioFile(filePath) {
let parsed;
try { try {
const { stdout } = await execFileAsync( const { stdout } = await execFileAsync(
"ffprobe", "ffprobe",
[ [
"-v", "-v",
"error", "error",
"-select_streams",
"a:0",
"-show_entries", "-show_entries",
"format=duration:format_tags:stream=codec_type:stream_tags", "stream=codec_type",
"-of", "-of",
"json", "default=noprint_wrappers=1:nokey=1",
filePath, filePath,
], ],
{ timeout: 15_000, maxBuffer: 1024 * 1024 } { 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) { } 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) { export { validateAudioFile };
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 };

View file

@ -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 };

View file

@ -1,32 +1,8 @@
/** import fs from "fs";
* @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 { EventEmitter } from "events"; import { EventEmitter } from "events";
import { randomUUID } from "node:crypto";
import { import {
AudioPlayerStatus, AudioPlayerStatus,
NoSubscriberBehavior, NoSubscriberBehavior,
StreamType,
VoiceConnectionStatus, VoiceConnectionStatus,
createAudioPlayer, createAudioPlayer,
createAudioResource, createAudioResource,
@ -35,8 +11,6 @@ import {
} from "@discordjs/voice"; } from "@discordjs/voice";
import { Events } from "discord.js"; import { Events } from "discord.js";
import { config } from "../config.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 { serializeTrack, serializeTracks } from "../web/serializers.js";
import { import {
deleteTrackFile, deleteTrackFile,
@ -44,41 +18,17 @@ import {
} from "../web/storage/storageManager.js"; } from "../web/storage/storageManager.js";
const AUTO_DISCONNECT_DELAY = 5 * 60 * 1000; const AUTO_DISCONNECT_DELAY = 5 * 60 * 1000;
// Délais entre les nouvelles tentatives quand le salon vocal est injoignable. Au-delà, la
// file attend une action (ajout d'un morceau, bouton Play).
const CONNECT_RETRY_DELAYS = [5_000, 15_000, 30_000, 60_000, 60_000];
// 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 { class MusicQueue extends EventEmitter {
// persistence : { load() → état | null, save(état) } pour garder la file d'un démarrage à constructor(client) {
// l'autre (voir queuePersistence.js). Sans elle, la file est perdue à l'arrêt.
constructor(
client,
{ retryDelays = CONNECT_RETRY_DELAYS, persistence = null } = {}
) {
super(); super();
this.setMaxListeners(50); // une écoute par page web ouverte (flux d'événements)
this.client = client; this.client = client;
this.queue = []; this.queue = [];
this.currentTrack = null; 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.connection = null;
this.playbackStatus = AudioPlayerStatus.Idle; this.playbackStatus = AudioPlayerStatus.Idle;
this.idleDisconnectTimeout = null; this.idleDisconnectTimeout = null;
this.aloneDisconnectTimeout = null; this.aloneDisconnectTimeout = null;
this.connectRetryTimeout = null;
this.connectFailures = 0;
this.retryDelays = retryDelays;
this.suspendedForAlone = false; this.suspendedForAlone = false;
this.playNextPromise = null; this.playNextPromise = null;
this.shuttingDown = false; this.shuttingDown = false;
@ -98,38 +48,23 @@ class MusicQueue extends EventEmitter {
this.client.on(Events.VoiceStateUpdate, this.voiceStateListener); this.client.on(Events.VoiceStateUpdate, this.voiceStateListener);
this.audioPlayer.on(AudioPlayerStatus.Idle, () => { this.audioPlayer.on(AudioPlayerStatus.Idle, () => {
const finished = this.currentTrack; if (this.currentTrack) {
handleTrackCompletion(this.currentTrack);
}
this.currentTrack = null; 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);
}
}
this.discardCurrent = false;
if (!this.shuttingDown) { if (!this.shuttingDown) {
void this.playNext(); 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) => { this.audioPlayer.on("error", (error) => {
console.error("Audio player encountered an error", error); console.error("Audio player encountered an error", error);
this.discardCurrent = true; handleTrackCompletion(this.currentTrack);
}); this.currentTrack = null;
if (!this.shuttingDown) {
this.on("queueUpdate", () => this.scheduleSave()); void this.playNext();
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.audioPlayer.on("stateChange", (oldState, newState) => {
this.playbackStatus = newState.status; this.playbackStatus = newState.status;
@ -142,37 +77,9 @@ class MusicQueue extends EventEmitter {
current: serializeTrack(this.currentTrack), current: serializeTrack(this.currentTrack),
upcoming: serializeTracks(this.queue), upcoming: serializeTracks(this.queue),
status: this.playbackStatus, 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() { async ensureConnection() {
if (this.connection) { if (this.connection) {
if ( if (
@ -215,8 +122,6 @@ class MusicQueue extends EventEmitter {
this.connection = connection; this.connection = connection;
connection.subscribe(this.audioPlayer); connection.subscribe(this.audioPlayer);
connection.on(VoiceConnectionStatus.Disconnected, async () => { 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 { try {
await Promise.race([ await Promise.race([
entersState(connection, VoiceConnectionStatus.Signalling, 5_000), entersState(connection, VoiceConnectionStatus.Signalling, 5_000),
@ -224,7 +129,7 @@ class MusicQueue extends EventEmitter {
]); ]);
} catch { } catch {
if (this.connection === connection) { 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) { enqueue(track) {
this.queue.push(track); this.queue.push(track);
// Ajouter un morceau est une demande de lecture explicite : elle lève la suspension
// (bot parti faute d'auditeurs) et relance les tentatives de connexion.
this.suspendedForAlone = false;
this.connectFailures = 0;
this.cancelIdleDisconnect(); this.cancelIdleDisconnect();
this.emit("queueUpdate", this.snapshot()); this.emit("queueUpdate", this.snapshot());
if (!this.currentTrack) { if (!this.currentTrack) {
@ -273,9 +174,7 @@ class MusicQueue extends EventEmitter {
} }
async runPlayNext() { async runPlayNext() {
this.cancelConnectRetry(); if (this.suspendedForAlone) {
if (this.shuttingDown || this.suspendedForAlone) {
return; return;
} }
@ -290,27 +189,26 @@ class MusicQueue extends EventEmitter {
try { try {
await this.ensureConnection(); await this.ensureConnection();
this.connectFailures = 0;
} catch (error) { } catch (error) {
console.error("Unable to connect to the configured voice channel", error); console.error("Unable to connect to the configured voice channel", error);
this.currentTrack = null; this.currentTrack = null;
this.scheduleConnectRetry();
return; return;
} }
if (this.shuttingDown || this.suspendedForAlone) { if (
this.shuttingDown ||
this.suspendedForAlone ||
this.queue[0]?.id !== nextTrack.id
) {
return; return;
} }
// La file a pu changer pendant la connexion (morceau retiré ou déplacé) : on repart
// de la nouvelle tête de file au lieu d'abandonner.
if (this.queue[0]?.id !== nextTrack.id) {
return this.runPlayNext();
}
try { try {
this.queue.shift(); this.queue.shift();
const resource = this.createResource(nextTrack); const stream = fs.createReadStream(nextTrack.path);
const resource = createAudioResource(stream, {
inlineVolume: true,
});
this.currentTrack = { this.currentTrack = {
...nextTrack, ...nextTrack,
@ -327,48 +225,12 @@ class MusicQueue extends EventEmitter {
} }
} }
createResource(track) { async remove(trackId) {
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) {
const index = this.queue.findIndex((track) => track.id === trackId); const index = this.queue.findIndex((track) => track.id === trackId);
if (index === -1) { if (index === -1) {
if (this.currentTrack && this.currentTrack.id === trackId) { if (this.currentTrack && this.currentTrack.id === trackId) {
// skip() repasse le player en Idle tout de suite, ce qui efface currentTrack.
const removed = this.currentTrack;
this.discardCurrent = true;
this.skip(); this.skip();
return removed; return this.currentTrack;
} }
return null; return null;
} }
@ -400,55 +262,12 @@ class MusicQueue extends EventEmitter {
} }
stop() { stop() {
this.cancelConnectRetry();
this.queue.forEach((track) => deleteTrackFile(track)); this.queue.forEach((track) => deleteTrackFile(track));
this.queue = []; this.queue = [];
this.discardCurrent = Boolean(this.currentTrack);
this.audioPlayer.stop(true); this.audioPlayer.stop(true);
this.emit("queueUpdate", this.snapshot()); 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() { pause() {
this.audioPlayer.pause(true); this.audioPlayer.pause(true);
} }
@ -459,7 +278,6 @@ class MusicQueue extends EventEmitter {
start() { start() {
this.suspendedForAlone = false; this.suspendedForAlone = false;
this.connectFailures = 0;
this.cancelIdleDisconnect(); this.cancelIdleDisconnect();
if (!this.currentTrack) { if (!this.currentTrack) {
return this.playNext(); return this.playNext();
@ -486,7 +304,6 @@ class MusicQueue extends EventEmitter {
this.currentTrack && this.currentTrack &&
this.currentTrack.libraryTrackId === libraryTrackId this.currentTrack.libraryTrackId === libraryTrackId
) { ) {
this.discardCurrent = true;
this.skip(); this.skip();
} }
@ -497,10 +314,7 @@ class MusicQueue extends EventEmitter {
return removed; return removed;
} }
// requeue : remet le morceau interrompu en tête de file, pour qu'il reprenne où il en était destroyConnection(reason, { suspend = false } = {}) {
// (à `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 } = {}) {
if (!this.connection && this.playbackStatus === AudioPlayerStatus.Idle) { if (!this.connection && this.playbackStatus === AudioPlayerStatus.Idle) {
return; return;
} }
@ -513,12 +327,7 @@ class MusicQueue extends EventEmitter {
this.cancelAloneDisconnect(); this.cancelAloneDisconnect();
const interruptedTrack = this.currentTrack; const interruptedTrack = this.currentTrack;
const interruptedAt = position ?? this.currentPosition();
this.currentTrack = null; this.currentTrack = null;
const requeued = Boolean(requeue && interruptedTrack);
if (requeued) {
this.queue.unshift(this.resumableTrack(interruptedTrack, interruptedAt));
}
if (this.connection) { if (this.connection) {
try { try {
@ -535,9 +344,7 @@ class MusicQueue extends EventEmitter {
console.error("Failed to stop audio player", error); console.error("Failed to stop audio player", error);
} }
if (!requeued) {
handleTrackCompletion(interruptedTrack); handleTrackCompletion(interruptedTrack);
}
this.emit("queueUpdate", this.snapshot()); this.emit("queueUpdate", this.snapshot());
console.log( console.log(
`[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})` `[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})`
@ -577,7 +384,7 @@ class MusicQueue extends EventEmitter {
this.aloneDisconnectTimeout = setTimeout(() => { this.aloneDisconnectTimeout = setTimeout(() => {
this.aloneDisconnectTimeout = null; this.aloneDisconnectTimeout = null;
if (this.connection && this.isBotAlone()) { if (this.connection && this.isBotAlone()) {
this.destroyConnection("alone timeout", { suspend: true, requeue: true }); this.destroyConnection("alone timeout", { suspend: true });
} }
}, AUTO_DISCONNECT_DELAY); }, AUTO_DISCONNECT_DELAY);
} }
@ -592,11 +399,6 @@ class MusicQueue extends EventEmitter {
evaluateAloneStatus() { evaluateAloneStatus() {
if (!this.connection) { if (!this.connection) {
this.cancelAloneDisconnect(); this.cancelAloneDisconnect();
// Parti faute d'auditeurs : revenir dès que quelqu'un rejoint le salon.
if (this.suspendedForAlone && this.queue.length > 0 && this.hasListeners()) {
this.suspendedForAlone = false;
void this.playNext();
}
return; return;
} }
@ -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() { isBotAlone() {
const channel = this.client.channels.cache.get(config.voiceChannelId); const channel = this.client.channels.cache.get(config.voiceChannelId);
const clientId = this.client.user?.id; if (!channel) {
if (!channel || !clientId || !channel.members.has(clientId)) {
return false; 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() { shutdown() {
this.shuttingDown = true; this.shuttingDown = true;
this.cancelIdleDisconnect(); this.cancelIdleDisconnect();
this.cancelAloneDisconnect(); this.cancelAloneDisconnect();
this.cancelConnectRetry();
clearTimeout(this.saveTimeout);
clearInterval(this.positionSaveInterval);
this.client.off(Events.VoiceStateUpdate, this.voiceStateListener); 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.forEach((track) => deleteTrackFile(track));
this.queue = []; this.queue = [];
this.destroyConnection("shutdown"); 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 }; export { MusicQueue };

View file

@ -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 };

View file

@ -1,23 +1,10 @@
{ {
"servers": [ "servers": [
{ {
"game": "Nom du jeu (état saisi à la main)", "game": "Nom du jeu",
"address": "games.example.com:25565", "address": "games.example.com:25565",
"port": 25565, "port": 25565,
"active": false "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
} }
] ]
} }

View file

@ -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,
};

View file

@ -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 { config } from "../../config.js";
import { createHash, timingSafeEqual } from "node:crypto"; import { createHash, timingSafeEqual } from "node:crypto";
@ -39,25 +30,6 @@ function createBearerAuth(getExpectedKey) {
const authMiddleware = createBearerAuth(() => config.webApiKey); 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"]); const LOOPBACK_ADDRESSES = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
function isLoopbackAddress(address) { 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" }); 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 };

View file

@ -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 };

View file

@ -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 };

View file

@ -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 };

View file

@ -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 { Router } from "express";
import { setTrackCover } from "../storage/libraryCovers.js";
import { findSection, getSections } from "../storage/librarySections.js";
import { import {
createQueueTrackFromLibrary, createQueueTrackFromLibrary,
deletePermanentTrack, deletePermanentTrack,
findPermanentTrack, findPermanentTrack,
getPermanentLibrary, getPermanentLibrary,
updatePermanentTracks,
} from "../storage/storageManager.js"; } from "../storage/storageManager.js";
import { serializeSections, serializeTrack, serializeTracks } from "../serializers.js"; import { 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);
}
function libraryRouter({ queue }) { function libraryRouter({ queue }) {
const router = Router(); const router = Router();
router.use("/sections", librarySectionsRouter({ queue }));
router.get("/", (req, res) => { router.get("/", (req, res) => {
res.json({ res.json({ tracks: serializeTracks(getPermanentLibrary()) });
tracks: serializeTracks(getPermanentLibrary()),
sections: serializeSections(getSections()),
});
}); });
router.delete("/:libraryId", (req, res) => { router.delete("/:libraryId", (req, res) => {
@ -50,87 +22,9 @@ function libraryRouter({ queue }) {
} }
queue.removeByLibraryId(track.id); queue.removeByLibraryId(track.id);
queue.emit("libraryUpdate");
res.json({ removed: serializeTrack(track) }); 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) => { router.post("/:libraryId/enqueue", (req, res) => {
const baseTrack = findPermanentTrack(req.params.libraryId); const baseTrack = findPermanentTrack(req.params.libraryId);
if (!baseTrack) { if (!baseTrack) {
@ -139,7 +33,7 @@ function libraryRouter({ queue }) {
const queueTrack = createQueueTrackFromLibrary( const queueTrack = createQueueTrackFromLibrary(
baseTrack, baseTrack,
req.user?.name ?? req.body?.requestedBy req.body?.requestedBy
); );
queue.enqueue(queueTrack); queue.enqueue(queueTrack);
res.status(201).json({ track: serializeTrack(queueTrack) }); res.status(201).json({ track: serializeTrack(queueTrack) });

View file

@ -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 };

View file

@ -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 { Router } from "express";
import { DirectMessageError, sendDirectMessage } from "../../features/directMessages.js"; import { DirectMessageError, sendDirectMessage } from "../../features/directMessages.js";
@ -17,7 +9,7 @@ function logDirectMessage(userId, status) {
console.log(`[${new Date().toLocaleString()}] DM ${target} → ${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 }) { function notificationsRouter({ client }) {
const router = Router(); const router = Router();

View file

@ -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"; import { Router } from "express";
function playerRouter({ queue }) { function playerRouter({ queue }) {
@ -28,35 +23,11 @@ function playerRouter({ queue }) {
res.json(queue.snapshot()); 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) => { router.post("/stop", (req, res) => {
queue.stop(); queue.stop();
res.json(queue.snapshot()); 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; return router;
} }

View file

@ -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 { Router } from "express";
import { createQueueTrackFromLibrary, findPermanentTrack } from "../storage/storageManager.js"; import { createQueueTrackFromLibrary, findPermanentTrack } from "../storage/storageManager.js";
import { serializeTrack } from "../serializers.js"; import { serializeTrack } from "../serializers.js";
@ -27,13 +22,13 @@ function queueRouter({ queue }) {
return res.status(404).json({ error: "Fichier permanent introuvable" }); 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); queue.enqueue(track);
res.status(201).json({ track: serializeTrack(track) }); res.status(201).json({ track: serializeTrack(track) });
}); });
router.delete("/:trackId", (req, res) => { router.delete("/:trackId", async (req, res) => {
const removed = queue.remove(req.params.trackId); const removed = await queue.remove(req.params.trackId);
if (!removed) { if (!removed) {
return res.status(404).json({ error: "Piste introuvable" }); return res.status(404).json({ error: "Piste introuvable" });
} }

View file

@ -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 { Router } from "express";
import multer from "multer"; import multer from "multer";
import { downloadAudio } from "../../media/downloadAudio.js"; import { validateAudioFile } from "../../media/validateAudioFile.js";
import { ingestAudioFile } from "../../music/ingest.js";
import { serializeTrack } from "../serializers.js"; import { serializeTrack } from "../serializers.js";
import { findSection } from "../storage/librarySections.js"; import {
import { TEMP_DIR } from "../storage/storageManager.js"; 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({ const upload = multer({
dest: TEMP_DIR, dest: TEMP_DIR,
limits: { limits: {
fileSize: 150 * 1024 * 1024, fileSize: 150 * 1024 * 1024,
fields: 5, fields: 4,
fieldSize: 512, fieldSize: 512,
}, },
fileFilter: (_req, file, callback) => { fileFilter: (_req, file, callback) => {
@ -32,54 +35,55 @@ const upload = multer({
callback(error); callback(error);
return; return;
} }
callback(null, true); callback(null, ALLOWED_AUDIO_TYPES.has(file.mimetype));
}, },
}); });
function uploadsRouter({ queue }) { function uploadsRouter({ queue }) {
const router = Router(); 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) => { router.post("/", upload.single("file"), async (req, res, next) => {
if (!req.file) { if (!req.file) {
return res.status(400).json({ error: "Aucun fichier reçu" }); return res.status(400).json({ error: "Aucun fichier reçu" });
} }
try { const permanent = req.body?.permanent === "true";
const track = await ingestAudioFile(req.file, options(req), { queue }); const enqueue = req.body?.enqueue !== "false";
return res.status(201).json({ const uploader = String(req.body?.uploader || "web-ui")
track: serializeTrack(track), .replace(/[\u0000-\u001f]/g, "")
enqueued: options(req).enqueue, .trim()
}); .slice(0, 80);
} catch (error) { const title = String(req.body?.notes || req.file.originalname)
return next(error); .replace(/[\u0000-\u001f]/g, "")
} .trim()
}); .slice(0, 200);
// Ajout depuis un lien direct vers un fichier audio : le serveur le télécharge lui-même.
router.post("/url", async (req, res, next) => {
const url = req.body?.url;
if (typeof url !== "string" || url.length > 2_000) {
return res.status(400).json({ error: "Lien manquant" });
}
try { try {
const file = await downloadAudio(url, { destinationDir: TEMP_DIR }); if (!permanent && !enqueue) {
const track = await ingestAudioFile(file, options(req), { queue }); 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({ return res.status(201).json({
track: serializeTrack(track), track: serializeTrack(track),
enqueued: options(req).enqueue, enqueued: enqueue,
}); });
} catch (error) { } catch (error) {
discardUploadedFile(req.file);
return next(error); return next(error);
} }
}); });

View file

@ -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) { function serializeTrack(track) {
if (!track) { if (!track) {
return null; return null;
} }
const { path: _path, storedName: _storedName, ...publicTrack } = track; const { path: _path, storedName: _storedName, ...publicTrack } = track;
return withCoverUrl(publicTrack); return publicTrack;
} }
function serializeTracks(tracks = []) { function serializeTracks(tracks = []) {
return tracks.map(serializeTrack); return tracks.map(serializeTrack);
} }
function serializeSection(section) { export { serializeTrack, serializeTracks };
return section ? withCoverUrl(section) : null;
}
function serializeSections(sections = []) {
return sections.map(serializeSection);
}
export { serializeSection, serializeSections, serializeTrack, serializeTracks };

View file

@ -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 <img> 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 express from "express";
import helmet from "helmet"; import helmet from "helmet";
import { rateLimit } from "express-rate-limit"; import { rateLimit } from "express-rate-limit";
@ -25,21 +5,17 @@ import multer from "multer";
import path from "path"; import path from "path";
import { config } from "../config.js"; import { config } from "../config.js";
import { import {
authMiddleware,
createBearerAuth, createBearerAuth,
createJukeboxAuth,
localOnly, localOnly,
} from "./middlewares/auth.js"; } from "./middlewares/auth.js";
import { authRouter, sessionMiddleware } from "./routes/auth.js";
import { eventsRouter } from "./routes/events.js";
import { libraryRouter } from "./routes/library.js"; import { libraryRouter } from "./routes/library.js";
import { notificationsRouter } from "./routes/notifications.js"; import { notificationsRouter } from "./routes/notifications.js";
import { playerRouter } from "./routes/player.js"; import { playerRouter } from "./routes/player.js";
import { queueRouter } from "./routes/queue.js"; import { queueRouter } from "./routes/queue.js";
import { uploadsRouter } from "./routes/uploads.js"; import { uploadsRouter } from "./routes/uploads.js";
import { backfillLibraryMetadata } from "./storage/libraryMetadata.js";
import { import {
cleanupTemporaryFiles, cleanupTemporaryFiles,
COVERS_DIR,
ensureStorageLayout, ensureStorageLayout,
} from "./storage/storageManager.js"; } 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( function createApp(
dependencies, dependencies,
{ { notificationsApiKey = config.notificationsApiKey } = {}
notificationsApiKey = config.notificationsApiKey,
oauth = {
enabled: config.discordOAuthEnabled,
clientId: config.applicationId,
clientSecret: config.discordClientSecret,
publicUrl: config.webPublicUrl,
sessionSecret: config.sessionSecret,
},
findMember = guildMemberFinder(dependencies.client),
fetchImpl = fetch,
} = {}
) { ) {
const app = express(); const app = express();
app.disable("x-powered-by"); app.disable("x-powered-by");
app.set("trust proxy", config.webTrustedProxies); app.set("trust proxy", config.webTrustedProxies);
app.use(helmet()); app.use(helmet());
app.use(express.json({ limit: "32kb" })); 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) => { app.get("/healthz", (_req, res) => {
res.json({ status: "ok", discord: discordReady() ? "ready" : "not-ready" }); res.json({ status: "ok" });
});
app.get("/readyz", (_req, res) => {
const ready = discordReady();
res.status(ready ? 200 : 503).json({ status: ready ? "ready" : "not-ready" });
}); });
// Messages privés pour les applications de confiance : connexions locales uniquement, // Messages privés pour les applications de confiance : connexions locales uniquement,
@ -126,38 +66,23 @@ function createApp(
notificationsRouter(dependencies) 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(); const apiRouter = express.Router();
apiRouter.use(apiRateLimit({ windowMs: 60_000, limit: 120 })); apiRouter.use(apiRateLimit({ windowMs: 60_000, limit: 120 }));
apiRouter.use(authFailureLimit()); apiRouter.use(authFailureLimit());
apiRouter.use(createJukeboxAuth({ publicUrl: oauth.publicUrl })); apiRouter.use(authMiddleware);
apiRouter.use( apiRouter.use(
"/uploads", "/uploads",
// Envoi de plusieurs fichiers d'un coup : une requête par fichier. apiRateLimit({ windowMs: 15 * 60_000, limit: 10 }),
apiRateLimit({ windowMs: 15 * 60_000, limit: 40 }),
uploadsRouter(dependencies) uploadsRouter(dependencies)
); );
apiRouter.use("/queue", queueRouter(dependencies)); apiRouter.use("/queue", queueRouter(dependencies));
apiRouter.use("/library", libraryRouter(dependencies)); apiRouter.use("/library", libraryRouter(dependencies));
apiRouter.use("/player", playerRouter(dependencies)); apiRouter.use("/player", playerRouter(dependencies));
apiRouter.use("/events", eventsRouter(dependencies));
app.use("/api", apiRouter); app.use("/api", apiRouter);
app.use( app.get(["/jukebox", "/jukebox/"], (_req, res) =>
"/covers", res.sendFile(path.join(PUBLIC_DIR, "jukebox.html"))
express.static(COVERS_DIR, { immutable: true, maxAge: "365d", index: false, redirect: false })
); );
// 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(express.static(PUBLIC_DIR));
app.use((error, _req, res, _next) => { app.use((error, _req, res, _next) => {
@ -176,38 +101,18 @@ function createApp(
return app; return app;
} }
const TEMP_CLEANUP_INTERVAL = 60 * 60_000;
function startWebServer(dependencies) { function startWebServer(dependencies) {
ensureStorageLayout(); ensureStorageLayout();
const cleanup = () => cleanupTemporaryFiles();
cleanupTemporaryFiles(undefined, { keep: dependencies.queue.inUsePaths() });
cleanup();
// Les fichiers temporaires de plus de 24 h sont supprimés pendant que le bot tourne,
// pas seulement à son démarrage.
const cleanupInterval = setInterval(cleanup, TEMP_CLEANUP_INTERVAL);
cleanupInterval.unref();
backfillLibraryMetadata()
.then((updated) => {
if (updated.length > 0) {
console.log(
`[${new Date().toLocaleString()}] Library metadata completed for ${updated.length} track(s)`
);
dependencies.queue.emit("libraryUpdate");
}
})
.catch((error) => console.error("Unable to complete library metadata", error));
const app = createApp(dependencies); const app = createApp(dependencies);
const port = config.webServerPort; const port = Number(process.env.PORT || config.webServerPort || 3000);
const server = app.listen(port, () => { const server = app.listen(port, () => {
console.log( console.log(
`[${new Date().toLocaleString()}] Web control server listening on port ${port}` `[${new Date().toLocaleString()}] Web control server listening on port ${port}`
); );
}); });
server.on("close", () => clearInterval(cleanupInterval));
return { app, server }; return { app, server };
} }

View file

@ -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 };

View file

@ -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 };

View file

@ -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,
};

View file

@ -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 fs from "fs";
import path from "path"; import path from "path";
import { randomUUID } from "node:crypto"; 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 PERMANENT_DIR = path.join(STORAGE_ROOT, "permanent");
const TEMP_DIR = path.join(STORAGE_ROOT, "temp"); const TEMP_DIR = path.join(STORAGE_ROOT, "temp");
const RUNTIME_DIR = path.join(STORAGE_ROOT, "runtime"); 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 LIBRARY_FILE = path.join(RUNTIME_DIR, "library.json");
const LEGACY_LIBRARY_FILE = path.join(STORAGE_ROOT, "library.json"); const LEGACY_LIBRARY_FILE = path.join(STORAGE_ROOT, "library.json");
const TEMP_FILE_MAX_AGE = 24 * 60 * 60 * 1000; const TEMP_FILE_MAX_AGE = 24 * 60 * 60 * 1000;
const MAX_LIBRARY_SIZE = 2 * 1024 * 1024 * 1024; const MAX_LIBRARY_SIZE = 2 * 1024 * 1024 * 1024;
function ensureStorageLayout() { function ensureStorageLayout() {
for (const directory of [PERMANENT_DIR, TEMP_DIR, RUNTIME_DIR, COVERS_DIR]) { if (!fs.existsSync(STORAGE_ROOT)) {
fs.mkdirSync(directory, { recursive: true }); 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)) { if (!fs.existsSync(LIBRARY_FILE)) {
@ -98,14 +87,7 @@ function writeLibrary(entries) {
function registerUploadedFile( function registerUploadedFile(
file, file,
{ { permanent, uploader = "unknown", title = file.originalname }
permanent,
uploader = "unknown",
title = file.originalname,
duration = null,
artist = null,
sectionId = null,
}
) { ) {
ensureStorageLayout(); ensureStorageLayout();
const createdAt = new Date().toISOString(); const createdAt = new Date().toISOString();
@ -120,16 +102,14 @@ function registerUploadedFile(
0 0
); );
if (librarySize + file.size > MAX_LIBRARY_SIZE) { if (librarySize + file.size > MAX_LIBRARY_SIZE) {
const error = new Error("La bibliothèque permanente a atteint sa limite de 2 Go"); throw new Error("La bibliothèque permanente a atteint sa limite de 2 Go");
error.status = 413;
throw error;
} }
const rawExtension = path.extname(file.originalname).toLowerCase(); const rawExtension = path.extname(file.originalname).toLowerCase();
const extension = /^\.[a-z0-9]{1,10}$/.test(rawExtension) const extension = /^\.[a-z0-9]{1,10}$/.test(rawExtension)
? rawExtension ? rawExtension
: ""; : "";
storedName = `${randomUUID()}${extension}`; storedName = `${randomUUID()}${extension.toLowerCase()}`;
finalPath = path.join(PERMANENT_DIR, storedName); finalPath = path.join(PERMANENT_DIR, storedName);
fs.renameSync(file.path, finalPath); fs.renameSync(file.path, finalPath);
permanentEntry = { permanentEntry = {
@ -140,9 +120,6 @@ function registerUploadedFile(
path: finalPath, path: finalPath,
size: file.size, size: file.size,
mimetype: file.mimetype, mimetype: file.mimetype,
duration,
artist,
sectionId,
uploader, uploader,
createdAt, createdAt,
}; };
@ -158,8 +135,6 @@ function registerUploadedFile(
storedName, storedName,
size: file.size, size: file.size,
mimetype: file.mimetype, mimetype: file.mimetype,
duration,
artist,
permanent, permanent,
uploader, uploader,
libraryTrackId: permanentEntry ? permanentEntry.id : null, libraryTrackId: permanentEntry ? permanentEntry.id : null,
@ -189,21 +164,14 @@ function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") {
storedName: libraryTrack.storedName, storedName: libraryTrack.storedName,
size: libraryTrack.size, size: libraryTrack.size,
mimetype: libraryTrack.mimetype, mimetype: libraryTrack.mimetype,
duration: libraryTrack.duration ?? null,
artist: libraryTrack.artist ?? null,
permanent: true, permanent: true,
uploader: uploader: requestedBy,
String(requestedBy ?? "")
.replace(/[\u0000-\u001f]/g, "")
.trim()
.slice(0, 80) || "library",
libraryTrackId: libraryTrack.id, libraryTrackId: libraryTrack.id,
createdAt: new Date().toISOString(), 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) {
function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE, { keep = new Set() } = {}) {
ensureStorageLayout(); ensureStorageLayout();
const cutoff = Date.now() - maxAge; 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); const filePath = path.join(TEMP_DIR, entry.name);
if (keep.has(filePath)) {
continue;
}
try { try {
if (fs.statSync(filePath).mtimeMs < cutoff) { if (fs.statSync(filePath).mtimeMs < cutoff) {
fs.unlinkSync(filePath); fs.unlinkSync(filePath);
@ -232,7 +197,7 @@ function deleteFileSafe(filePath) {
} }
try { try {
fs.rmSync(filePath, { force: true }); fs.existsSync(filePath) && fs.unlinkSync(filePath);
} catch (error) { } catch (error) {
console.error(`Failed to delete file ${filePath}`, error); console.error(`Failed to delete file ${filePath}`, error);
} }
@ -242,31 +207,6 @@ function discardUploadedFile(file) {
deleteFileSafe(file?.path); 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) { function deletePermanentTrack(id) {
const library = getPermanentLibrary(); const library = getPermanentLibrary();
const index = library.findIndex((entry) => entry.id === id); const index = library.findIndex((entry) => entry.id === id);
@ -277,7 +217,6 @@ function deletePermanentTrack(id) {
const [removed] = library.splice(index, 1); const [removed] = library.splice(index, 1);
writeLibrary(library); writeLibrary(library);
deleteFileSafe(removed.path); deleteFileSafe(removed.path);
deleteCoverFile(removed.cover);
return removed; return removed;
} }
@ -299,9 +238,7 @@ function deleteTrackFile(track) {
} }
export { export {
COVERS_DIR,
PERMANENT_DIR, PERMANENT_DIR,
RUNTIME_DIR,
TEMP_DIR, TEMP_DIR,
ensureStorageLayout, ensureStorageLayout,
registerUploadedFile, registerUploadedFile,
@ -310,9 +247,7 @@ export {
createQueueTrackFromLibrary, createQueueTrackFromLibrary,
cleanupTemporaryFiles, cleanupTemporaryFiles,
discardUploadedFile, discardUploadedFile,
deleteCoverFile,
deletePermanentTrack, deletePermanentTrack,
updatePermanentTracks,
handleTrackCompletion, handleTrackCompletion,
deleteTrackFile, deleteTrackFile,
}; };

View file

@ -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");
});

View file

@ -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 test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";

View file

@ -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 test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import fs from "node:fs";
const ENVIRONMENT = { const ENVIRONMENT = {
NODE_ENV: "test", NODE_ENV: "test",
@ -20,37 +16,30 @@ const ENVIRONMENT = {
}; };
Object.assign(process.env, 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 () => { test("all Discord commands expose valid command data", async () => {
const commands = await loadCommands(); const modules = await loadCommands();
assert.equal(commands.length, 13); assert.equal(modules.length, 10);
for (const command of commands) { for (const module of modules) {
assert.doesNotThrow(() => command.data.toJSON()); assert.doesNotThrow(() => module.command.data.toJSON());
assert.equal(typeof command.execute, "function"); assert.equal(typeof module.command.execute, "function");
assert.ok(command.category, command.data.name);
} }
}); });
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 () => { test("administrative commands require Discord permissions", async () => {
const commands = await loadCommands(); const modules = await loadCommands();
const protectedCommands = new Set([ const protectedCommands = new Set([
"deletemsgs", "deletemsgs",
"invitation", "invitation",
@ -60,61 +49,11 @@ test("administrative commands require Discord permissions", async () => {
"undeafall", "undeafall",
]); ]);
for (const command of commands) { for (const module of modules) {
const data = command.data.toJSON(); const data = module.command.data.toJSON();
if (protectedCommands.has(data.name)) { if (protectedCommands.has(data.name)) {
assert.notEqual(data.default_member_permissions, undefined, data.name); assert.notEqual(data.default_member_permissions, undefined, data.name);
assert.notEqual(data.default_member_permissions, null, 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]]);
});

View file

@ -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")));
});

View file

@ -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 test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { DirectMessageError, sendDirectMessage } from "../src/features/directMessages.js"; 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: { 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/); 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);
});

View file

@ -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));
}
});

View file

@ -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,
});
});

View file

@ -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 : "));
});

View file

@ -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>/);
});

View file

@ -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);
});

View file

@ -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 test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { DiscordjsErrorCodes } from "discord.js"; import { DiscordjsErrorCodes } from "discord.js";

View file

@ -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 test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";

View file

@ -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 }), []);
});

View file

@ -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);
});

View file

@ -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 test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { EventEmitter } from "node:events";
Object.assign(process.env, { Object.assign(process.env, {
NODE_ENV: "test", NODE_ENV: "test",
@ -50,275 +43,10 @@ test("queue snapshots do not expose filesystem paths", () => {
queue.currentTrack = { id: "current", path: "/private/current.mp3" }; queue.currentTrack = { id: "current", path: "/private/current.mp3" };
queue.queue = [{ id: "next", path: "/private/next.mp3" }]; queue.queue = [{ id: "next", path: "/private/next.mp3" }];
queue.playbackStatus = "playing"; queue.playbackStatus = "playing";
queue.loop = false;
assert.deepEqual(queue.snapshot(), { assert.deepEqual(queue.snapshot(), {
current: { id: "current" }, current: { id: "current" },
upcoming: [{ id: "next" }], upcoming: [{ id: "next" }],
status: "playing", 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();
});

View file

@ -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 test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { serializeTrack, serializeTracks } from "../src/web/serializers.js"; import { serializeTrack, serializeTracks } from "../src/web/serializers.js";

View file

@ -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 test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import fs from "node:fs"; 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 }); 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 });
}
});

View file

@ -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);
});

View file

@ -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 test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
@ -48,8 +42,6 @@ function fakeClient() {
const fakeQueue = { const fakeQueue = {
snapshot: () => ({ current: null, upcoming: [], status: "idle" }), 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) { async function withServer(options, run) {
@ -122,116 +114,3 @@ test("only loopback connections count as local", () => {
assert.equal(isLoopbackAddress(address), false); 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(), /<title>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);
});
});