Compare commits

...

10 commits

Author SHA1 Message Date
8cf0a8eb5b Stop listening when an events client disconnects; warn on partial OAuth setup
All checks were successful
Deploy Palico Bot / check (push) Successful in 10s
Deploy Palico Bot / deploy (push) Successful in 7s
- Detach the events stream from the queue on the response's close event,
  which fires when the client goes away whatever the Node version.
- Log a warning when only some of the Discord login variables are set,
  instead of silently leaving the login disabled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:23:28 +01:00
a269824e2a Optionally check game servers' status instead of editing it by hand
A server with "check": true in gameservers-list.json is probed over TCP
every two minutes, on "checkPort" or its game port; games played over UDP
can be checked on a TCP side port such as RCON. Servers without it keep
their manual "active" status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:22:25 +01:00
03c410973e Rework the jukebox page: live updates, Discord login, progress, batch uploads
- Follow the queue live through /api/events (read with fetch so the key can
  be sent), reconnect with backoff and reload the state meanwhile; an
  indicator shows whether the page is live.
- Log in with Discord when enabled, the password stays available as a
  fallback; explain failed logins and expired sessions.
- Show a progress bar and durations, the queue length and total time, and a
  hint when the queue waits for listeners.
- Shuffle and loop buttons; search, rename and add the whole library,
  optionally shuffled.
- Upload several files at once with per-file progress (XMLHttpRequest), add
  a direct link, drag and drop files; allow 40 uploads per 15 minutes.
- Style password, URL and search fields, focus rings, and the phone layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:21:43 +01:00
399e851178 Let guild members log in to the jukebox with Discord
- Optional Discord OAuth2 login (identify scope), enabled by
  DISCORD_CLIENT_SECRET, WEB_PUBLIC_URL and SESSION_SECRET; restricted to
  members of the configured guild, checked at login.
- Stateless 30-day session in a signed HttpOnly SameSite=Lax cookie; the
  OAuth state is checked against its own short-lived cookie.
- The jukebox API accepts the key or the session; with the session,
  changes must come from the site's own origin. The member's server name
  becomes the uploader name.
- GET /auth/me tells the page whether the login is enabled and who is
  logged in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:17:48 +01:00
9fb54798dd Keep the queue across restarts; add shuffle, loop, renaming and live events
- Save the queue to storage/runtime/queue.json and restore it at startup,
  the interrupted track first; playback resumes once someone is in the
  voice channel. Shutdown keeps the queued files instead of deleting them.
- Shuffle the upcoming tracks; loop mode sends finished tracks back to the
  end of the queue, except removed or failed ones.
- Rename library tracks (queued copies follow), enqueue the whole library,
  optionally shuffled.
- Stream queue and library changes to the web page with Server-Sent Events
  (GET /api/events).
- Sanitise the requester name sent when queueing a library track.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:15:25 +01:00
39d2b6acfb Add tracks from a direct link and from Discord with /play, /skip, /queue
- Download direct audio links server side (web page and /play), refusing
  internal and special addresses at connection time and after every
  redirect, with size and time limits.
- /play takes an attachment, a direct link or a library track
  (autocomplete), and can keep the file in the library; /skip and /queue
  control and show the shared queue.
- Share one ingest path between uploads, links and Discord attachments.
- Answer 413 instead of 500 when the library is full.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:13:12 +01:00
98f4d29ac7 Encode jukebox audio with native ffmpeg, normalise loudness, read metadata
- Play every track through an ffmpeg process that normalises loudness
  (EBU R128) and outputs Ogg Opus, handed to Discord as is: no more Opus
  encoding in JavaScript with opusscript. Measured at over 40x real time,
  about 2% of a core while playing. Closing the stream kills ffmpeg.
- Encoding at upload instead was ruled out: over two minutes for an 85-minute
  mix, during which the upload would hang.
- Read duration, title and artist with ffprobe at upload; default the title
  to "Artist - Title" or the file name without extension.
- Fill the duration of existing library entries at startup.
- Expose the position of the current track in queue snapshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:10:49 +01:00
d200040691 Lighten the website and make it more accessible
- Serve the hero images as WebP at their display size: 118 KB and 55 KB
  instead of 3.5 MB and 1.4 MB.
- Add a favicon, an apple-touch icon, a description and a theme colour.
- Announce status messages to screen readers and label the move buttons.
- Offer "Se souvenir de moi" to keep the password on the device, and keep
  working when browser storage is unavailable.
- Fix typos in the jukebox introduction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:05:57 +01:00
362c7772ba Make Discord commands and the deploy pipeline sturdier
- Defer the voice commands' reply: updating every member can take longer
  than the 3 seconds Discord allows; one member leaving no longer fails the
  whole operation.
- Replace the deprecated ephemeral option with MessageFlags, answer command
  errors in French and log when that answer itself fails; route
  autocomplete interactions to the command.
- Add /readyz, which answers 503 while the bot is not connected to Discord.
- Run npm ci and npm run check on every push; deploy main only when they
  pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:04:43 +01:00
a1cefe6da5 Fix jukebox playback getting stuck and make the web page reflect actions
- Adding a track or someone joining the voice channel now resumes a queue
  suspended because the bot was alone; before, only the Play button did.
- Retry the voice connection with backoff instead of giving up after one
  failed attempt.
- Keep playing when the head of the queue changes while connecting.
- Requeue the interrupted track when the bot leaves an empty channel or
  loses its voice connection.
- Removing the current track no longer answers 404; other bots no longer
  count as listeners.
- Accept uploads whatever MIME type the browser sends (ffprobe validates the
  content) and clean temporary files hourly, sparing queued ones.
- Web page: refresh again after an action instead of reusing a stale
  request, disable buttons while a request runs, show the real start time and
  custom titles, and support drag and drop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 11:59:58 +01:00
60 changed files with 3617 additions and 671 deletions

View file

@ -14,3 +14,11 @@ WEB_TRUSTED_PROXIES=
NOTIFICATIONS_API_KEY=
# Facultatif : lien d'invitation temporaire publié par /invitation sans option « lien ».
INVITE_LINK=
# Facultatif : connexion avec Discord sur la page web (active si les trois sont définies).
# Secret OAuth2 de l'application (portail développeur Discord, onglet OAuth2).
DISCORD_CLIENT_SECRET=
# Adresse publique du site, sans / final (https://…). Ajouter <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,18 +1,33 @@
name: Deploy Palico Bot
# Les contrôles tournent sur chaque branche ; le déploiement, seulement après un push sur
# main dont les contrôles ont réussi.
on:
push:
branches:
- main
pull_request:
jobs:
deploy:
check:
runs-on: docker
# Image fixée ici : celle du label « docker » (node:20-bullseye) n'est plus maintenue,
# et son miroir de sécurité renvoie 404 (échec du run 4).
container:
image: node:24-bookworm
steps:
- uses: actions/checkout@v4
- name: Install dependencies
run: npm ci
- name: Syntax checks and tests
run: npm run check
deploy:
needs: check
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: docker
container:
image: node:24-bookworm
steps:
- name: Deploy on WebApps
env:

View file

@ -45,7 +45,7 @@ npm run check
Le dossier `storage/` est une donnée applicative et ne doit pas être remplacé
pendant un déploiement. Sauvegarder régulièrement :
- `storage/runtime/library.json` ;
- `storage/runtime/library.json` (et `storage/runtime/queue.json`, la file en cours) ;
- `storage/permanent/`.
Les fichiers placés dans `storage/temp/` sont temporaires et nettoyés après
@ -57,12 +57,22 @@ La liste des serveurs de jeux est locale. La créer à partir du modèle :
cp src/static/gameservers-list.example.json src/static/gameservers-list.json
```
L'état de chaque serveur est soit saisi à la main (`"active"`), soit vérifié
toutes les deux minutes par le bot avec `"check": true` : il tente une connexion
TCP sur `"checkPort"` (ou `"port"`) de l'hôte de `"address"`. Pour un jeu dont
le port de jeu est en UDP, indiquer un port TCP annexe (RCON, requête) dans
`"checkPort"`.
## Déploiement
Un push sur `main` lance `.forgejo/workflows/deploy.yml`, qui se connecte en SSH
à la VM et exécute `/usr/local/bin/deploy-palico-bot` (mise à jour du dépôt,
dépendances, redémarrage du service `palico-bot`). Le workflow ne lance ni les
contrôles ni les tests : lancer `npm run check` avant de pousser.
`.forgejo/workflows/deploy.yml` lance `npm ci` puis `npm run check` (syntaxe et
tests) à chaque push, sur toutes les branches. Sur `main`, et seulement si ces
contrôles réussissent, il se connecte ensuite en SSH à la VM et exécute
`/usr/local/bin/deploy-palico-bot` (mise à jour du dépôt, dépendances, redémarrage
du service `palico-bot`).
Supervision : `/healthz` répond dès que le processus tourne ; `/readyz` répond
`503` tant que le bot n'est pas connecté à Discord.
Variables facultatives :
@ -75,6 +85,44 @@ Variables facultatives :
- `INVITE_LINK` : lien publié par `/invitation` quand la commande ne reçoit pas
de lien.
## Jukebox
La page `/jukebox` et les commandes `/play`, `/skip` et `/queue` pilotent la même
file d'attente.
- `/play fichier:` (pièce jointe), `/play lien:` (lien direct vers un fichier
audio) ou `/play morceau:` (bibliothèque, avec autocomplétion) ; l'option
`garder` ajoute le fichier à la bibliothèque. La page web accepte aussi un
lien direct. YouTube et Spotify ne sont pas pris en charge.
- Le serveur télécharge lui-même les liens et refuse les adresses internes
(réseau local, boucle locale…), y compris après une redirection.
- Chaque morceau passe par `ffmpeg`, qui normalise le volume (EBU R128) et
encode en Opus : Discord reçoit l'audio sans réencodage.
- La file est enregistrée dans `storage/runtime/queue.json` : après un
redémarrage, elle reprend dès que quelqu'un est dans le salon vocal.
- La page web reçoit les changements en direct par `GET /api/events`
(Server-Sent Events, même clé que le reste de l'API).
### Connexion avec Discord
Facultative : sans elle, la page web demande le mot de passe (`WEB_API_KEY`), qui
reste utilisable dans tous les cas. Pour l'activer :
1. Portail développeur Discord, application du bot, onglet OAuth2 : copier le
secret client et ajouter la redirection `<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.
## Invitations
Les membres ne peuvent pas créer d'invitation : un seul lien, à adhésion

View file

@ -4,6 +4,7 @@ import path from "path";
import { fileURLToPath } from "url";
import { config } from "./src/config.js";
import { MusicQueue } from "./src/music/queue.js";
import { createQueuePersistence } from "./src/music/queuePersistence.js";
import { startWebServer } from "./src/web/server.js";
const __filename = fileURLToPath(import.meta.url);
@ -56,7 +57,13 @@ for (const file of eventFiles) {
}
}
const musicQueue = new MusicQueue(client);
const musicQueue = new MusicQueue(client, {
persistence: createQueuePersistence(
path.join(process.cwd(), "storage", "runtime", "queue.json")
),
});
// Les commandes du jukebox (/play, /skip, /queue) y accèdent par interaction.client.
client.musicQueue = musicQueue;
await client.login(config.token);
const { server } = startWebServer({ queue: musicQueue, client });

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

BIN
public/img/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

View file

@ -4,12 +4,16 @@
<meta charset="utf-8" />
<title>Palico Bot</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="Palico Bot : le jukebox du salon vocal Discord." />
<meta name="theme-color" content="#140b24" />
<link rel="icon" type="image/png" href="/img/favicon.png" />
<link rel="apple-touch-icon" href="/img/apple-touch-icon.png" />
<link rel="stylesheet" href="/style/styles.css" />
</head>
<body>
<div class="hero hero--home">
<div class="hero__visual">
<img src="/img/palico-index.png" alt="Palico Bot" />
<img src="/img/palico-index.webp" alt="Palico Bot" width="640" height="960" />
</div>
<div class="hero__content">

View file

@ -4,177 +4,245 @@
<meta charset="utf-8" />
<title>Palico Jukebox</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#140b24" />
<link rel="icon" type="image/png" href="/img/favicon.png" />
<link rel="apple-touch-icon" href="/img/apple-touch-icon.png" />
<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" />
<img src="/img/palico-jukebox.webp" alt="Palico Jukebox" width="400" height="857" />
</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 />
T'inquiète pas, je peux m'occuper de ça !<br />
<br />
Uploade des fichiers et gère la playlist depuis cette interface web.
Tout est synchronisé avec le salon vocal.
Ajoute des morceaux et gère la playlist depuis cette page, ou avec
<code>/play</code> sur Discord. 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>
<button id="heroUploadBtn" class="btn" type="button">Ajouter une musique</button>
<button id="heroQueueBtn" class="btn btn--ghost" type="button">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"
/>
<h2>Connexion</h2>
<div id="loggedIn" hidden>
<p class="panel__subtitle">
Connecté en tant que <strong id="userName"></strong>.
</p>
<button id="logoutBtn" class="btn btn--ghost btn--small" type="button">
Se déconnecter
</button>
</div>
<div id="discordLogin" hidden>
<p class="panel__subtitle">Réservé aux membres du serveur Discord.</p>
<a class="btn btn--discord" href="/auth/discord">Se connecter avec Discord</a>
</div>
<details id="keyLogin" class="key-login">
<summary id="keyLoginSummary">Utiliser le mot de passe</summary>
<p class="panel__subtitle">
Sans « Se souvenir de moi », le mot de passe est oublié à la
fermeture de l'onglet.
</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"
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>
<div>
<label for="apiKey">Mot de passe</label>
<input
type="password"
id="apiKey"
name="apiKey"
placeholder="Mot de passe"
autocomplete="current-password"
/>
<label class="form-checkbox u-mt-1">
<input type="checkbox" id="rememberKey" class="form-checkbox__input" />
<span>Se souvenir de moi sur cet appareil</span>
</label>
<div class="form-actions">
<button type="submit" class="btn">Sauvegarder</button>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn">Sauvegarder</button>
</div>
</form>
</form>
</details>
</div>
</div>
</div>
<main>
<div id="status" class="status status--info" hidden></div>
<div id="status" class="status status--info" role="status" aria-live="polite" hidden></div>
<section class="panel panel--glass">
<section class="panel panel--glass" aria-labelledby="playerTitle">
<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>
<h2 id="playerTitle">Lecture en cours</h2>
<p class="panel__subtitle">État du player Discord, mis à jour en direct.</p>
</div>
<button id="refreshBtn" class="btn btn--ghost btn--small">Rafraîchir</button>
<span id="liveIndicator" class="live-indicator" data-live="false">Hors ligne</span>
</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"
<div class="progress" id="progress" hidden>
<div
class="progress__track"
role="progressbar"
aria-label="Progression du morceau"
aria-valuemin="0"
aria-valuemax="100"
aria-valuenow="0"
id="progressTrack"
>
<div class="progress__bar" id="progressBar"></div>
</div>
<div class="progress__times">
<span id="progressElapsed">0:00</span>
<span id="progressTotal"></span>
</div>
</div>
<div class="control-group">
<button class="btn" type="button" data-player-action="play" title="Lance la file si elle est en attente">
Play
</button>
<button id="pauseResumeBtn" class="btn btn--secondary" type="button" data-player-action="pause">
Pause
</button>
<button class="btn" data-player-action="skip">Suivante</button>
<button class="btn btn--danger" data-player-action="stop">
<button class="btn" type="button" data-player-action="skip">Suivante</button>
<button class="btn btn--secondary" type="button" data-player-action="shuffle">Mélanger</button>
<button id="loopBtn" class="btn btn--secondary" type="button" aria-pressed="false">
Boucle : non
</button>
<button class="btn btn--danger" type="button" data-player-action="stop">
Stop & vider la file
</button>
</div>
</section>
<section class="panel panel--glass" id="queueSection">
<section class="panel panel--glass" id="queueSection" aria-labelledby="queueTitle">
<div class="panel__header">
<div>
<h2>File d'attente</h2>
<h2 id="queueTitle">File d'attente</h2>
<p class="panel__subtitle">
Réorganise les morceaux, supprime-les ou ajoute ceux de la
bibliothèque.
</p>
</div>
<span id="queueSummary" class="badge" hidden></span>
</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">
<section class="panel panel--glass" aria-labelledby="libraryTitle">
<div class="panel__header">
<div>
<h2>Uploader une musique</h2>
<h2 id="libraryTitle">Bibliothèque permanente</h2>
<p class="panel__subtitle">
Formats audio supportés par FFmpeg. Les fichiers temporaires sont
supprimés automatiquement après lecture.
Les fichiers conservés sont listés ici. Ajoute-les à la file,
renomme-les ou supprime-les.
</p>
</div>
<div class="badge">Drag & drop supporté</div>
<div class="toolbar">
<button id="enqueueAllBtn" class="btn btn--secondary btn--small" type="button">Tout ajouter</button>
<button id="enqueueAllShuffledBtn" class="btn btn--secondary btn--small" type="button">
Tout ajouter, mélangé
</button>
</div>
</div>
<form id="uploadForm">
<label for="musicFile">Fichier audio</label>
<input
type="file"
id="musicFile"
name="musicFile"
accept="audio/*"
required
/>
<label for="librarySearch" class="visually-hidden">Rechercher dans la bibliothèque</label>
<input
type="search"
id="librarySearch"
placeholder="Rechercher un morceau…"
autocomplete="off"
/>
<ul id="libraryList" class="list list--stack u-mt-1"></ul>
<p id="libraryEmpty" class="text--muted">Aucun fichier permanent enregistré.</p>
</section>
<label for="uploadNotes" class="u-mt-1">Commentaire (optionnel)</label>
<section class="panel panel--glass" id="uploadSection" aria-labelledby="uploadTitle">
<div class="panel__header">
<div>
<h2 id="uploadTitle">Ajouter de la musique</h2>
<p class="panel__subtitle">
Fichiers audio (150 Mo au plus chacun) ou lien direct vers un
fichier. Les morceaux temporaires sont supprimés après lecture.
</p>
</div>
<div class="badge">Glisser-déposer accepté</div>
</div>
<div class="grid grid--two">
<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>
<form id="uploadForm" class="u-mt-1">
<label for="musicFile">Fichiers audio</label>
<input type="file" id="musicFile" name="musicFile" accept="audio/*,video/*" multiple required />
<label for="uploadNotes" class="u-mt-1">Titre (optionnel, pour un seul fichier)</label>
<input
type="text"
id="uploadNotes"
name="notes"
placeholder="Titre personnalisé"
maxlength="200"
placeholder="Par défaut : les tags du fichier, sinon son nom"
/>
<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">Envoyer</button>
</form>
<button type="submit" class="btn u-mt-1">Uploader</button>
<ul id="uploadList" class="list upload-list" aria-live="polite"></ul>
<form id="urlForm" class="u-mt-1 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">Ajouter</button>
</div>
<p class="hint">YouTube et Spotify ne sont pas pris en charge.</p>
</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>
<a class="btn btn--ghost btn--small" href="/">Retour à l'accueil</a>
</div>
<script type="module" src="/scripts/jukebox.js"></script>

View file

@ -1,20 +1,52 @@
const API_KEY_STORAGE_KEY = "palico-api-key";
const DISPLAY_NAME_STORAGE_KEY = "palico-display-name";
export function getStoredApiKey() {
return sessionStorage.getItem(API_KEY_STORAGE_KEY) || "";
// Le stockage peut être indisponible (navigation privée, cookies bloqués) : la page doit
// fonctionner quand même, simplement sans mémoire.
function storageGet(storage, key) {
try {
return storage.getItem(key);
} catch {
return null;
}
}
export function setStoredApiKey(value) {
sessionStorage.setItem(API_KEY_STORAGE_KEY, value || "");
function storageSet(storage, key, value) {
try {
if (value) {
storage.setItem(key, value);
} else {
storage.removeItem(key);
}
} catch {
// Stockage indisponible.
}
}
export function getStoredApiKey() {
return (
storageGet(sessionStorage, API_KEY_STORAGE_KEY) ||
storageGet(localStorage, API_KEY_STORAGE_KEY) ||
""
);
}
export function isApiKeyRemembered() {
return Boolean(storageGet(localStorage, API_KEY_STORAGE_KEY));
}
// remember : garde la clé sur l'appareil (localStorage) au lieu de l'onglet (sessionStorage).
export function setStoredApiKey(value, { remember = false } = {}) {
storageSet(remember ? localStorage : sessionStorage, API_KEY_STORAGE_KEY, value);
storageSet(remember ? sessionStorage : localStorage, API_KEY_STORAGE_KEY, "");
}
export function getStoredDisplayName() {
return localStorage.getItem(DISPLAY_NAME_STORAGE_KEY) || "";
return storageGet(localStorage, DISPLAY_NAME_STORAGE_KEY) || "";
}
export function setStoredDisplayName(value) {
localStorage.setItem(DISPLAY_NAME_STORAGE_KEY, value || "");
storageSet(localStorage, DISPLAY_NAME_STORAGE_KEY, value);
}
export function createStatusManager(statusElement) {
@ -61,6 +93,19 @@ export function formatBytes(bytes = 0) {
return `${(bytes / Math.pow(1024, index)).toFixed(1)} ${units[index]}`;
}
// Durée lisible : 3:07, 1:05:09. null si inconnue.
export function formatDuration(seconds) {
const value = Number(seconds);
if (!Number.isFinite(value) || value < 0 || seconds === null) return null;
const total = Math.round(value);
const hours = Math.floor(total / 3600);
const minutes = Math.floor((total % 3600) / 60);
const secs = String(total % 60).padStart(2, "0");
return hours > 0
? `${hours}:${String(minutes).padStart(2, "0")}:${secs}`
: `${minutes}:${secs}`;
}
export function formatDate(value) {
if (!value) return "?";
try {

File diff suppressed because it is too large Load diff

View file

@ -19,6 +19,25 @@
box-sizing: border-box;
}
[hidden] {
display: none !important;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
white-space: nowrap;
}
code {
background: rgba(255, 255, 255, 0.08);
border-radius: 6px;
padding: 0.1rem 0.35rem;
}
body {
margin: 0;
min-height: 100vh;
@ -109,6 +128,7 @@ p {
.hero__visual img {
max-width: 200px;
width: 100%;
height: auto;
filter: drop-shadow(0 25px 45px rgba(0, 0, 0, 0.45));
}
@ -146,6 +166,11 @@ p {
backdrop-filter: blur(18px);
}
.panel--dragover {
border-color: var(--accent);
border-style: dashed;
}
.panel__subtitle {
color: var(--muted);
margin-top: 0.35rem;
@ -176,6 +201,9 @@ label {
}
input[type="text"],
input[type="password"],
input[type="url"],
input[type="search"],
input[type="file"],
select,
textarea {
@ -254,6 +282,149 @@ select:focus {
font-size: 0.9rem;
}
a.btn {
display: inline-block;
text-decoration: none;
text-align: center;
}
.btn--discord {
background: #5865f2;
color: #fff;
}
.btn--discord:hover {
box-shadow: 0 10px 25px rgba(88, 101, 242, 0.4);
}
.btn[aria-pressed="true"] {
background: linear-gradient(120deg, var(--accent), var(--accent-strong));
color: #08010f;
}
.btn:focus-visible {
outline: 2px solid #fff;
outline-offset: 2px;
}
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.key-login summary {
cursor: pointer;
color: var(--muted);
margin: 1rem 0 0.75rem;
}
.live-indicator {
display: inline-flex;
align-items: center;
gap: 0.45rem;
font-size: 0.85rem;
color: var(--muted-dark);
white-space: nowrap;
}
.live-indicator::before {
content: "";
width: 0.55rem;
height: 0.55rem;
border-radius: 50%;
background: var(--muted-dark);
}
.live-indicator[data-live="true"] {
color: var(--success);
}
.live-indicator[data-live="true"]::before {
background: var(--success);
box-shadow: 0 0 0 4px rgba(89, 255, 167, 0.15);
}
.progress {
margin-top: 0.9rem;
}
.progress__track {
height: 6px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.1);
overflow: hidden;
}
.progress__bar {
height: 100%;
width: 0;
background: linear-gradient(120deg, var(--accent), var(--accent-strong));
transition: width 0.9s linear;
}
.progress__times {
display: flex;
justify-content: space-between;
color: var(--muted);
font-size: 0.85rem;
margin-top: 0.35rem;
font-variant-numeric: tabular-nums;
}
.upload-list {
margin-top: 1rem;
}
.upload-list__item {
display: grid;
grid-template-columns: minmax(0, 1fr) 140px minmax(0, 1fr);
align-items: center;
gap: 0.75rem;
padding: 0.4rem 0;
font-size: 0.9rem;
}
.upload-list__name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.upload-list__item progress {
width: 100%;
accent-color: var(--accent);
}
.upload-list__state {
color: var(--muted);
}
.upload-list__item[data-state="ok"] .upload-list__state {
color: var(--success);
}
.upload-list__item[data-state="error"] .upload-list__state {
color: var(--danger);
}
.url-form {
border-top: 1px solid var(--border);
padding-top: 1.25rem;
margin-top: 1.5rem;
}
.url-form__row {
display: flex;
gap: 0.75rem;
}
.hint {
color: var(--muted-dark);
font-size: 0.85rem;
margin: 0.5rem 0 0;
}
.control-group {
display: flex;
flex-wrap: wrap;
@ -412,4 +583,23 @@ select:focus {
.control-group {
flex-direction: column;
}
.url-form__row {
flex-direction: column;
}
.upload-list__item {
grid-template-columns: 1fr;
gap: 0.25rem;
}
.media-item {
flex-direction: column;
align-items: stretch;
}
.media-item__actions .btn {
width: auto;
flex: 1;
}
}

View file

@ -1,34 +1,34 @@
import { SlashCommandBuilder } from "discord.js";
const command = {
data: new SlashCommandBuilder()
.setName("maketeam")
.setDescription("Crée des equipes au hasard")
.addIntegerOption((option) =>
option
import { MessageFlags, SlashCommandBuilder } from "discord.js";
const command = {
data: new SlashCommandBuilder()
.setName("maketeam")
.setDescription("Crée des equipes au hasard")
.addIntegerOption((option) =>
option
.setName("number")
.setDescription("Nombre d'équipe")
.setMinValue(1)
.setMaxValue(20)
.setRequired(true)
)
.addStringOption((option) =>
option
)
.addStringOption((option) =>
option
.setName("players")
.setDescription("Liste des joueurs, séparés par un espace")
.setMinLength(1)
.setMaxLength(1000)
.setRequired(true)
),
async execute(interaction) {
const teamNumber = interaction.options.getInteger("number");
const players = interaction.options.getString("players");
),
async execute(interaction) {
const teamNumber = interaction.options.getInteger("number");
const players = interaction.options.getString("players");
const playersArray = players.trim().split(/\s+/);
if (teamNumber > playersArray.length) {
await interaction.reply({
content: "Le nombre d'équipes ne peut pas dépasser le nombre de joueurs.",
ephemeral: true,
flags: MessageFlags.Ephemeral,
});
return;
}
@ -42,22 +42,22 @@ const command = {
shuffledPlayers[index],
];
}
shuffledPlayers.forEach((player, index) => {
const teamIndex = index % teamNumber;
teams[teamIndex].push(player);
});
let message = "";
let teamList = "";
teams.forEach((team, index) => {
teamList = `${teamList}\n${index + 1}. ${team.join(", ")}`;
});
message = `Yop ! Voici les équipes proposés :\n${teamList}`;
await interaction.reply(message);
},
};
export { command };
shuffledPlayers.forEach((player, index) => {
const teamIndex = index % teamNumber;
teams[teamIndex].push(player);
});
let message = "";
let teamList = "";
teams.forEach((team, index) => {
teamList = `${teamList}\n${index + 1}. ${team.join(", ")}`;
});
message = `Yop ! Voici les équipes proposés :\n${teamList}`;
await interaction.reply(message);
},
};
export { command };

View file

@ -0,0 +1,126 @@
import { MessageFlags, SlashCommandBuilder, escapeMarkdown } from "discord.js";
import { downloadAudio } from "../../media/downloadAudio.js";
import { ingestAudioFile } from "../../music/ingest.js";
import { trackLabel } from "../../features/formatTrack.js";
import {
TEMP_DIR,
createQueueTrackFromLibrary,
findPermanentTrack,
getPermanentLibrary,
} from "../../web/storage/storageManager.js";
const MAX_ATTACHMENT_SIZE = 150 * 1024 * 1024;
function positionMessage(queue, track) {
if (queue.currentTrack?.id === track.id) {
return "c'est parti ! 🎶";
}
const index = queue.queue.findIndex((queued) => queued.id === track.id);
return index >= 0 ? `position ${index + 1} dans la file.` : "ajouté à la file.";
}
const command = {
data: new SlashCommandBuilder()
.setName("play")
.setDescription("Ajoute un morceau à la file du jukebox")
.addAttachmentOption((option) =>
option.setName("fichier").setDescription("Fichier audio à jouer")
)
.addStringOption((option) =>
option
.setName("lien")
.setDescription("Lien direct vers un fichier audio (pas YouTube ni Spotify)")
.setMaxLength(2000)
)
.addStringOption((option) =>
option
.setName("morceau")
.setDescription("Morceau de la bibliothèque")
.setAutocomplete(true)
)
.addBooleanOption((option) =>
option
.setName("garder")
.setDescription("Garder le fichier ou le lien dans la bibliothèque")
),
async autocomplete(interaction) {
const query = interaction.options.getFocused().toLowerCase();
const choices = getPermanentLibrary()
.filter((entry) =>
`${entry.title || ""} ${entry.originalName || ""}`.toLowerCase().includes(query)
)
.slice(0, 25)
.map((entry) => ({ name: trackLabel(entry).slice(0, 100), value: entry.id }));
await interaction.respond(choices);
},
async execute(interaction) {
const queue = interaction.client.musicQueue;
const attachment = interaction.options.getAttachment("fichier");
const link = interaction.options.getString("lien");
const libraryId = interaction.options.getString("morceau");
const keep = interaction.options.getBoolean("garder") ?? false;
const sources = [attachment, link, libraryId].filter(Boolean);
if (sources.length !== 1) {
await interaction.reply({
content: "Choisis une seule source : `fichier`, `lien` ou `morceau`.",
flags: MessageFlags.Ephemeral,
});
return;
}
const uploader = interaction.member?.displayName || interaction.user.username;
if (libraryId) {
const entry = findPermanentTrack(libraryId);
if (!entry) {
await interaction.reply({
content: "Morceau introuvable dans la bibliothèque.",
flags: MessageFlags.Ephemeral,
});
return;
}
const track = queue.enqueue(createQueueTrackFromLibrary(entry, uploader));
await interaction.reply(
`**${escapeMarkdown(trackLabel(track))}** : ${positionMessage(queue, track)}`
);
return;
}
if (attachment && attachment.size > MAX_ATTACHMENT_SIZE) {
await interaction.reply({
content: "Fichier trop volumineux (150 Mo au plus).",
flags: MessageFlags.Ephemeral,
});
return;
}
await interaction.deferReply();
try {
const file = await downloadAudio(attachment?.url ?? link, { destinationDir: TEMP_DIR });
if (attachment?.name) {
file.originalname = attachment.name;
}
const track = await ingestAudioFile(
file,
{ permanent: keep, enqueue: true, uploader },
{ queue }
);
await interaction.editReply(
`**${escapeMarkdown(trackLabel(track))}** : ${positionMessage(queue, track)}`
);
} catch (error) {
if (!error.status) throw error;
// Erreur attendue (lien invalide, fichier non audio…) : on l'explique sans la publier.
await interaction.deleteReply().catch(() => {});
await interaction.followUp({
content: `Impossible d'ajouter ce morceau : ${error.message}`,
flags: MessageFlags.Ephemeral,
});
}
},
};
export { command };

View file

@ -0,0 +1,41 @@
import { MessageFlags, SlashCommandBuilder, escapeMarkdown } from "discord.js";
import { trackLabel } from "../../features/formatTrack.js";
const SHOWN_TRACKS = 10;
function buildQueueMessage(queue) {
const lines = [];
lines.push(
queue.currentTrack
? `🎶 En cours : **${escapeMarkdown(trackLabel(queue.currentTrack))}**`
: "🎶 Rien en cours de lecture."
);
if (queue.queue.length === 0) {
lines.push("La file est vide. Ajoute un morceau avec `/play`.");
} else {
lines.push("", "__À suivre__ :");
queue.queue.slice(0, SHOWN_TRACKS).forEach((track, index) => {
lines.push(`${index + 1}. ${escapeMarkdown(trackLabel(track))}`);
});
const hidden = queue.queue.length - SHOWN_TRACKS;
if (hidden > 0) {
lines.push(`… et ${hidden} autre(s).`);
}
}
return lines.join("\n");
}
const command = {
data: new SlashCommandBuilder()
.setName("queue")
.setDescription("Affiche la file d'attente du jukebox"),
async execute(interaction) {
await interaction.reply({
content: buildQueueMessage(interaction.client.musicQueue),
flags: MessageFlags.Ephemeral,
});
},
};
export { buildQueueMessage, command };

View file

@ -0,0 +1,24 @@
import { MessageFlags, SlashCommandBuilder, escapeMarkdown } from "discord.js";
import { trackLabel } from "../../features/formatTrack.js";
const command = {
data: new SlashCommandBuilder()
.setName("skip")
.setDescription("Passe au morceau suivant du jukebox"),
async execute(interaction) {
const queue = interaction.client.musicQueue;
const current = queue.currentTrack;
if (!current) {
await interaction.reply({
content: "Rien n'est en cours de lecture.",
flags: MessageFlags.Ephemeral,
});
return;
}
queue.skip();
await interaction.reply(`⏭️ **${escapeMarkdown(trackLabel(current))}** passé.`);
},
};
export { command };

View file

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

View file

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

View file

@ -1,28 +1,33 @@
import { SlashCommandBuilder } from "discord.js";
const command = {
data: new SlashCommandBuilder()
.setName("listcommand")
.setDescription("Affiche la liste des commandes disponibles"),
async execute(interaction) {
let message = `Voila la liste des commandes que tu peux utiliser :
__Categorie Utililaires__ :
\`/deletemsgs\`: Supprime les 100 derniers messages non épinglés
\`/invitation\`: Publie le message d'invitation temporaire (lien vérifié)
__Categorie Vocal__ :
\`/muteall\`: Rends tout le monde muet
\`/unmuteall\`: Rends la parole à tout le monde
\`/deafall\`: Rends tout le monde sourd
\`/undeafall\`: Rends l'ouïe à tout le monde
__Categorie Jeux__ :
\`/dice\`: Lance un ou plusieurs dés avec un nombre de faces choisi
\`/maketeam\`: Crée un certain nombre d'équipes en renseignant des joueurs (séparés par un espace)
`;
await interaction.reply({ content: message, ephemeral: true });
},
};
export { command };
import { MessageFlags, SlashCommandBuilder } from "discord.js";
const command = {
data: new SlashCommandBuilder()
.setName("listcommand")
.setDescription("Affiche la liste des commandes disponibles"),
async execute(interaction) {
let message = `Voila la liste des commandes que tu peux utiliser :
__Categorie Utililaires__ :
\`/deletemsgs\`: Supprime les 100 derniers messages non épinglés
\`/invitation\`: Publie le message d'invitation temporaire (lien vérifié)
__Categorie Jukebox__ :
\`/play\`: Ajoute un morceau (fichier, lien direct ou morceau de la bibliothèque)
\`/skip\`: Passe au morceau suivant
\`/queue\`: Affiche la file d'attente
__Categorie Vocal__ :
\`/muteall\`: Rends tout le monde muet
\`/unmuteall\`: Rends la parole à tout le monde
\`/deafall\`: Rends tout le monde sourd
\`/undeafall\`: Rends l'ouïe à tout le monde
__Categorie Jeux__ :
\`/dice\`: Lance un ou plusieurs dés avec un nombre de faces choisi
\`/maketeam\`: Crée un certain nombre d'équipes en renseignant des joueurs (séparés par un espace)
`;
await interaction.reply({ content: message, flags: MessageFlags.Ephemeral });
},
};
export { command };

View file

@ -1,12 +1,12 @@
import { SlashCommandBuilder } from "discord.js";
const command = {
import { MessageFlags, SlashCommandBuilder } from "discord.js";
const command = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Reponds avec Pong"),
.setName("ping")
.setDescription("Reponds avec Pong"),
async execute(interaction) {
await interaction.reply({ content: "Euh... Pong ! 🐱", ephemeral: true });
},
};
export { command };
await interaction.reply({ content: "Euh... Pong ! 🐱", flags: MessageFlags.Ephemeral });
},
};
export { command };

View file

@ -1,17 +1,19 @@
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { changeVoiceStatus } from "../../features/utilities.js";
import { requirePermission } from "../../features/permissions.js";
const command = {
data: new SlashCommandBuilder()
const command = {
data: new SlashCommandBuilder()
.setName("deafall")
.setDescription("Deaf tout le monde dans le lounge")
.setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers),
async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.DeafenMembers))) return;
// Changer l'état de chaque membre peut dépasser les 3 s qu'accorde Discord pour répondre.
await interaction.deferReply();
await changeVoiceStatus(interaction.client, "deaf", "all");
await interaction.reply("On n'entends plus rien ! 🐱");
},
};
export { command };
await interaction.editReply("On n'entends plus rien ! 🐱");
},
};
export { command };

View file

@ -1,17 +1,19 @@
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { changeVoiceStatus } from "../../features/utilities.js";
import { requirePermission } from "../../features/permissions.js";
const command = {
data: new SlashCommandBuilder()
const command = {
data: new SlashCommandBuilder()
.setName("muteall")
.setDescription("Mute tout le monde dans le lounge")
.setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers),
async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.MuteMembers))) return;
// Changer l'état de chaque membre peut dépasser les 3 s qu'accorde Discord pour répondre.
await interaction.deferReply();
await changeVoiceStatus(interaction.client, "mute", "all");
await interaction.reply("Voila, tout le monde est mioute ! 🐱");
},
};
export { command };
await interaction.editReply("Voila, tout le monde est mioute ! 🐱");
},
};
export { command };

View file

@ -1,17 +1,19 @@
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { changeVoiceStatus } from "../../features/utilities.js";
import { requirePermission } from "../../features/permissions.js";
const command = {
data: new SlashCommandBuilder()
const command = {
data: new SlashCommandBuilder()
.setName("undeafall")
.setDescription("Undeaf tout le monde dans le lounge")
.setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers),
async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.DeafenMembers))) return;
// Changer l'état de chaque membre peut dépasser les 3 s qu'accorde Discord pour répondre.
await interaction.deferReply();
await changeVoiceStatus(interaction.client, "undeaf", "all");
await interaction.reply("Voila, les oreilles sont réparées ! 🐱");
},
};
export { command };
await interaction.editReply("Voila, les oreilles sont réparées ! 🐱");
},
};
export { command };

View file

@ -1,17 +1,19 @@
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { changeVoiceStatus } from "../../features/utilities.js";
import { requirePermission } from "../../features/permissions.js";
const command = {
data: new SlashCommandBuilder()
const command = {
data: new SlashCommandBuilder()
.setName("unmuteall")
.setDescription("Unmute tout le monde dans le lounge")
.setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers),
async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.MuteMembers))) return;
// Changer l'état de chaque membre peut dépasser les 3 s qu'accorde Discord pour répondre.
await interaction.deferReply();
await changeVoiceStatus(interaction.client, "unmute", "all");
await interaction.reply("Et.... unmioute ! 🐱");
},
};
export { command };
await interaction.editReply("Et.... unmioute ! 🐱");
},
};
export { command };

View file

@ -41,6 +41,36 @@ const notificationsApiKey = process.env.NOTIFICATIONS_API_KEY?.trim() || null;
// INVITE_LINK : lien publié par /invitation quand la commande ne reçoit pas de lien.
const inviteLink = process.env.INVITE_LINK?.trim() || null;
// Connexion avec Discord sur la page web (facultative, active si les trois sont définies) :
// DISCORD_CLIENT_SECRET (portail développeur, OAuth2), WEB_PUBLIC_URL (adresse publique du
// site, sans / final) et SESSION_SECRET (32 caractères au moins, signe les sessions).
const discordClientSecret = process.env.DISCORD_CLIENT_SECRET?.trim() || null;
const webPublicUrl = process.env.WEB_PUBLIC_URL?.trim().replace(/\/+$/, "") || null;
const sessionSecret = process.env.SESSION_SECRET?.trim() || null;
const discordOAuthEnabled = Boolean(discordClientSecret && webPublicUrl && sessionSecret);
const oauthVariablesSet = [discordClientSecret, webPublicUrl, sessionSecret].filter(Boolean).length;
if (oauthVariablesSet > 0 && !discordOAuthEnabled) {
console.warn(
"Connexion avec Discord désactivée : DISCORD_CLIENT_SECRET, WEB_PUBLIC_URL et SESSION_SECRET doivent toutes être définies"
);
}
if (discordOAuthEnabled) {
let publicUrl;
try {
publicUrl = new URL(webPublicUrl);
} catch {
throw new Error("WEB_PUBLIC_URL doit être une adresse complète (https://…)");
}
if (publicUrl.protocol !== "https:" && publicUrl.hostname !== "localhost") {
throw new Error("WEB_PUBLIC_URL doit être en https");
}
if (sessionSecret.length < 32) {
throw new Error("SESSION_SECRET doit contenir au moins 32 caractères");
}
}
if (notificationsApiKey && notificationsApiKey === process.env.WEB_API_KEY) {
throw new Error("NOTIFICATIONS_API_KEY doit être différente de WEB_API_KEY");
}
@ -54,6 +84,10 @@ const config = Object.freeze({
webTrustedProxies,
notificationsApiKey,
inviteLink,
discordOAuthEnabled,
discordClientSecret,
webPublicUrl,
sessionSecret,
applicationId: process.env.DISCORD_APPLICATION_ID,
token: process.env.DISCORD_TOKEN,
voiceChannelId: process.env.VOICE_CHANNEL_ID,

View file

@ -1,36 +1,48 @@
import { Events } from "discord.js";
const event = {
name: Events.InteractionCreate,
async execute(interaction) {
if (!interaction.isChatInputCommand()) return;
import { Events, MessageFlags } from "discord.js";
const ERROR_MESSAGE = "Oups, une erreur est survenue pendant la commande 😿";
const event = {
name: Events.InteractionCreate,
async execute(interaction) {
if (interaction.isAutocomplete()) {
const command = interaction.client.commands.get(interaction.commandName)?.command;
try {
await command?.autocomplete?.(interaction);
} catch (error) {
console.error(`Autocomplete failed for ${interaction.commandName}`, error);
}
return;
}
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName)?.command;
if (!command) {
console.error(
`No command matching ${interaction.commandName} was found.`
);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({
content: "There was an error while executing this command!",
ephemeral: true,
});
} else {
await interaction.reply({
content: "There was an error while executing this command!",
ephemeral: true,
});
}
}
},
};
export { event };
if (!command) {
console.error(
`No command matching ${interaction.commandName} was found.`
);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Command ${interaction.commandName} failed`, error);
// Le message d'erreur peut lui-même échouer (interaction expirée) : on le journalise
// au lieu de laisser une promesse rejetée sans gestionnaire.
try {
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: ERROR_MESSAGE, flags: MessageFlags.Ephemeral });
} else {
await interaction.reply({ content: ERROR_MESSAGE, flags: MessageFlags.Ephemeral });
}
} catch (replyError) {
console.error("Unable to report the command error to the user", replyError);
}
}
},
};
export { event };

View file

@ -1,14 +1,17 @@
import { Events } from "discord.js";
import { showGameServers } from "../features/showGameServers.js";
const event = {
name: Events.ClientReady,
once: true,
const event = {
name: Events.ClientReady,
once: true,
async execute(client) {
console.log(
`[${new Date().toLocaleString()}] Logged in as ${client.user.tag}`
);
console.log(
`[${new Date().toLocaleString()}] Logged in as ${client.user.tag}`
);
// File rechargée au démarrage : reprendre si quelqu'un est déjà dans le salon vocal.
client.musicQueue?.evaluateAloneStatus();
try {
await showGameServers(client);
} catch (error) {
@ -16,5 +19,5 @@ const event = {
}
},
};
export { event };
export { event };

View file

@ -0,0 +1,17 @@
// Durée lisible : 3:07, 1:05:09.
function formatDuration(seconds) {
if (!Number.isFinite(seconds) || seconds < 0) return null;
const total = Math.round(seconds);
const hours = Math.floor(total / 3600);
const minutes = Math.floor((total % 3600) / 60);
const secs = String(total % 60).padStart(2, "0");
return hours > 0 ? `${hours}:${String(minutes).padStart(2, "0")}:${secs}` : `${minutes}:${secs}`;
}
function trackLabel(track) {
const title = track.title || track.originalName || "Sans titre";
const duration = formatDuration(track.duration);
return duration ? `${title} (${duration})` : title;
}
export { formatDuration, trackLabel };

View file

@ -1,3 +1,5 @@
import { MessageFlags } from "discord.js";
async function requirePermission(interaction, permission) {
if (interaction.memberPermissions?.has(permission)) {
return true;
@ -5,7 +7,7 @@ async function requirePermission(interaction, permission) {
await interaction.reply({
content: "Tu n'as pas la permission d'utiliser cette commande.",
ephemeral: true,
flags: MessageFlags.Ephemeral,
});
return false;
}

View file

@ -1,38 +1,82 @@
import net from "node:net";
import { config } from "../config.js";
import { getJSONData } from "./utilities.js";
var currentStatus = [];
import { getJSONData } from "./utilities.js";
const PROBE_TIMEOUT = 3_000;
const REFRESH_INTERVAL = 120_000;
var currentStatus = [];
// Essaie d'ouvrir une connexion TCP : vrai si le port répond dans le délai.
function probeTcp(host, port, { timeout = PROBE_TIMEOUT, connect = net.connect } = {}) {
return new Promise((resolve) => {
const socket = connect({ host, port });
const finish = (online) => {
socket.destroy();
resolve(online);
};
socket.setTimeout(timeout, () => finish(false));
socket.once("connect", () => finish(true));
socket.once("error", () => finish(false));
});
}
// État d'un serveur : sondé si "check" vaut true (TCP sur "checkPort", sinon "port", à l'hôte
// de "address"), sinon le champ "active" saisi à la main. Un jeu dont le port de jeu est en
// UDP peut être sondé sur un port TCP annexe (RCON, requête…) avec "checkPort".
async function serverStatus(server, probe = probeTcp) {
if (server.check !== true) {
return Boolean(server.active);
}
const host = server.checkHost || String(server.address || "").replace(/:\d+$/, "");
const port = Number(server.checkPort ?? server.port);
if (!host || !Number.isInteger(port) || port <= 0 || port > 65_535) {
return false;
}
return probe(host, port);
}
async function readServers(probe) {
const data = getJSONData("src/static/gameservers-list.json");
const servers = await Promise.all(
data.servers.map(async (server) => ({
...server,
active: await serverStatus(server, probe),
}))
);
return { ...data, servers };
}
async function checkServersStatus(client) {
const data = getJSONData("src/static/gameservers-list.json");
const newStatus = data.servers.map((server) => server.active);
if (JSON.stringify(newStatus) === JSON.stringify(currentStatus)) {
return;
}
const data = await readServers();
const newStatus = data.servers.map((server) => server.active);
if (JSON.stringify(newStatus) === JSON.stringify(currentStatus)) {
return;
}
await updateMessage(client, data);
currentStatus = newStatus;
return true;
}
currentStatus = newStatus;
return true;
}
async function updateMessage(client, data) {
var newMessage = `Hello 😺 ! Voila les serveurs de jeux qu'on a chez nous :\n\n`;
data.servers.forEach((server) => {
newMessage =
newMessage +
"```ansi\n" +
`${server.game} : ` +
`${server.active ? "Online" : "Offline"}\n` +
`${server.address}\n` +
"```";
});
var newMessage = `Hello 😺 ! Voila les serveurs de jeux qu'on a chez nous :\n\n`;
data.servers.forEach((server) => {
newMessage =
newMessage +
"```ansi\n" +
`${server.game} : ` +
`${server.active ? "[2;32mOnline[0m" : "[2;31mOffline[0m"}\n` +
`${server.address}\n` +
"```";
});
newMessage =
newMessage +
`\nPour mettre en ligne un serveur, faut voir avec <@${config.shinuwaUserId}> , c'est lui qui gère ca !\n`;
newMessage +
`\nPour mettre en ligne un serveur, faut voir avec <@${config.shinuwaUserId}> , c'est lui qui gère ca !\n`;
const channel = client.channels.cache.get(config.textChannelId);
if (!channel?.isTextBased()) {
throw new Error("Salon textuel configuré introuvable");
@ -46,16 +90,16 @@ async function updateMessage(client, data) {
}
async function showGameServers(client) {
const data = getJSONData("src/static/gameservers-list.json");
currentStatus = data.servers.map((server) => server.active);
const data = await readServers();
currentStatus = data.servers.map((server) => server.active);
await updateMessage(client, data);
const interval = setInterval(() => {
checkServersStatus(client).catch((error) =>
console.error("Unable to update game server status", error)
);
}, 120000);
}, REFRESH_INTERVAL);
interval.unref();
}
export { showGameServers };
}
export { probeTcp, serverStatus, showGameServers };

View file

@ -1,6 +1,6 @@
import fs from "fs";
import fs from "fs";
import { config } from "../config.js";
async function changeVoiceStatus(client, status, members) {
const changeStatus = async (type, value, selectedMembers) => {
const operations = [];
@ -16,7 +16,15 @@ async function changeVoiceStatus(client, status, members) {
}
break;
}
await Promise.all(operations);
// Un membre qui quitte le salon pendant l'opération ne doit pas faire échouer les autres.
const results = await Promise.allSettled(operations);
const failures = results.filter((result) => result.status === "rejected");
if (failures.length > 0) {
console.error(
`changeVoiceStatus: ${failures.length} member(s) could not be updated`,
failures[0].reason
);
}
};
const voiceChannel = client.channels.cache.get(config.voiceChannelId);
@ -48,18 +56,18 @@ async function changeVoiceStatus(client, status, members) {
throw new Error(`Statut vocal inconnu : ${status}`);
}
}
function getJSONData(file) {
const jsonFile = fs.readFileSync(file);
const data = JSON.parse(jsonFile);
return data;
}
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function getJSONData(file) {
const jsonFile = fs.readFileSync(file);
const data = JSON.parse(jsonFile);
return data;
}
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
export {
changeVoiceStatus,
getJSONData,

197
src/media/downloadAudio.js Normal file
View file

@ -0,0 +1,197 @@
import dns from "node:dns";
import fs from "node:fs";
import http from "node:http";
import https from "node:https";
import net from "node:net";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { pipeline } from "node:stream/promises";
const MAX_DOWNLOAD_SIZE = 150 * 1024 * 1024;
const MAX_REDIRECTS = 5;
const SOCKET_TIMEOUT = 30_000;
const TOTAL_TIMEOUT = 5 * 60_000;
// Adresses jamais contactées : le bot tourne sur un réseau qui héberge d'autres services, et
// l'URL vient d'un utilisateur (protection contre la falsification de requêtes côté serveur).
const blockedAddresses = new net.BlockList();
for (const [network, prefix] of [
["0.0.0.0", 8],
["10.0.0.0", 8],
["100.64.0.0", 10],
["127.0.0.0", 8],
["169.254.0.0", 16],
["172.16.0.0", 12],
["192.0.0.0", 24],
["192.168.0.0", 16],
["198.18.0.0", 15],
["224.0.0.0", 4],
["240.0.0.0", 4],
]) {
blockedAddresses.addSubnet(network, prefix, "ipv4");
}
for (const [network, prefix] of [
["::", 128],
["::1", 128],
["fc00::", 7],
["fe80::", 10],
["ff00::", 8],
["64:ff9b::", 96],
["2002::", 16],
]) {
blockedAddresses.addSubnet(network, prefix, "ipv6");
}
function downloadError(message, status = 400) {
const error = new Error(message);
error.status = status;
return error;
}
function isBlockedAddress(address) {
const family = net.isIP(address);
if (family === 0) return true;
if (family === 6) {
// Adresse IPv4 écrite en IPv6 (::ffff:10.0.0.1) : on vérifie la partie IPv4.
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address);
if (mapped) return blockedAddresses.check(mapped[1], "ipv4");
return blockedAddresses.check(address, "ipv6");
}
return blockedAddresses.check(address, "ipv4");
}
// Résolution DNS qui refuse les adresses internes. Elle est appelée par la connexion elle-même :
// l'adresse vérifiée est celle qu'on contacte (pas de changement entre vérification et usage).
function safeLookup(hostname, options, callback) {
dns.lookup(hostname, { ...options, all: true }, (error, addresses) => {
if (error) return callback(error);
const allowed = addresses.filter(({ address }) => !isBlockedAddress(address));
if (allowed.length === 0) {
return callback(downloadError("Adresse non autorisée"));
}
if (options.all) return callback(null, allowed);
return callback(null, allowed[0].address, allowed[0].family);
});
}
function parseUrl(value) {
let url;
try {
url = new URL(value);
} catch {
throw downloadError("Lien invalide");
}
if (url.protocol !== "https:" && url.protocol !== "http:") {
throw downloadError("Seuls les liens http et https sont acceptés");
}
if (url.username || url.password) {
throw downloadError("Les liens avec identifiants ne sont pas acceptés");
}
// Les adresses IP écrites en clair ne passent pas par la résolution DNS : on les vérifie ici.
const hostname = url.hostname.replace(/^\[|\]$/g, "");
if (net.isIP(hostname) && isBlockedAddress(hostname)) {
throw downloadError("Adresse non autorisée");
}
return url;
}
function fileNameFrom(response, url) {
const disposition = response.headers["content-disposition"] || "";
const encoded = /filename\*=UTF-8''([^;]+)/i.exec(disposition)?.[1];
const plain = /filename="?([^";]+)"?/i.exec(disposition)?.[1];
let name = encoded || plain || path.posix.basename(url.pathname);
try {
name = decodeURIComponent(name);
} catch {
// Nom laissé tel quel.
}
name = path.basename(name).replace(/[\u0000-\u001f]/g, "").trim().slice(0, 255);
return name || "audio";
}
function request(url, { signal, lookup }) {
const client = url.protocol === "https:" ? https : http;
return new Promise((resolve, reject) => {
const req = client.get(
url,
{
lookup,
signal,
timeout: SOCKET_TIMEOUT,
headers: { "user-agent": "palico-bot", accept: "audio/*, */*;q=0.5" },
},
resolve
);
req.on("timeout", () => req.destroy(downloadError("Le serveur distant ne répond pas", 504)));
req.on("error", reject);
});
}
// Télécharge un fichier dans destinationDir et renvoie un objet de la même forme qu'un fichier
// reçu par multer ({ path, originalname, size, mimetype }).
async function downloadAudio(
value,
{ destinationDir, maxSize = MAX_DOWNLOAD_SIZE, lookup = safeLookup } = {}
) {
let url = parseUrl(value);
const signal = AbortSignal.timeout(TOTAL_TIMEOUT);
for (let redirects = 0; ; redirects++) {
let response;
try {
response = await request(url, { signal, lookup });
} catch (error) {
if (error.status) throw error;
throw downloadError(`Téléchargement impossible : ${error.message}`, 502);
}
const status = response.statusCode;
if (status >= 300 && status < 400 && response.headers.location) {
response.resume();
if (redirects >= MAX_REDIRECTS) {
throw downloadError("Trop de redirections", 502);
}
url = parseUrl(new URL(response.headers.location, url).href);
continue;
}
if (status !== 200) {
response.resume();
throw downloadError(`Le serveur distant a répondu ${status}`, 502);
}
const announced = Number(response.headers["content-length"]);
if (Number.isFinite(announced) && announced > maxSize) {
response.destroy();
throw downloadError("Fichier trop volumineux (150 Mo au plus)", 413);
}
const filePath = path.join(destinationDir, `download-${randomUUID()}`);
let size = 0;
response.on("data", (chunk) => {
size += chunk.length;
if (size > maxSize) {
response.destroy(downloadError("Fichier trop volumineux (150 Mo au plus)", 413));
}
});
try {
await pipeline(response, fs.createWriteStream(filePath));
} catch (error) {
fs.rmSync(filePath, { force: true });
if (error.status) throw error;
throw downloadError(`Téléchargement interrompu : ${error.message}`, 502);
}
return {
path: filePath,
originalname: fileNameFrom(response, url),
size,
mimetype: String(response.headers["content-type"] || "application/octet-stream")
.split(";")[0]
.trim(),
};
}
}
export { downloadAudio, isBlockedAddress, safeLookup };

View file

@ -1,35 +1,134 @@
import { execFile } from "node:child_process";
import { execFile, spawn } from "node:child_process";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
async function validateAudioFile(filePath) {
// Normalisation du volume (EBU R128, mode dynamique en une passe) : tous les morceaux sortent
// au même niveau, quel que soit le fichier d'origine.
const LOUDNORM_FILTER = "loudnorm=I=-16:TP=-1.5:LRA=11";
const MAX_STDERR_LENGTH = 4_000;
function cleanTag(value) {
if (typeof value !== "string") return null;
const cleaned = value.replace(/[\u0000-\u001f]/g, "").trim().slice(0, 200);
return cleaned || null;
}
// Les noms des tags varient selon le format (« title » en ID3, « TITLE » en Vorbis) : on les
// met en minuscules. Les tags Ogg sont portés par le flux, les autres par le conteneur.
function lowerCaseTags(...tagSets) {
const tags = {};
for (const set of tagSets) {
for (const [key, value] of Object.entries(set || {})) {
tags[key.toLowerCase()] ??= value;
}
}
return tags;
}
// Vérifie qu'un fichier contient une piste audio et lit sa durée (secondes) et ses tags.
async function probeAudioFile(filePath) {
let parsed;
try {
const { stdout } = await execFileAsync(
"ffprobe",
[
"-v",
"error",
"-select_streams",
"a:0",
"-show_entries",
"stream=codec_type",
"format=duration:format_tags:stream=codec_type:stream_tags",
"-of",
"default=noprint_wrappers=1:nokey=1",
"json",
filePath,
],
{ timeout: 15_000, maxBuffer: 1024 * 1024 }
);
if (stdout.trim() !== "audio") {
throw new Error("Aucune piste audio détectée");
}
parsed = JSON.parse(stdout);
} catch (error) {
const validationError = new Error("Le fichier fourni n'est pas un audio valide");
validationError.status = 400;
validationError.cause = error;
throw validationError;
throw invalidAudioError(error);
}
const audioStream = parsed.streams?.find((stream) => stream.codec_type === "audio");
if (!audioStream) {
throw invalidAudioError(new Error("Aucune piste audio détectée"));
}
const duration = Number(parsed.format?.duration);
const tags = lowerCaseTags(parsed.format?.tags, audioStream.tags);
return {
duration: Number.isFinite(duration) && duration > 0 ? Math.round(duration) : null,
title: cleanTag(tags.title),
artist: cleanTag(tags.artist),
};
}
export { validateAudioFile };
function invalidAudioError(cause) {
const error = new Error("Le fichier fourni n'est pas un audio valide");
error.status = 400;
error.cause = cause;
return error;
}
async function validateAudioFile(filePath) {
await probeAudioFile(filePath);
}
// Décode le fichier, normalise le volume et encode en Ogg Opus avec le ffmpeg natif : Discord
// reçoit l'Opus tel quel, sans réencodage en JavaScript. Fermer le flux arrête ffmpeg.
function createOpusStream(filePath, { spawnProcess = spawn } = {}) {
const ffmpeg = spawnProcess(
"ffmpeg",
[
"-hide_banner",
"-loglevel",
"error",
"-i",
filePath,
"-map",
"0:a:0",
"-vn",
"-af",
LOUDNORM_FILTER,
"-c:a",
"libopus",
"-b:a",
"128k",
"-ar",
"48000",
"-ac",
"2",
"-f",
"ogg",
"pipe:1",
],
{ stdio: ["ignore", "pipe", "pipe"] }
);
const output = ffmpeg.stdout;
let stderr = "";
ffmpeg.stderr.on("data", (chunk) => {
if (stderr.length < MAX_STDERR_LENGTH) {
stderr += chunk.toString();
}
});
ffmpeg.on("error", (error) => {
output.destroy(error);
});
ffmpeg.on("close", (code, signal) => {
if (code !== 0 && signal === null && !output.destroyed) {
output.destroy(
new Error(`ffmpeg exited with code ${code}: ${stderr.trim().slice(0, 500)}`)
);
}
});
output.on("close", () => {
if (ffmpeg.exitCode === null && ffmpeg.signalCode === null) {
ffmpeg.kill("SIGKILL");
}
});
return output;
}
export { LOUDNORM_FILTER, createOpusStream, probeAudioFile, validateAudioFile };

60
src/music/ingest.js Normal file
View file

@ -0,0 +1,60 @@
import { probeAudioFile } from "../media/validateAudioFile.js";
import {
discardUploadedFile,
registerUploadedFile,
} from "../web/storage/storageManager.js";
function cleanText(value, maxLength) {
return String(value ?? "")
.replace(/[\u0000-\u001f]/g, "")
.trim()
.slice(0, maxLength);
}
// Titre par défaut : « Artiste - Titre » d'après les tags, sinon le nom du fichier sans
// son extension.
function defaultTitle({ title, artist }, originalName) {
if (title) {
return (artist ? `${artist} - ${title}` : title).slice(0, 200);
}
return originalName.replace(/\.[a-z0-9]{1,10}$/i, "").slice(0, 200) || originalName;
}
// Ajoute un fichier déjà présent dans storage/temp (upload, lien, pièce jointe Discord) :
// vérifie que c'est de l'audio, l'enregistre (bibliothèque si permanent) et le met en file.
// En cas d'échec, le fichier est supprimé.
async function ingestAudioFile(
file,
{ permanent = false, enqueue = true, uploader, title } = {},
{ queue, probe = probeAudioFile }
) {
try {
if (!permanent && !enqueue) {
const error = new Error("Un fichier temporaire doit être ajouté à la file d'attente");
error.status = 400;
throw error;
}
const metadata = await probe(file.path);
const track = registerUploadedFile(file, {
permanent,
uploader: cleanText(uploader, 80) || "inconnu",
title: cleanText(title, 200) || defaultTitle(metadata, file.originalname),
duration: metadata.duration,
artist: metadata.artist,
});
if (permanent) {
queue.emit("libraryUpdate");
}
if (enqueue) {
queue.enqueue(track);
}
return track;
} catch (error) {
discardUploadedFile(file);
throw error;
}
}
export { defaultTitle, ingestAudioFile };

View file

@ -1,8 +1,9 @@
import fs from "fs";
import { EventEmitter } from "events";
import { randomUUID } from "node:crypto";
import {
AudioPlayerStatus,
NoSubscriberBehavior,
StreamType,
VoiceConnectionStatus,
createAudioPlayer,
createAudioResource,
@ -11,6 +12,7 @@ import {
} from "@discordjs/voice";
import { Events } from "discord.js";
import { config } from "../config.js";
import { createOpusStream } from "../media/validateAudioFile.js";
import { serializeTrack, serializeTracks } from "../web/serializers.js";
import {
deleteTrackFile,
@ -18,17 +20,35 @@ import {
} from "../web/storage/storageManager.js";
const AUTO_DISCONNECT_DELAY = 5 * 60 * 1000;
// Délais entre les nouvelles tentatives quand le salon vocal est injoignable. Au-delà, la
// file attend une action (ajout d'un morceau, bouton Play).
const CONNECT_RETRY_DELAYS = [5_000, 15_000, 30_000, 60_000, 60_000];
class MusicQueue extends EventEmitter {
constructor(client) {
// persistence : { load() → état | null, save(état) } pour garder la file d'un démarrage à
// l'autre (voir queuePersistence.js). Sans elle, la file est perdue à l'arrêt.
constructor(
client,
{ retryDelays = CONNECT_RETRY_DELAYS, persistence = null } = {}
) {
super();
this.setMaxListeners(50); // une écoute par page web ouverte (flux d'événements)
this.client = client;
this.queue = [];
this.currentTrack = null;
this.loop = false;
// Le morceau en cours ne doit pas revenir en fin de file en mode boucle (retiré, en
// erreur, file vidée).
this.discardCurrent = false;
this.persistence = persistence;
this.saveTimeout = null;
this.connection = null;
this.playbackStatus = AudioPlayerStatus.Idle;
this.idleDisconnectTimeout = null;
this.aloneDisconnectTimeout = null;
this.connectRetryTimeout = null;
this.connectFailures = 0;
this.retryDelays = retryDelays;
this.suspendedForAlone = false;
this.playNextPromise = null;
this.shuttingDown = false;
@ -48,24 +68,33 @@ class MusicQueue extends EventEmitter {
this.client.on(Events.VoiceStateUpdate, this.voiceStateListener);
this.audioPlayer.on(AudioPlayerStatus.Idle, () => {
if (this.currentTrack) {
handleTrackCompletion(this.currentTrack);
}
const finished = this.currentTrack;
this.currentTrack = null;
if (finished) {
if (this.loop && !this.discardCurrent && !this.shuttingDown) {
// Mode boucle : le morceau repart en fin de file, fichier conservé.
const { startedAt: _startedAt, ...track } = finished;
this.queue.push({ ...track, id: randomUUID() });
} else {
handleTrackCompletion(finished);
}
}
this.discardCurrent = false;
if (!this.shuttingDown) {
void this.playNext();
}
});
// Après une erreur, le player passe toujours en Idle : le gestionnaire ci-dessus
// termine le morceau et lance le suivant (sans le remettre en boucle).
this.audioPlayer.on("error", (error) => {
console.error("Audio player encountered an error", error);
handleTrackCompletion(this.currentTrack);
this.currentTrack = null;
if (!this.shuttingDown) {
void this.playNext();
}
this.discardCurrent = true;
});
this.on("queueUpdate", () => this.scheduleSave());
this.restore();
this.audioPlayer.on("stateChange", (oldState, newState) => {
this.playbackStatus = newState.status;
this.emit("queueUpdate", this.snapshot());
@ -77,9 +106,21 @@ class MusicQueue extends EventEmitter {
current: serializeTrack(this.currentTrack),
upcoming: serializeTracks(this.queue),
status: this.playbackStatus,
loop: this.loop,
// Millisecondes déjà jouées du morceau en cours (pauses exclues).
position: this.audioPlayer?.state?.resource?.playbackDuration ?? 0,
};
}
// Fichiers encore utiles (file d'attente et morceau en cours), à ne pas nettoyer.
inUsePaths() {
return new Set(
[this.currentTrack, ...this.queue]
.map((track) => track?.path)
.filter(Boolean)
);
}
async ensureConnection() {
if (this.connection) {
if (
@ -129,7 +170,7 @@ class MusicQueue extends EventEmitter {
]);
} catch {
if (this.connection === connection) {
this.destroyConnection("voice connection lost");
this.destroyConnection("voice connection lost", { requeue: true });
}
}
});
@ -153,6 +194,10 @@ class MusicQueue extends EventEmitter {
enqueue(track) {
this.queue.push(track);
// Ajouter un morceau est une demande de lecture explicite : elle lève la suspension
// (bot parti faute d'auditeurs) et relance les tentatives de connexion.
this.suspendedForAlone = false;
this.connectFailures = 0;
this.cancelIdleDisconnect();
this.emit("queueUpdate", this.snapshot());
if (!this.currentTrack) {
@ -174,7 +219,9 @@ class MusicQueue extends EventEmitter {
}
async runPlayNext() {
if (this.suspendedForAlone) {
this.cancelConnectRetry();
if (this.shuttingDown || this.suspendedForAlone) {
return;
}
@ -189,26 +236,27 @@ class MusicQueue extends EventEmitter {
try {
await this.ensureConnection();
this.connectFailures = 0;
} catch (error) {
console.error("Unable to connect to the configured voice channel", error);
this.currentTrack = null;
this.scheduleConnectRetry();
return;
}
if (
this.shuttingDown ||
this.suspendedForAlone ||
this.queue[0]?.id !== nextTrack.id
) {
if (this.shuttingDown || this.suspendedForAlone) {
return;
}
// La file a pu changer pendant la connexion (morceau retiré ou déplacé) : on repart
// de la nouvelle tête de file au lieu d'abandonner.
if (this.queue[0]?.id !== nextTrack.id) {
return this.runPlayNext();
}
try {
this.queue.shift();
const stream = fs.createReadStream(nextTrack.path);
const resource = createAudioResource(stream, {
inlineVolume: true,
});
const resource = this.createResource(nextTrack);
this.currentTrack = {
...nextTrack,
@ -225,12 +273,48 @@ class MusicQueue extends EventEmitter {
}
}
createResource(track) {
return createAudioResource(createOpusStream(track.path), {
inputType: StreamType.OggOpus,
});
}
scheduleConnectRetry() {
if (this.shuttingDown || this.queue.length === 0 || this.connectRetryTimeout) {
return;
}
if (this.connectFailures >= this.retryDelays.length) {
console.error(
`[${new Date().toLocaleString()}] MusicQueue gave up connecting after ${this.connectFailures} retries; the next enqueue or Play will try again`
);
return;
}
const delay = this.retryDelays[this.connectFailures];
this.connectFailures += 1;
this.connectRetryTimeout = setTimeout(() => {
this.connectRetryTimeout = null;
void this.playNext();
}, delay);
}
cancelConnectRetry() {
if (this.connectRetryTimeout) {
clearTimeout(this.connectRetryTimeout);
this.connectRetryTimeout = null;
}
}
async remove(trackId) {
const index = this.queue.findIndex((track) => track.id === trackId);
if (index === -1) {
if (this.currentTrack && this.currentTrack.id === trackId) {
// skip() repasse le player en Idle tout de suite, ce qui efface currentTrack.
const removed = this.currentTrack;
this.discardCurrent = true;
this.skip();
return this.currentTrack;
return removed;
}
return null;
}
@ -262,12 +346,43 @@ class MusicQueue extends EventEmitter {
}
stop() {
this.cancelConnectRetry();
this.queue.forEach((track) => deleteTrackFile(track));
this.queue = [];
this.discardCurrent = Boolean(this.currentTrack);
this.audioPlayer.stop(true);
this.emit("queueUpdate", this.snapshot());
}
// Mélange les morceaux à venir (le morceau en cours n'est pas touché).
shuffle() {
for (let index = this.queue.length - 1; index > 0; index--) {
const randomIndex = Math.floor(Math.random() * (index + 1));
[this.queue[index], this.queue[randomIndex]] = [
this.queue[randomIndex],
this.queue[index],
];
}
this.emit("queueUpdate", this.snapshot());
return this.snapshot();
}
setLoop(enabled) {
this.loop = Boolean(enabled);
this.emit("queueUpdate", this.snapshot());
return this.snapshot();
}
// Met à jour le titre des morceaux en file venant d'une entrée de bibliothèque renommée.
renameLibraryTrack(libraryTrackId, title) {
for (const track of [this.currentTrack, ...this.queue]) {
if (track && track.libraryTrackId === libraryTrackId) {
track.title = title;
}
}
this.emit("queueUpdate", this.snapshot());
}
pause() {
this.audioPlayer.pause(true);
}
@ -278,6 +393,7 @@ class MusicQueue extends EventEmitter {
start() {
this.suspendedForAlone = false;
this.connectFailures = 0;
this.cancelIdleDisconnect();
if (!this.currentTrack) {
return this.playNext();
@ -304,6 +420,7 @@ class MusicQueue extends EventEmitter {
this.currentTrack &&
this.currentTrack.libraryTrackId === libraryTrackId
) {
this.discardCurrent = true;
this.skip();
}
@ -314,7 +431,9 @@ class MusicQueue extends EventEmitter {
return removed;
}
destroyConnection(reason, { suspend = false } = {}) {
// requeue : remet le morceau interrompu en tête de file (il reprendra du début) au lieu
// de le perdre, quand la coupure ne vient pas d'une demande d'arrêt.
destroyConnection(reason, { suspend = false, requeue = false } = {}) {
if (!this.connection && this.playbackStatus === AudioPlayerStatus.Idle) {
return;
}
@ -328,6 +447,11 @@ class MusicQueue extends EventEmitter {
const interruptedTrack = this.currentTrack;
this.currentTrack = null;
const requeued = Boolean(requeue && interruptedTrack);
if (requeued) {
const { startedAt: _startedAt, ...track } = interruptedTrack;
this.queue.unshift(track);
}
if (this.connection) {
try {
@ -344,7 +468,9 @@ class MusicQueue extends EventEmitter {
console.error("Failed to stop audio player", error);
}
handleTrackCompletion(interruptedTrack);
if (!requeued) {
handleTrackCompletion(interruptedTrack);
}
this.emit("queueUpdate", this.snapshot());
console.log(
`[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})`
@ -384,7 +510,7 @@ class MusicQueue extends EventEmitter {
this.aloneDisconnectTimeout = setTimeout(() => {
this.aloneDisconnectTimeout = null;
if (this.connection && this.isBotAlone()) {
this.destroyConnection("alone timeout", { suspend: true });
this.destroyConnection("alone timeout", { suspend: true, requeue: true });
}
}, AUTO_DISCONNECT_DELAY);
}
@ -399,6 +525,11 @@ class MusicQueue extends EventEmitter {
evaluateAloneStatus() {
if (!this.connection) {
this.cancelAloneDisconnect();
// Parti faute d'auditeurs : revenir dès que quelqu'un rejoint le salon.
if (this.suspendedForAlone && this.queue.length > 0 && this.hasListeners()) {
this.suspendedForAlone = false;
void this.playNext();
}
return;
}
@ -414,35 +545,109 @@ class MusicQueue extends EventEmitter {
}
}
isBotAlone() {
// Membres humains du salon configuré, sans le bot lui-même ni les autres bots.
listeners() {
const channel = this.client.channels.cache.get(config.voiceChannelId);
if (!channel) {
return false;
}
const clientId = this.client.user?.id;
if (!clientId) {
return false;
if (!channel || !clientId) {
return null;
}
if (!channel.members.has(clientId)) {
return false;
}
const others = channel.members.filter((member) => member.id !== clientId);
return others.size === 0;
return [...channel.members.values()].filter(
(member) => member.id !== clientId && !member.user?.bot
);
}
hasListeners() {
return (this.listeners()?.length ?? 0) > 0;
}
isBotAlone() {
const channel = this.client.channels.cache.get(config.voiceChannelId);
const clientId = this.client.user?.id;
if (!channel || !clientId || !channel.members.has(clientId)) {
return false;
}
return this.listeners().length === 0;
}
// Avec la persistance, la file (morceau en cours en tête) est enregistrée et ses fichiers
// gardés pour le prochain démarrage ; sans elle, les fichiers temporaires sont supprimés.
shutdown() {
this.shuttingDown = true;
this.cancelIdleDisconnect();
this.cancelAloneDisconnect();
this.cancelConnectRetry();
clearTimeout(this.saveTimeout);
this.client.off(Events.VoiceStateUpdate, this.voiceStateListener);
if (this.persistence) {
this.destroyConnection("shutdown", { requeue: true });
this.save();
return;
}
this.queue.forEach((track) => deleteTrackFile(track));
this.queue = [];
this.destroyConnection("shutdown");
}
persistedState() {
return {
// Le morceau en cours reprendra du début, en tête de file.
queue: [this.currentTrack, ...this.queue]
.filter(Boolean)
.map(({ startedAt: _startedAt, ...track }) => track),
loop: this.loop,
};
}
scheduleSave() {
if (!this.persistence || this.saveTimeout || this.shuttingDown) {
return;
}
this.saveTimeout = setTimeout(() => {
this.saveTimeout = null;
this.save();
}, 500);
this.saveTimeout.unref?.();
}
save() {
if (!this.persistence) return;
try {
this.persistence.save(this.persistedState());
} catch (error) {
console.error("Unable to save the music queue", error);
}
}
// Recharge la file enregistrée. Elle reste en attente (comme quand le bot est parti faute
// d'auditeurs) : la lecture reprend dès qu'il y a quelqu'un dans le salon, avec un ajout
// ou avec le bouton Play.
restore() {
if (!this.persistence) return;
let state;
try {
state = this.persistence.load();
} catch (error) {
console.error("Unable to restore the music queue", error);
return;
}
if (!state) return;
this.queue = (Array.isArray(state.queue) ? state.queue : []).filter(
(track) => track && typeof track.id === "string" && typeof track.path === "string"
);
this.loop = Boolean(state.loop);
if (this.queue.length > 0) {
this.suspendedForAlone = true;
console.log(
`[${new Date().toLocaleString()}] MusicQueue restored ${this.queue.length} track(s)`
);
}
}
}
export { MusicQueue };

View file

@ -0,0 +1,27 @@
import fs from "node:fs";
import path from "node:path";
// Enregistre la file dans un fichier JSON (écriture atomique) et ne recharge que les morceaux
// dont le fichier existe encore.
function createQueuePersistence(filePath) {
return {
load() {
if (!fs.existsSync(filePath)) return null;
const state = JSON.parse(fs.readFileSync(filePath, "utf8"));
return {
...state,
queue: (state.queue || []).filter(
(track) => typeof track?.path === "string" && fs.existsSync(track.path)
),
};
},
save(state) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
const temporaryFile = `${filePath}.${process.pid}.tmp`;
fs.writeFileSync(temporaryFile, JSON.stringify(state, null, 2));
fs.renameSync(temporaryFile, filePath);
},
};
}
export { createQueuePersistence };

View file

@ -1,10 +1,23 @@
{
"servers": [
{
"game": "Nom du jeu",
"game": "Nom du jeu (état saisi à la main)",
"address": "games.example.com:25565",
"port": 25565,
"active": false
},
{
"game": "Nom du jeu (état vérifié par le bot, en TCP)",
"address": "games.example.com:25566",
"port": 25566,
"check": true
},
{
"game": "Jeu en UDP (vérifié sur son port RCON, en TCP)",
"address": "games.example.com:8211",
"port": 8211,
"check": true,
"checkPort": 25575
}
]
}

78
src/web/auth/session.js Normal file
View file

@ -0,0 +1,78 @@
import { createHmac, timingSafeEqual } from "node:crypto";
const SESSION_COOKIE = "palico_session";
const STATE_COOKIE = "palico_oauth_state";
const SESSION_DURATION = 30 * 24 * 60 * 60 * 1000;
function sign(payload, secret) {
return createHmac("sha256", secret).update(payload).digest("base64url");
}
// Jeton de session sans stockage côté serveur : « données.signature », signé par HMAC.
// Changer SESSION_SECRET déconnecte tout le monde.
function createSessionToken({ id, name }, secret, now = Date.now()) {
const payload = Buffer.from(
JSON.stringify({ sub: id, name, exp: now + SESSION_DURATION })
).toString("base64url");
return `${payload}.${sign(payload, secret)}`;
}
function readSessionToken(token, secret, now = Date.now()) {
if (typeof token !== "string" || !secret) return null;
const [payload, signature, extra] = token.split(".");
if (!payload || !signature || extra !== undefined) return null;
const expected = Buffer.from(sign(payload, secret));
const received = Buffer.from(signature);
if (expected.length !== received.length || !timingSafeEqual(expected, received)) {
return null;
}
try {
const data = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
if (typeof data.sub !== "string" || typeof data.exp !== "number" || data.exp < now) {
return null;
}
return { id: data.sub, name: String(data.name || "").slice(0, 80) };
} catch {
return null;
}
}
function parseCookies(header = "") {
const cookies = {};
for (const part of header.split(";")) {
const index = part.indexOf("=");
if (index === -1) continue;
const name = part.slice(0, index).trim();
try {
cookies[name] = decodeURIComponent(part.slice(index + 1).trim());
} catch {
// Cookie mal formé : ignoré.
}
}
return cookies;
}
function serializeCookie(name, value, { maxAge, path = "/", secure = true } = {}) {
return [
`${name}=${encodeURIComponent(value)}`,
`Path=${path}`,
"HttpOnly",
"SameSite=Lax",
secure ? "Secure" : null,
maxAge !== undefined ? `Max-Age=${Math.floor(maxAge / 1000)}` : null,
]
.filter(Boolean)
.join("; ");
}
export {
SESSION_COOKIE,
SESSION_DURATION,
STATE_COOKIE,
createSessionToken,
parseCookies,
readSessionToken,
serializeCookie,
};

View file

@ -30,6 +30,25 @@ function createBearerAuth(getExpectedKey) {
const authMiddleware = createBearerAuth(() => config.webApiKey);
// API du jukebox : la clé (en-tête Authorization) ou une session Discord (cookie, voir
// sessionMiddleware). Avec le cookie, une requête qui modifie quelque chose doit venir du site
// lui-même (en-tête Origin), en plus de la protection SameSite du cookie.
function createJukeboxAuth({ publicUrl } = {}) {
const allowedOrigin = publicUrl ? new URL(publicUrl).origin : null;
return function jukeboxAuth(req, res, next) {
if (req.headers.authorization || !req.user) {
return authMiddleware(req, res, next);
}
const safeMethod = req.method === "GET" || req.method === "HEAD";
const origin = req.headers.origin;
if (!safeMethod && origin && origin !== allowedOrigin) {
return res.status(403).json({ error: "Origine refusée" });
}
return next();
};
}
const LOOPBACK_ADDRESSES = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
function isLoopbackAddress(address) {
@ -45,4 +64,4 @@ function localOnly(req, res, next) {
return res.status(403).json({ error: "Route réservée aux applications locales", code: "LOCAL_ONLY" });
}
export { authMiddleware, createBearerAuth, isLoopbackAddress, localOnly };
export { authMiddleware, createBearerAuth, createJukeboxAuth, isLoopbackAddress, localOnly };

125
src/web/routes/auth.js Normal file
View file

@ -0,0 +1,125 @@
import { Router } from "express";
import { randomBytes } from "node:crypto";
import {
SESSION_COOKIE,
SESSION_DURATION,
STATE_COOKIE,
createSessionToken,
parseCookies,
readSessionToken,
serializeCookie,
} from "../auth/session.js";
const DISCORD_API = "https://discord.com/api/v10";
const STATE_DURATION = 10 * 60 * 1000;
// Lit la session (cookie signé) et place l'utilisateur dans req.user.
function sessionMiddleware(oauth) {
return function readSession(req, _res, next) {
if (oauth.enabled) {
const token = parseCookies(req.headers.cookie)[SESSION_COOKIE];
req.user = readSessionToken(token, oauth.sessionSecret);
}
next();
};
}
// Connexion avec Discord (OAuth2, portée « identify ») réservée aux membres du serveur.
// oauth : { enabled, clientId, clientSecret, publicUrl, sessionSecret }.
// findMember(userId) renvoie le membre du serveur ou null.
function authRouter({ oauth, findMember, fetchImpl = fetch }) {
const router = Router();
const secure = oauth.enabled && new URL(oauth.publicUrl).protocol === "https:";
const redirectUri = oauth.enabled ? `${oauth.publicUrl}/auth/discord/callback` : null;
const fail = (res, reason) => res.redirect(303, `/jukebox/?login=${reason}`);
router.get("/me", (req, res) => {
res.set("Cache-Control", "no-store");
res.json({ oauthEnabled: oauth.enabled, user: req.user ?? null });
});
router.get("/discord", (req, res) => {
if (!oauth.enabled) {
return res.status(404).json({ error: "Connexion avec Discord désactivée" });
}
const state = randomBytes(24).toString("base64url");
res.append(
"Set-Cookie",
serializeCookie(STATE_COOKIE, state, { maxAge: STATE_DURATION, path: "/auth", secure })
);
const params = new URLSearchParams({
client_id: oauth.clientId,
response_type: "code",
redirect_uri: redirectUri,
scope: "identify",
state,
prompt: "none",
});
res.redirect(303, `https://discord.com/oauth2/authorize?${params}`);
});
router.get("/discord/callback", async (req, res) => {
if (!oauth.enabled) {
return res.status(404).json({ error: "Connexion avec Discord désactivée" });
}
const expectedState = parseCookies(req.headers.cookie)[STATE_COOKIE];
res.append(
"Set-Cookie",
serializeCookie(STATE_COOKIE, "", { maxAge: 0, path: "/auth", secure })
);
if (req.query.error) return fail(res, "denied");
if (!expectedState || req.query.state !== expectedState) return fail(res, "state");
if (typeof req.query.code !== "string") return fail(res, "failed");
try {
const tokenResponse = await fetchImpl(`${DISCORD_API}/oauth2/token`, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: oauth.clientId,
client_secret: oauth.clientSecret,
grant_type: "authorization_code",
code: req.query.code,
redirect_uri: redirectUri,
}),
});
if (!tokenResponse.ok) throw new Error(`token exchange: ${tokenResponse.status}`);
const { access_token: accessToken } = await tokenResponse.json();
const userResponse = await fetchImpl(`${DISCORD_API}/users/@me`, {
headers: { authorization: `Bearer ${accessToken}` },
});
if (!userResponse.ok) throw new Error(`user lookup: ${userResponse.status}`);
const user = await userResponse.json();
const member = await findMember(user.id);
if (!member) return fail(res, "not-member");
const name = member.displayName || user.global_name || user.username;
res.append(
"Set-Cookie",
serializeCookie(
SESSION_COOKIE,
createSessionToken({ id: user.id, name }, oauth.sessionSecret),
{ maxAge: SESSION_DURATION, secure }
)
);
console.log(`[${new Date().toLocaleString()}] Web login: ${user.id}`);
return res.redirect(303, "/jukebox/");
} catch (error) {
console.error("Discord login failed", error);
return fail(res, "failed");
}
});
router.post("/logout", (req, res) => {
res.append("Set-Cookie", serializeCookie(SESSION_COOKIE, "", { maxAge: 0, secure }));
res.status(204).end();
});
return router;
}
export { authRouter, sessionMiddleware };

41
src/web/routes/events.js Normal file
View file

@ -0,0 +1,41 @@
import { Router } from "express";
const HEARTBEAT_INTERVAL = 25_000;
// Flux d'événements (Server-Sent Events) : « queue » envoie l'état de la file à chaque
// changement, « library » signale que la bibliothèque a changé. La page s'en sert à la place
// d'un rafraîchissement périodique.
function eventsRouter({ queue }) {
const router = Router();
router.get("/", (req, res) => {
res.writeHead(200, {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
});
const send = (event, data) => {
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
};
const onQueueUpdate = (snapshot) => send("queue", snapshot);
const onLibraryUpdate = () => send("library", {});
send("queue", queue.snapshot());
queue.on("queueUpdate", onQueueUpdate);
queue.on("libraryUpdate", onLibraryUpdate);
const heartbeat = setInterval(() => res.write(": ping\n\n"), HEARTBEAT_INTERVAL);
// Fermeture de la connexion (onglet fermé, réseau coupé) : on arrête d'écouter la file.
res.on("close", () => {
clearInterval(heartbeat);
queue.off("queueUpdate", onQueueUpdate);
queue.off("libraryUpdate", onLibraryUpdate);
});
});
return router;
}
export { eventsRouter };

View file

@ -4,6 +4,7 @@ import {
deletePermanentTrack,
findPermanentTrack,
getPermanentLibrary,
updatePermanentTracks,
} from "../storage/storageManager.js";
import { serializeTrack, serializeTracks } from "../serializers.js";
@ -22,9 +23,45 @@ function libraryRouter({ queue }) {
}
queue.removeByLibraryId(track.id);
queue.emit("libraryUpdate");
res.json({ removed: serializeTrack(track) });
});
router.patch("/:libraryId", (req, res) => {
const title = String(req.body?.title ?? "")
.replace(/[\u0000-\u001f]/g, "")
.trim()
.slice(0, 200);
if (!title) {
return res.status(400).json({ error: "Titre manquant" });
}
const [track] = updatePermanentTracks(new Map([[req.params.libraryId, { title }]]));
if (!track) {
return res.status(404).json({ error: "Fichier permanent introuvable" });
}
queue.renameLibraryTrack(track.id, title);
queue.emit("libraryUpdate");
res.json({ track: serializeTrack(track) });
});
// Ajoute toute la bibliothèque à la file, mélangée si shuffle vaut true.
router.post("/enqueue-all", (req, res) => {
const entries = getPermanentLibrary();
if (req.body?.shuffle === true) {
for (let index = entries.length - 1; index > 0; index--) {
const randomIndex = Math.floor(Math.random() * (index + 1));
[entries[index], entries[randomIndex]] = [entries[randomIndex], entries[index]];
}
}
const tracks = entries.map((entry) =>
queue.enqueue(createQueueTrackFromLibrary(entry, req.user?.name ?? req.body?.requestedBy))
);
res.status(201).json({ tracks: serializeTracks(tracks) });
});
router.post("/:libraryId/enqueue", (req, res) => {
const baseTrack = findPermanentTrack(req.params.libraryId);
if (!baseTrack) {
@ -33,7 +70,7 @@ function libraryRouter({ queue }) {
const queueTrack = createQueueTrackFromLibrary(
baseTrack,
req.body?.requestedBy
req.user?.name ?? req.body?.requestedBy
);
queue.enqueue(queueTrack);
res.status(201).json({ track: serializeTrack(queueTrack) });

View file

@ -28,6 +28,17 @@ function playerRouter({ queue }) {
res.json(queue.snapshot());
});
router.post("/shuffle", (req, res) => {
res.json(queue.shuffle());
});
router.post("/loop", (req, res) => {
if (typeof req.body?.enabled !== "boolean") {
return res.status(400).json({ error: "enabled doit être un booléen" });
}
res.json(queue.setLoop(req.body.enabled));
});
return router;
}

View file

@ -22,7 +22,7 @@ function queueRouter({ queue }) {
return res.status(404).json({ error: "Fichier permanent introuvable" });
}
const track = createQueueTrackFromLibrary(libraryTrack, requestedBy);
const track = createQueueTrackFromLibrary(libraryTrack, req.user?.name ?? requestedBy);
queue.enqueue(track);
res.status(201).json({ track: serializeTrack(track) });
});

View file

@ -1,26 +1,13 @@
import { Router } from "express";
import multer from "multer";
import { validateAudioFile } from "../../media/validateAudioFile.js";
import { downloadAudio } from "../../media/downloadAudio.js";
import { ingestAudioFile } from "../../music/ingest.js";
import { serializeTrack } from "../serializers.js";
import {
TEMP_DIR,
discardUploadedFile,
registerUploadedFile,
} from "../storage/storageManager.js";
const ALLOWED_AUDIO_TYPES = new Set([
"audio/aac",
"audio/flac",
"audio/mp4",
"audio/mpeg",
"audio/ogg",
"audio/wav",
"audio/webm",
"audio/x-flac",
"audio/x-m4a",
"audio/x-wav",
]);
import { TEMP_DIR } from "../storage/storageManager.js";
// Pas de filtre sur le type MIME : il vient du navigateur et varie selon le système (un MP3
// peut arriver en « audio/mp3 », un FLAC sans type). Les fichiers refusés disparaissaient sans
// message clair ; ffprobe vérifie le contenu réel après l'envoi.
const upload = multer({
dest: TEMP_DIR,
limits: {
@ -35,55 +22,52 @@ const upload = multer({
callback(error);
return;
}
callback(null, ALLOWED_AUDIO_TYPES.has(file.mimetype));
callback(null, true);
},
});
function uploadsRouter({ queue }) {
const router = Router();
// Connecté avec Discord, le nom vient de la session et non du formulaire.
const options = ({ body, user }) => ({
permanent: body?.permanent === "true" || body?.permanent === true,
enqueue: body?.enqueue !== "false" && body?.enqueue !== false,
uploader: user?.name || body?.uploader || "web-ui",
title: body?.notes,
});
router.post("/", upload.single("file"), async (req, res, next) => {
if (!req.file) {
return res.status(400).json({ error: "Aucun fichier reçu" });
}
const permanent = req.body?.permanent === "true";
const enqueue = req.body?.enqueue !== "false";
const uploader = String(req.body?.uploader || "web-ui")
.replace(/[\u0000-\u001f]/g, "")
.trim()
.slice(0, 80);
const title = String(req.body?.notes || req.file.originalname)
.replace(/[\u0000-\u001f]/g, "")
.trim()
.slice(0, 200);
try {
if (!permanent && !enqueue) {
const error = new Error(
"Un fichier temporaire doit être ajouté à la file d'attente"
);
error.status = 400;
throw error;
}
await validateAudioFile(req.file.path);
const track = registerUploadedFile(req.file, {
permanent,
uploader,
title: title || req.file.originalname,
});
if (enqueue) {
queue.enqueue(track);
}
const track = await ingestAudioFile(req.file, options(req), { queue });
return res.status(201).json({
track: serializeTrack(track),
enqueued: enqueue,
enqueued: options(req).enqueue,
});
} catch (error) {
return next(error);
}
});
// Ajout depuis un lien direct vers un fichier audio : le serveur le télécharge lui-même.
router.post("/url", async (req, res, next) => {
const url = req.body?.url;
if (typeof url !== "string" || url.length > 2_000) {
return res.status(400).json({ error: "Lien manquant" });
}
try {
const file = await downloadAudio(url, { destinationDir: TEMP_DIR });
const track = await ingestAudioFile(file, options(req), { queue });
return res.status(201).json({
track: serializeTrack(track),
enqueued: options(req).enqueue,
});
} catch (error) {
discardUploadedFile(req.file);
return next(error);
}
});

View file

@ -5,15 +5,18 @@ import multer from "multer";
import path from "path";
import { config } from "../config.js";
import {
authMiddleware,
createBearerAuth,
createJukeboxAuth,
localOnly,
} from "./middlewares/auth.js";
import { authRouter, sessionMiddleware } from "./routes/auth.js";
import { eventsRouter } from "./routes/events.js";
import { libraryRouter } from "./routes/library.js";
import { notificationsRouter } from "./routes/notifications.js";
import { playerRouter } from "./routes/player.js";
import { queueRouter } from "./routes/queue.js";
import { uploadsRouter } from "./routes/uploads.js";
import { backfillLibraryMetadata } from "./storage/libraryMetadata.js";
import {
cleanupTemporaryFiles,
ensureStorageLayout,
@ -41,18 +44,54 @@ function authFailureLimit() {
});
}
const UNKNOWN_MEMBER = 10007;
// Membre du serveur Discord configuré, ou null s'il n'en fait pas partie.
function guildMemberFinder(client) {
return async (userId) => {
const guild =
client.guilds?.cache.get(config.discordGuildId) ??
(await client.guilds.fetch(config.discordGuildId));
try {
return await guild.members.fetch(userId);
} catch (error) {
if (error?.code === UNKNOWN_MEMBER) return null;
throw error;
}
};
}
function createApp(
dependencies,
{ notificationsApiKey = config.notificationsApiKey } = {}
{
notificationsApiKey = config.notificationsApiKey,
oauth = {
enabled: config.discordOAuthEnabled,
clientId: config.applicationId,
clientSecret: config.discordClientSecret,
publicUrl: config.webPublicUrl,
sessionSecret: config.sessionSecret,
},
findMember = guildMemberFinder(dependencies.client),
fetchImpl = fetch,
} = {}
) {
const app = express();
app.disable("x-powered-by");
app.set("trust proxy", config.webTrustedProxies);
app.use(helmet());
app.use(express.json({ limit: "32kb" }));
app.use(sessionMiddleware(oauth));
// /healthz : le processus répond (sonde de vie). /readyz : le bot est aussi connecté à
// Discord, sinon 503 (à utiliser pour la supervision).
const discordReady = () => dependencies.client?.isReady?.() ?? false;
app.get("/healthz", (_req, res) => {
res.json({ status: "ok" });
res.json({ status: "ok", discord: discordReady() ? "ready" : "not-ready" });
});
app.get("/readyz", (_req, res) => {
const ready = discordReady();
res.status(ready ? 200 : 503).json({ status: ready ? "ready" : "not-ready" });
});
// Messages privés pour les applications de confiance : connexions locales uniquement,
@ -66,18 +105,27 @@ function createApp(
notificationsRouter(dependencies)
);
app.use(
"/auth",
// /auth/me est appelée à chaque chargement de page : seule la connexion est limitée.
apiRateLimit({ windowMs: 15 * 60_000, limit: 60, skip: (req) => req.path === "/me" }),
authRouter({ oauth, findMember, fetchImpl })
);
const apiRouter = express.Router();
apiRouter.use(apiRateLimit({ windowMs: 60_000, limit: 120 }));
apiRouter.use(authFailureLimit());
apiRouter.use(authMiddleware);
apiRouter.use(createJukeboxAuth({ publicUrl: oauth.publicUrl }));
apiRouter.use(
"/uploads",
apiRateLimit({ windowMs: 15 * 60_000, limit: 10 }),
// Envoi de plusieurs fichiers d'un coup : une requête par fichier.
apiRateLimit({ windowMs: 15 * 60_000, limit: 40 }),
uploadsRouter(dependencies)
);
apiRouter.use("/queue", queueRouter(dependencies));
apiRouter.use("/library", libraryRouter(dependencies));
apiRouter.use("/player", playerRouter(dependencies));
apiRouter.use("/events", eventsRouter(dependencies));
app.use("/api", apiRouter);
app.get(["/jukebox", "/jukebox/"], (_req, res) =>
@ -101,9 +149,28 @@ function createApp(
return app;
}
const TEMP_CLEANUP_INTERVAL = 60 * 60_000;
function startWebServer(dependencies) {
ensureStorageLayout();
cleanupTemporaryFiles();
const cleanup = () =>
cleanupTemporaryFiles(undefined, { keep: dependencies.queue.inUsePaths() });
cleanup();
// Les fichiers temporaires de plus de 24 h sont supprimés pendant que le bot tourne,
// pas seulement à son démarrage.
const cleanupInterval = setInterval(cleanup, TEMP_CLEANUP_INTERVAL);
cleanupInterval.unref();
backfillLibraryMetadata()
.then((updated) => {
if (updated.length > 0) {
console.log(
`[${new Date().toLocaleString()}] Library metadata completed for ${updated.length} track(s)`
);
dependencies.queue.emit("libraryUpdate");
}
})
.catch((error) => console.error("Unable to complete library metadata", error));
const app = createApp(dependencies);
const port = Number(process.env.PORT || config.webServerPort || 3000);
@ -113,6 +180,7 @@ function startWebServer(dependencies) {
`[${new Date().toLocaleString()}] Web control server listening on port ${port}`
);
});
server.on("close", () => clearInterval(cleanupInterval));
return { app, server };
}

View file

@ -0,0 +1,24 @@
import { probeAudioFile } from "../../media/validateAudioFile.js";
import { getPermanentLibrary, updatePermanentTracks } from "./storageManager.js";
// Complète la durée et l'artiste des morceaux ajoutés avant que l'upload ne les relève.
// Un fichier illisible est ignoré : il sera retenté au prochain démarrage.
async function backfillLibraryMetadata({ probe = probeAudioFile } = {}) {
const missing = getPermanentLibrary().filter((entry) => entry.duration == null);
const updates = new Map();
for (const entry of missing) {
try {
const { duration, artist } = await probe(entry.path);
if (duration != null) {
updates.set(entry.id, { duration, artist: entry.artist ?? artist });
}
} catch (error) {
console.error(`Unable to read metadata of library entry ${entry.id}`, error.cause ?? error);
}
}
return updatePermanentTracks(updates);
}
export { backfillLibraryMetadata };

View file

@ -87,7 +87,13 @@ function writeLibrary(entries) {
function registerUploadedFile(
file,
{ permanent, uploader = "unknown", title = file.originalname }
{
permanent,
uploader = "unknown",
title = file.originalname,
duration = null,
artist = null,
}
) {
ensureStorageLayout();
const createdAt = new Date().toISOString();
@ -102,7 +108,9 @@ function registerUploadedFile(
0
);
if (librarySize + file.size > MAX_LIBRARY_SIZE) {
throw new Error("La bibliothèque permanente a atteint sa limite de 2 Go");
const error = new Error("La bibliothèque permanente a atteint sa limite de 2 Go");
error.status = 413;
throw error;
}
const rawExtension = path.extname(file.originalname).toLowerCase();
@ -120,6 +128,8 @@ function registerUploadedFile(
path: finalPath,
size: file.size,
mimetype: file.mimetype,
duration,
artist,
uploader,
createdAt,
};
@ -135,6 +145,8 @@ function registerUploadedFile(
storedName,
size: file.size,
mimetype: file.mimetype,
duration,
artist,
permanent,
uploader,
libraryTrackId: permanentEntry ? permanentEntry.id : null,
@ -164,14 +176,21 @@ function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") {
storedName: libraryTrack.storedName,
size: libraryTrack.size,
mimetype: libraryTrack.mimetype,
duration: libraryTrack.duration ?? null,
artist: libraryTrack.artist ?? null,
permanent: true,
uploader: requestedBy,
uploader:
String(requestedBy ?? "")
.replace(/[\u0000-\u001f]/g, "")
.trim()
.slice(0, 80) || "library",
libraryTrackId: libraryTrack.id,
createdAt: new Date().toISOString(),
};
}
function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE) {
// keep : chemins encore utilisés (file d'attente, morceau en cours), jamais supprimés.
function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE, { keep = new Set() } = {}) {
ensureStorageLayout();
const cutoff = Date.now() - maxAge;
@ -181,6 +200,9 @@ function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE) {
}
const filePath = path.join(TEMP_DIR, entry.name);
if (keep.has(filePath)) {
continue;
}
try {
if (fs.statSync(filePath).mtimeMs < cutoff) {
fs.unlinkSync(filePath);
@ -207,6 +229,24 @@ function discardUploadedFile(file) {
deleteFileSafe(file?.path);
}
// Modifie des champs d'entrées de la bibliothèque : updates est une Map id → champs.
// Relit le fichier juste avant d'écrire, pour ne pas écraser un ajout fait entre-temps.
function updatePermanentTracks(updates) {
const library = getPermanentLibrary();
const updated = [];
for (const entry of library) {
const fields = updates.get(entry.id);
if (fields) {
Object.assign(entry, fields);
updated.push(entry);
}
}
if (updated.length > 0) {
writeLibrary(library);
}
return updated;
}
function deletePermanentTrack(id) {
const library = getPermanentLibrary();
const index = library.findIndex((entry) => entry.id === id);
@ -248,6 +288,7 @@ export {
cleanupTemporaryFiles,
discardUploadedFile,
deletePermanentTrack,
updatePermanentTracks,
handleTrackCompletion,
deleteTrackFile,
};

68
test/audio.test.js Normal file
View file

@ -0,0 +1,68 @@
import test from "node:test";
import assert from "node:assert/strict";
import { spawn, spawnSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { StreamType, createAudioResource } from "@discordjs/voice";
import { createOpusStream, probeAudioFile } from "../src/media/validateAudioFile.js";
const hasFfmpeg =
spawnSync("ffmpeg", ["-version"]).status === 0 &&
spawnSync("ffprobe", ["-version"]).status === 0;
const skip = hasFfmpeg ? false : "ffmpeg et ffprobe sont nécessaires";
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-audio-"));
test.after(() => fs.rmSync(directory, { recursive: true, force: true }));
// Un MP3 de `seconds` secondes (un la à 440 Hz) avec des tags ID3.
function makeTone(name, seconds, { title = "Chanson", artist = "Palico" } = {}) {
const file = path.join(directory, name);
const result = spawnSync("ffmpeg", [
"-v", "error", "-y",
"-f", "lavfi", "-i", `sine=frequency=440:duration=${seconds}`,
"-metadata", `title=${title}`, "-metadata", `artist=${artist}`,
"-c:a", "libmp3lame", "-b:a", "64k", file,
]);
assert.equal(result.status, 0, result.stderr?.toString());
return file;
}
test("probeAudioFile reads the duration and the tags", { skip }, async () => {
const metadata = await probeAudioFile(makeTone("tagged.mp3", 2));
assert.equal(metadata.duration, 2);
assert.equal(metadata.title, "Chanson");
assert.equal(metadata.artist, "Palico");
});
test("probeAudioFile rejects a file without audio", { skip }, async () => {
const file = path.join(directory, "not-audio.mp3");
fs.writeFileSync(file, "pas du son");
await assert.rejects(probeAudioFile(file), { status: 400 });
});
test("createOpusStream yields Opus packets that Discord can play as is", { skip }, async () => {
const resource = createAudioResource(createOpusStream(makeTone("short.mp3", 1)), {
inputType: StreamType.OggOpus,
});
let packets = 0;
for await (const packet of resource.playStream) {
assert.ok(Buffer.isBuffer(packet) && packet.length > 0);
packets += 1;
}
// 1 s d'audio en trames Opus de 20 ms : une cinquantaine de paquets.
assert.ok(packets >= 45, `${packets} paquets`);
});
test("closing the Opus stream stops ffmpeg", { skip }, async () => {
let child;
const output = createOpusStream(makeTone("long.mp3", 120), {
spawnProcess: (...args) => (child = spawn(...args)),
});
await new Promise((resolve) => output.once("data", resolve));
const exited = new Promise((resolve) => child.once("exit", (_code, signal) => resolve(signal)));
output.destroy();
assert.equal(await exited, "SIGKILL");
});

View file

@ -31,7 +31,7 @@ async function loadCommands() {
test("all Discord commands expose valid command data", async () => {
const modules = await loadCommands();
assert.equal(modules.length, 10);
assert.equal(modules.length, 13);
for (const module of modules) {
assert.doesNotThrow(() => module.command.data.toJSON());
assert.equal(typeof module.command.execute, "function");
@ -57,3 +57,13 @@ test("administrative commands require Discord permissions", async () => {
}
}
});
test("/queue lists the current track and what comes next", async () => {
const { buildQueueMessage } = await import("../src/commands/jukebox/queue.js");
const message = buildQueueMessage({
currentTrack: { title: "Thème *principal*", duration: 187 },
queue: [{ title: "Suite", duration: 3909 }],
});
assert.match(message, /En cours : \*\*Thème \\\*principal\\\* \(3:07\)\*\*/);
assert.match(message, /1\. Suite \(1:05:09\)/);
});

165
test/discordAuth.test.js Normal file
View file

@ -0,0 +1,165 @@
import test from "node:test";
import assert from "node:assert/strict";
Object.assign(process.env, {
NODE_ENV: "test",
DISCORD_GUILD_ID: "1",
SHINUWA_USER_ID: "1",
WEB_SERVER_PORT: "3000",
WEB_API_KEY: "web-key",
DISCORD_APPLICATION_ID: "client-id",
DISCORD_TOKEN: "test-token",
VOICE_CHANNEL_ID: "1",
TEXT_CHANNEL_ID: "1",
GAME_SERVERS_MESSAGE_ID: "1",
});
const { createApp } = await import("../src/web/server.js");
const { createSessionToken, readSessionToken } = await import("../src/web/auth/session.js");
const SECRET = "s".repeat(40);
const MEMBER_ID = "111111111111111111";
const STRANGER_ID = "222222222222222222";
const oauth = {
enabled: true,
clientId: "client-id",
clientSecret: "client-secret",
publicUrl: "http://localhost",
sessionSecret: SECRET,
};
// Faux Discord : le code « member » identifie un membre du serveur, « stranger » un inconnu.
function fakeDiscordFetch(calls) {
return async (url, options = {}) => {
calls.push({ url, options });
if (url.endsWith("/oauth2/token")) {
const code = options.body.get("code");
return Response.json({ access_token: `token-${code}` });
}
if (url.endsWith("/users/@me")) {
const token = options.headers.authorization;
const id = token === "Bearer token-member" ? MEMBER_ID : STRANGER_ID;
return Response.json({ id, username: "palico", global_name: "Palico" });
}
return new Response(null, { status: 404 });
};
}
const fakeQueue = {
snapshot: () => ({ current: null, upcoming: [], status: "idle", loop: false, position: 0 }),
};
async function withApp(run) {
const calls = [];
const app = createApp(
{ queue: fakeQueue, client: {} },
{
oauth,
fetchImpl: fakeDiscordFetch(calls),
findMember: async (id) => (id === MEMBER_ID ? { displayName: "Chef Palico" } : null),
}
);
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
try {
await run(`http://127.0.0.1:${server.address().port}`, calls);
} finally {
await new Promise((resolve) => server.close(resolve));
}
}
function cookieValue(response, name) {
const header = response.headers.getSetCookie().find((cookie) => cookie.startsWith(`${name}=`));
return header ? decodeURIComponent(header.split(";")[0].slice(name.length + 1)) : null;
}
async function login(base, code) {
const start = await fetch(`${base}/auth/discord`, { redirect: "manual" });
assert.equal(start.status, 303);
const authorizeUrl = new URL(start.headers.get("location"));
assert.equal(authorizeUrl.hostname, "discord.com");
assert.equal(authorizeUrl.searchParams.get("scope"), "identify");
const state = authorizeUrl.searchParams.get("state");
const stateCookie = cookieValue(start, "palico_oauth_state");
assert.equal(stateCookie, state);
return fetch(`${base}/auth/discord/callback?code=${code}&state=${state}`, {
redirect: "manual",
headers: { cookie: `palico_oauth_state=${stateCookie}` },
});
}
test("a guild member logs in with Discord and uses the jukebox API", async () => {
await withApp(async (base) => {
const callback = await login(base, "member");
assert.equal(callback.status, 303);
assert.equal(callback.headers.get("location"), "/jukebox/");
const session = cookieValue(callback, "palico_session");
assert.ok(session);
const me = await (await fetch(`${base}/auth/me`, { headers: { cookie: `palico_session=${session}` } })).json();
assert.deepEqual(me, { oauthEnabled: true, user: { id: MEMBER_ID, name: "Chef Palico" } });
const queue = await fetch(`${base}/api/queue`, { headers: { cookie: `palico_session=${session}` } });
assert.equal(queue.status, 200);
});
});
test("someone outside the guild is turned away", async () => {
await withApp(async (base) => {
const callback = await login(base, "stranger");
assert.equal(callback.headers.get("location"), "/jukebox/?login=not-member");
assert.equal(cookieValue(callback, "palico_session"), null);
});
});
test("a callback without the matching state is refused", async () => {
await withApp(async (base, calls) => {
const callback = await fetch(`${base}/auth/discord/callback?code=member&state=forged`, {
redirect: "manual",
headers: { cookie: "palico_oauth_state=other" },
});
assert.equal(callback.headers.get("location"), "/jukebox/?login=state");
assert.equal(calls.length, 0);
});
});
test("a cookie session cannot change anything from another site", async () => {
await withApp(async (base) => {
const session = createSessionToken({ id: MEMBER_ID, name: "Chef Palico" }, SECRET);
const response = await fetch(`${base}/api/player/skip`, {
method: "POST",
headers: { cookie: `palico_session=${session}`, origin: "https://evil.example" },
});
assert.equal(response.status, 403);
});
});
test("tampered or expired session tokens are rejected", () => {
const token = createSessionToken({ id: MEMBER_ID, name: "Chef" }, SECRET, 0);
assert.equal(readSessionToken(token, SECRET, 1)?.id, MEMBER_ID);
assert.equal(readSessionToken(token, "x".repeat(40), 1), null);
const [payload, signature] = token.split(".");
const forged = Buffer.from(JSON.stringify({ sub: STRANGER_ID, name: "x", exp: 9e15 })).toString("base64url");
assert.equal(readSessionToken(`${forged}.${signature}`, SECRET, 1), null);
assert.equal(readSessionToken(`${payload}.${signature}`, SECRET, 31 * 24 * 3600 * 1000), null);
});
test("without OAuth the API still needs the key", async () => {
const app = createApp({ queue: fakeQueue, client: {} });
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
try {
const me = await (await fetch(`${base}/auth/me`)).json();
assert.equal(me.oauthEnabled, false);
assert.equal((await fetch(`${base}/api/queue`)).status, 401);
assert.equal(
(await fetch(`${base}/api/queue`, { headers: { authorization: "Bearer web-key" } })).status,
200
);
} finally {
await new Promise((resolve) => server.close(resolve));
}
});

114
test/downloadAudio.test.js Normal file
View file

@ -0,0 +1,114 @@
import test from "node:test";
import assert from "node:assert/strict";
import dns from "node:dns";
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { downloadAudio, isBlockedAddress } from "../src/media/downloadAudio.js";
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-download-"));
test.after(() => fs.rmSync(directory, { recursive: true, force: true }));
// Le serveur de test écoute en local, adresse que le téléchargeur refuse : les tests qui
// doivent l'atteindre passent une résolution DNS sans filtre.
const allowLocal = (hostname, options, callback) => dns.lookup(hostname, options, callback);
async function withServer(handler, run) {
const server = http.createServer(handler);
server.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
try {
await run(`http://localhost:${server.address().port}`);
} finally {
await new Promise((resolve) => server.close(resolve));
}
}
test("internal and special addresses are blocked", () => {
for (const address of ["127.0.0.1", "10.1.2.3", "192.168.0.100", "172.20.0.1", "169.254.169.254", "100.64.0.1", "::1", "fd00::1", "fe80::1", "::ffff:10.0.0.1"]) {
assert.equal(isBlockedAddress(address), true, address);
}
for (const address of ["1.1.1.1", "151.101.130.132", "2606:4700::1111"]) {
assert.equal(isBlockedAddress(address), false, address);
}
});
test("a direct link is downloaded with its file name", async () => {
await withServer(
(req, res) => {
res.writeHead(200, {
"content-type": "audio/mpeg",
"content-disposition": "attachment; filename=\"chanson.mp3\"",
});
res.end("fake audio");
},
async (base) => {
const file = await downloadAudio(`${base}/download?id=1`, {
destinationDir: directory,
lookup: allowLocal,
});
assert.equal(file.originalname, "chanson.mp3");
assert.equal(file.mimetype, "audio/mpeg");
assert.equal(file.size, 10);
assert.equal(fs.readFileSync(file.path, "utf8"), "fake audio");
}
);
});
test("local addresses are refused, written as an IP or behind a host name", async () => {
await assert.rejects(downloadAudio("http://127.0.0.1:1/a.mp3", { destinationDir: directory }), {
status: 400,
});
await withServer(
(req, res) => res.end("secret"),
async (base) => {
await assert.rejects(downloadAudio(`${base}/a.mp3`, { destinationDir: directory }), {
message: /non autorisée/,
});
}
);
});
test("a redirect towards an internal address is refused", async () => {
await withServer(
(req, res) => {
res.writeHead(302, { location: "http://192.168.0.100/admin" });
res.end();
},
async (base) => {
await assert.rejects(
downloadAudio(`${base}/a.mp3`, { destinationDir: directory, lookup: allowLocal }),
{ message: /non autorisée/ }
);
}
);
});
test("files over the size limit are refused and removed", async () => {
await withServer(
(req, res) => {
res.writeHead(200);
res.write(Buffer.alloc(600));
res.end(Buffer.alloc(600));
},
async (base) => {
const before = fs.readdirSync(directory).length;
await assert.rejects(
downloadAudio(`${base}/big.mp3`, {
destinationDir: directory,
lookup: allowLocal,
maxSize: 1000,
}),
{ status: 413 }
);
assert.equal(fs.readdirSync(directory).length, before);
}
);
});
test("only http and https links are accepted", async () => {
await assert.rejects(downloadAudio("file:///etc/passwd", { destinationDir: directory }), {
status: 400,
});
});

46
test/gameServers.test.js Normal file
View file

@ -0,0 +1,46 @@
import test from "node:test";
import assert from "node:assert/strict";
import net from "node:net";
Object.assign(process.env, {
NODE_ENV: "test",
DISCORD_GUILD_ID: "1",
SHINUWA_USER_ID: "1",
WEB_SERVER_PORT: "3000",
WEB_API_KEY: "test-key",
DISCORD_APPLICATION_ID: "1",
DISCORD_TOKEN: "test-token",
VOICE_CHANNEL_ID: "1",
TEXT_CHANNEL_ID: "1",
GAME_SERVERS_MESSAGE_ID: "1",
});
const { probeTcp, serverStatus } = await import("../src/features/showGameServers.js");
test("a listening TCP port is online, a closed one offline", async () => {
const server = net.createServer((socket) => socket.end());
server.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
const { port } = server.address();
try {
assert.equal(await probeTcp("127.0.0.1", port), true);
} finally {
await new Promise((resolve) => server.close(resolve));
}
assert.equal(await probeTcp("127.0.0.1", port), false);
});
test("servers without check keep their manual status", async () => {
const probe = () => assert.fail("must not probe");
assert.equal(await serverStatus({ active: true }, probe), true);
assert.equal(await serverStatus({ active: false }, probe), false);
});
test("checked servers are probed on checkPort, else on port", async () => {
const probed = [];
const probe = async (host, port) => probed.push(`${host}:${port}`) && true;
await serverStatus({ address: "games.example.com:8211", port: 8211, check: true, checkPort: 25575 }, probe);
await serverStatus({ address: "games.example.com:25566", port: 25566, check: true }, probe);
assert.deepEqual(probed, ["games.example.com:25575", "games.example.com:25566"]);
assert.equal(await serverStatus({ address: "x", check: true }, probe), false);
});

67
test/ingest.test.js Normal file
View file

@ -0,0 +1,67 @@
import test from "node:test";
import assert from "node:assert/strict";
import { EventEmitter } from "node:events";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
// storageManager.js fixe ses dossiers au chargement, d'après le répertoire de travail.
const originalDirectory = process.cwd();
const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-ingest-"));
process.chdir(temporaryDirectory);
const storage = await import("../src/web/storage/storageManager.js");
const { defaultTitle, ingestAudioFile } = await import("../src/music/ingest.js");
storage.ensureStorageLayout();
test.after(() => {
process.chdir(originalDirectory);
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
});
function fakeQueue() {
const queue = new EventEmitter();
queue.enqueued = [];
queue.enqueue = (track) => queue.enqueued.push(track);
return queue;
}
function tempFile(name) {
const filePath = path.join(storage.TEMP_DIR, `upload-${name}`);
fs.writeFileSync(filePath, "audio");
return { path: filePath, originalname: name, size: 5, mimetype: "audio/mpeg" };
}
test("default titles come from the tags, else from the file name", () => {
assert.equal(defaultTitle({ title: "Song", artist: "Band" }, "x.mp3"), "Band - Song");
assert.equal(defaultTitle({ title: "Song", artist: null }, "x.mp3"), "Song");
assert.equal(defaultTitle({ title: null, artist: null }, "Mon morceau.flac"), "Mon morceau");
});
test("an ingested file is queued with its metadata", async () => {
const queue = fakeQueue();
let libraryUpdates = 0;
queue.on("libraryUpdate", () => libraryUpdates++);
const track = await ingestAudioFile(
tempFile("a.mp3"),
{ permanent: true, uploader: "Shinuwa\u0007" },
{ queue, probe: async () => ({ duration: 61, title: "Titre", artist: "Artiste" }) }
);
assert.equal(track.title, "Artiste - Titre");
assert.equal(track.duration, 61);
assert.equal(track.uploader, "Shinuwa");
assert.deepEqual(queue.enqueued, [track]);
assert.equal(libraryUpdates, 1);
assert.equal(storage.getPermanentLibrary()[0].duration, 61);
});
test("a file that is not audio is deleted", async () => {
const file = tempFile("b.mp3");
const invalid = Object.assign(new Error("pas de l'audio"), { status: 400 });
await assert.rejects(
ingestAudioFile(file, {}, { queue: fakeQueue(), probe: async () => { throw invalid; } }),
invalid
);
assert.equal(fs.existsSync(file.path), false);
});

View file

@ -1,5 +1,6 @@
import test from "node:test";
import assert from "node:assert/strict";
import { EventEmitter } from "node:events";
Object.assign(process.env, {
NODE_ENV: "test",
@ -43,10 +44,206 @@ test("queue snapshots do not expose filesystem paths", () => {
queue.currentTrack = { id: "current", path: "/private/current.mp3" };
queue.queue = [{ id: "next", path: "/private/next.mp3" }];
queue.playbackStatus = "playing";
queue.loop = false;
assert.deepEqual(queue.snapshot(), {
current: { id: "current" },
upcoming: [{ id: "next" }],
status: "playing",
loop: false,
position: 0,
});
});
const BOT_ID = "bot";
// Faux client Discord : un salon vocal (identifiant « 1 », comme VOICE_CHANNEL_ID) dont on
// choisit les membres.
function fakeClient(memberIds = []) {
const client = new EventEmitter();
const members = new Map(
memberIds.map((id) => [id, { id, user: { bot: id === BOT_ID || id.startsWith("otherbot") } }])
);
client.user = { id: BOT_ID };
client.channels = { cache: new Map([["1", { id: "1", members }]]) };
return { client, members };
}
// File dont la connexion vocale et la lecture sont simulées.
function fakeQueue(client, { connect = async () => {}, retryDelays } = {}) {
const queue = new MusicQueue(client, retryDelays ? { retryDelays } : undefined);
const played = [];
queue.connectAttempts = 0;
queue.ensureConnection = async () => {
if (queue.connection) return;
queue.connectAttempts += 1;
await connect();
queue.connection = { destroy() {} };
};
queue.createResource = (track) => track;
queue.audioPlayer.play = (resource) => played.push(resource.id);
return { queue, played };
}
const track = (id) => ({ id, path: `/nonexistent/${id}`, permanent: true });
const settle = () => new Promise((resolve) => setTimeout(resolve, 20));
test("adding a track resumes a queue suspended because the bot was alone", async () => {
const { client } = fakeClient();
const { queue, played } = fakeQueue(client);
queue.suspendedForAlone = true;
queue.enqueue(track("a"));
await settle();
assert.deepEqual(played, ["a"]);
assert.equal(queue.suspendedForAlone, false);
queue.shutdown();
});
test("someone joining the voice channel resumes a suspended queue", async () => {
const { client, members } = fakeClient();
const { queue, played } = fakeQueue(client);
queue.queue.push(track("a"));
queue.suspendedForAlone = true;
members.set("otherbot-1", { id: "otherbot-1", user: { bot: true } });
client.emit("voiceStateUpdate", { channelId: null }, { channelId: "1" });
await settle();
assert.deepEqual(played, [], "another bot joining is not a listener");
members.set("user-1", { id: "user-1", user: { bot: false } });
client.emit("voiceStateUpdate", { channelId: null }, { channelId: "1" });
await settle();
assert.deepEqual(played, ["a"]);
queue.shutdown();
});
test("a failed voice connection is retried", async () => {
const { client } = fakeClient();
let failures = 1;
const { queue, played } = fakeQueue(client, {
retryDelays: [10],
connect: async () => {
if (failures-- > 0) throw new Error("Ready timeout");
},
});
const originalConsoleError = console.error;
console.error = () => {};
try {
queue.enqueue(track("a"));
await settle();
await settle();
} finally {
console.error = originalConsoleError;
}
assert.equal(queue.connectAttempts, 2);
assert.deepEqual(played, ["a"]);
queue.shutdown();
});
test("removing the head of the queue while connecting plays the next track", async () => {
const { client } = fakeClient();
let release;
const { queue, played } = fakeQueue(client, {
connect: () => new Promise((resolve) => (release = resolve)),
});
queue.enqueue(track("a"));
queue.enqueue(track("b"));
await queue.remove("a");
release();
await settle();
assert.deepEqual(played, ["b"]);
queue.shutdown();
});
test("removing the current track returns it", async () => {
const { client } = fakeClient();
const { queue } = fakeQueue(client);
queue.currentTrack = track("a");
queue.audioPlayer.stop = () => {
queue.currentTrack = null;
return true;
};
assert.equal((await queue.remove("a"))?.id, "a");
queue.shutdown();
});
test("leaving an empty channel keeps the interrupted track at the head of the queue", () => {
const { client } = fakeClient([BOT_ID]);
const { queue } = fakeQueue(client);
queue.connection = { destroy() {} };
queue.currentTrack = { ...track("a"), startedAt: "2026-01-01T00:00:00.000Z" };
queue.queue.push(track("b"));
queue.destroyConnection("alone timeout", { suspend: true, requeue: true });
assert.deepEqual(queue.queue.map(({ id }) => id), ["a", "b"]);
assert.equal("startedAt" in queue.queue[0], false);
assert.equal(queue.suspendedForAlone, true);
queue.shutdown();
});
test("other bots do not count as listeners", () => {
const { client, members } = fakeClient([BOT_ID, "otherbot-1"]);
const { queue } = fakeQueue(client);
assert.equal(queue.isBotAlone(), true);
members.set("user-1", { id: "user-1", user: { bot: false } });
assert.equal(queue.isBotAlone(), false);
queue.shutdown();
});
test("in loop mode a finished track goes back to the end of the queue", () => {
const { client } = fakeClient();
const { queue } = fakeQueue(client);
queue.setLoop(true);
queue.currentTrack = track("a");
queue.queue.push(track("b"));
queue.playNext = () => {};
queue.audioPlayer.emit("idle");
assert.deepEqual(queue.queue.map(({ path }) => path), ["/nonexistent/b", "/nonexistent/a"]);
// Un morceau retiré ou en erreur ne revient pas.
queue.currentTrack = track("c");
queue.audioPlayer.emit("error", new Error("bad file"));
queue.audioPlayer.emit("idle");
assert.equal(queue.queue.some(({ path }) => path === "/nonexistent/c"), false);
queue.shutdown();
});
test("shuffle keeps every upcoming track", () => {
const { client } = fakeClient();
const { queue } = fakeQueue(client);
queue.queue.push(...["a", "b", "c", "d", "e"].map(track));
queue.shuffle();
assert.deepEqual(queue.queue.map(({ id }) => id).sort(), ["a", "b", "c", "d", "e"]);
queue.shutdown();
});
test("the queue survives a restart and waits for listeners", () => {
let saved = null;
const persistence = { load: () => saved, save: (state) => (saved = state) };
const { client } = fakeClient();
const first = new MusicQueue(client, { persistence });
first.queue.push(track("b"));
first.currentTrack = { ...track("a"), startedAt: "2026-01-01T00:00:00.000Z" };
first.connection = { destroy() {} };
first.setLoop(true);
first.shutdown();
assert.deepEqual(saved.queue.map(({ id }) => id), ["a", "b"]);
assert.equal("startedAt" in saved.queue[0], false);
const second = new MusicQueue(client, { persistence });
assert.deepEqual(second.queue.map(({ id }) => id), ["a", "b"]);
assert.equal(second.loop, true);
assert.equal(second.suspendedForAlone, true);
second.shutdown();
});

View file

@ -81,3 +81,36 @@ test("legacy library entries migrate without their absolute paths", async () =>
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
}
});
test("library metadata backfill fills the missing durations", async () => {
const originalDirectory = process.cwd();
const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-storage-"));
try {
process.chdir(temporaryDirectory);
const storage = await import(`../src/web/storage/storageManager.js?backfill=${Date.now()}`);
storage.ensureStorageLayout();
const uploadedPath = path.join(storage.TEMP_DIR, "upload");
fs.writeFileSync(uploadedPath, "fake audio content");
storage.registerUploadedFile(
{ path: uploadedPath, originalname: "old.mp3", size: 18, mimetype: "audio/mpeg" },
{ permanent: true, uploader: "test", title: "Old" }
);
// libraryMetadata.js importe storageManager.js sans paramètre : on passe par la même
// instance de module que lui, avec le répertoire de travail temporaire.
const { backfillLibraryMetadata } = await import("../src/web/storage/libraryMetadata.js");
const shared = await import("../src/web/storage/storageManager.js");
shared.ensureStorageLayout();
const updated = await backfillLibraryMetadata({
probe: async () => ({ duration: 42, artist: "Palico", title: null }),
});
assert.equal(updated.length, 1);
assert.equal(shared.getPermanentLibrary()[0].duration, 42);
assert.equal(shared.getPermanentLibrary()[0].artist, "Palico");
} finally {
process.chdir(originalDirectory);
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
}
});

View file

@ -114,3 +114,87 @@ test("only loopback connections count as local", () => {
assert.equal(isLoopbackAddress(address), false);
}
});
test("/readyz reports whether the bot is connected to Discord", async () => {
const app = createApp({ queue: fakeQueue, client: { isReady: () => false } });
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
try {
assert.equal((await fetch(`${base}/healthz`)).status, 200);
assert.equal((await fetch(`${base}/readyz`)).status, 503);
} finally {
await new Promise((resolve) => server.close(resolve));
}
});
test("the events stream sends the queue state, then every update", async () => {
const { EventEmitter } = await import("node:events");
const queue = new EventEmitter();
let snapshot = { current: null, upcoming: [], status: "idle", loop: false, position: 0 };
queue.snapshot = () => snapshot;
queue.setLoop = (enabled) => {
snapshot = { ...snapshot, loop: enabled };
queue.emit("queueUpdate", snapshot);
return snapshot;
};
const app = createApp({ queue, client: fakeClient() });
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const controller = new AbortController();
try {
const response = await fetch(`${base}/api/events`, {
headers: { authorization: "Bearer web-key" },
signal: controller.signal,
});
assert.equal(response.status, 200);
assert.match(response.headers.get("content-type"), /text\/event-stream/);
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let received = "";
const readUntil = async (pattern) => {
while (!pattern.test(received)) {
const { value, done } = await reader.read();
if (done) break;
received += value;
}
};
await readUntil(/event: queue\ndata: .*"loop":false/);
const loopResponse = await fetch(`${base}/api/player/loop`, {
method: "POST",
headers: { authorization: "Bearer web-key", "content-type": "application/json" },
body: JSON.stringify({ enabled: true }),
});
assert.equal(loopResponse.status, 200);
await readUntil(/"loop":true/);
assert.match(received, /"loop":true/);
const invalid = await fetch(`${base}/api/player/loop`, {
method: "POST",
headers: { authorization: "Bearer web-key", "content-type": "application/json" },
body: JSON.stringify({ enabled: "yes" }),
});
assert.equal(invalid.status, 400);
// Le client se déconnecte : le serveur cesse d'écouter la file.
assert.equal(queue.listenerCount("queueUpdate"), 1);
controller.abort();
for (let attempt = 0; attempt < 50 && queue.listenerCount("queueUpdate") > 0; attempt++) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
assert.equal(queue.listenerCount("queueUpdate"), 0);
} finally {
controller.abort();
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
}
});
test("the events stream requires the jukebox key", async () => {
await withServer({}, async ({ base }) => {
assert.equal((await fetch(`${base}/api/events`)).status, 401);
});
});