Compare commits
2 commits
e08dba41a3
...
11ee972636
| Author | SHA1 | Date | |
|---|---|---|---|
| 11ee972636 | |||
| 3795ee06cb |
74 changed files with 2083 additions and 221 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -17,6 +17,7 @@ storage/permanent/*
|
|||
!storage/permanent/.gitkeep
|
||||
storage/temp/*
|
||||
!storage/temp/.gitkeep
|
||||
storage/covers/
|
||||
|
||||
# Operating system files
|
||||
.DS_Store
|
||||
|
|
|
|||
10
CLAUDE.md
Normal file
10
CLAUDE.md
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
# palico-bot
|
||||
|
||||
Bot Discord et jukebox web autohébergé (Node.js, discord.js, Express). Voir
|
||||
[README.md](README.md) pour la configuration et le déploiement.
|
||||
|
||||
- Validation : `npm run check` (syntaxe et tests) avant de rendre un travail.
|
||||
- Conventions (langue, en-têtes de fichiers `/** @file … */` en trois niveaux,
|
||||
feuille de style) : [CONTRIBUTING.md](CONTRIBUTING.md). Un nouveau fichier
|
||||
reçoit son en-tête dès sa création ; un fichier modifié dont le rôle, les
|
||||
appelants ou les pièges changent voit son en-tête mis à jour.
|
||||
110
CONTRIBUTING.md
Normal file
110
CONTRIBUTING.md
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
# Contribuer à palico-bot
|
||||
|
||||
## Validation
|
||||
|
||||
```bash
|
||||
npm run check
|
||||
```
|
||||
|
||||
Vérifie la syntaxe de tous les fichiers JavaScript (front compris) puis lance les
|
||||
tests, dont celui des en-têtes de fichiers (`test/fileHeaders.test.js`).
|
||||
|
||||
## Langue
|
||||
|
||||
- Code (noms de variables, fonctions, fichiers) et journaux du serveur : anglais.
|
||||
- Commentaires, documentation et textes vus par les utilisateurs (Discord, page
|
||||
web, erreurs de l'API) : français.
|
||||
|
||||
## En-têtes de fichiers
|
||||
|
||||
Chaque fichier JavaScript (sources, front, scripts et tests) commence par un
|
||||
en-tête. Il s'adresse à quelqu'un qui ouvre le fichier pour la première fois :
|
||||
ce que fait le fichier, pourquoi il existe et ce qu'il faut savoir avant de le
|
||||
modifier.
|
||||
|
||||
### Syntaxe
|
||||
|
||||
- **JavaScript** : bloc JSDoc qui commence par `/**` puis ` * @file`. Le texte
|
||||
de `@file` est la description ; ses lignes suivantes s'alignent sous le texte
|
||||
(7 espaces après `*`). Les rubriques viennent après une ligne ` *` vide, et
|
||||
leurs lignes suivantes sont décalées de 2 espaces. Une ligne vide sépare le
|
||||
bloc du code.
|
||||
- **CSS** : commentaire `/* … */` dont la première ligne est ` * Rôle : …`, puis
|
||||
les mêmes rubriques (`Chargé par`, `Attention`).
|
||||
|
||||
Pas de `@author`, `@version` ni `@since` : Git garde déjà cet historique, et ces
|
||||
balises se périment. Pas de `@module` (le chemin suffit) ni de `@description`
|
||||
(doublon du texte de `@file`).
|
||||
|
||||
### Trois niveaux de détail
|
||||
|
||||
**Fichier simple** (commande, route simple, test) : la description seule, en
|
||||
une ou deux lignes.
|
||||
|
||||
```js
|
||||
/**
|
||||
* @file Commande /skip : passe au morceau suivant du jukebox.
|
||||
*/
|
||||
```
|
||||
|
||||
**Fichier partagé** (module de `features/`, `media/`, authentification,
|
||||
réglages) : la description, puis seulement les rubriques utiles parmi
|
||||
`Utilisé par`, `Attention` et `@see`.
|
||||
|
||||
```js
|
||||
/**
|
||||
* @file Enregistre la file du jukebox dans storage/runtime/queue.json pour la retrouver au redémarrage.
|
||||
*
|
||||
* Utilisé par : index.js, qui le passe à MusicQueue (option `persistence`).
|
||||
* Attention : l'écriture passe par un fichier temporaire renommé, pour ne jamais laisser un JSON à
|
||||
* moitié écrit ; au chargement, les morceaux dont le fichier a disparu sont ignorés.
|
||||
*/
|
||||
```
|
||||
|
||||
**Fichier central** (point d'entrée, file du jukebox, serveur web, stockage,
|
||||
script de la page, ou tout fichier de plus de 300 lignes) : gabarit complet.
|
||||
|
||||
```js
|
||||
/**
|
||||
* @file <Ce que fait le fichier et pourquoi il existe, en une ou deux phrases.>
|
||||
*
|
||||
* Contexte : <sa place dans l'ensemble (bot, serveur web, page).>
|
||||
* Points d'entrée : <les 2 à 4 exports ou méthodes importants, pas la liste complète.>
|
||||
* Utilisé par : <appelants principaux.>
|
||||
* Dépend de : <modules clés.>
|
||||
* Attention : <invariants, pièges, effets de bord.>
|
||||
* @see <section du README ou document de référence>
|
||||
*/
|
||||
```
|
||||
|
||||
### Ce que vérifie le test
|
||||
|
||||
`test/fileHeaders.test.js` fait échouer `npm run check` quand :
|
||||
|
||||
- un fichier JavaScript ne commence pas par `/**` puis ` * @file` ;
|
||||
- un fichier de sa liste `CENTRAL_FILES`, ou un fichier source de plus de
|
||||
300 lignes, n'a pas `Contexte :`, `Utilisé par :` et `@see` ;
|
||||
- `public/style/styles.css` ne commence pas par son `Rôle :`.
|
||||
|
||||
Un fichier qui devient central s'ajoute à `CENTRAL_FILES`. Le test ne lit que la
|
||||
présence des rubriques : leur contenu reste à écrire avec soin.
|
||||
|
||||
### Règles
|
||||
|
||||
- Écrire l'en-tête **après avoir lu le fichier**, jamais d'après son seul nom.
|
||||
- Expliquer le pourquoi et le contexte, sans paraphraser le code.
|
||||
- Citer les points d'entrée, pas toutes les fonctions : une liste complète se
|
||||
périme.
|
||||
- Omettre une rubrique vide plutôt que d'écrire « aucun ».
|
||||
- Un commentaire qui explique une déclaration précise reste au-dessus de cette
|
||||
déclaration, pas dans l'en-tête.
|
||||
- Mettre l'en-tête à jour quand le rôle, les appelants ou les pièges du fichier
|
||||
changent.
|
||||
|
||||
## Feuille de style
|
||||
|
||||
`public/style/styles.css` est servie telle quelle, sans compilation (pas de
|
||||
Sass). Les couleurs viennent des variables de `:root` ; leurs versions
|
||||
transparentes en dérivent avec `color-mix()` au lieu d'être recopiées en
|
||||
`rgba()`. Les classes utilitaires (`u-…`, `.grid`) restent en fin de fichier,
|
||||
pour l'emporter sur les composants.
|
||||
11
README.md
11
README.md
|
|
@ -43,8 +43,9 @@ npm run deploy
|
|||
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` (et `storage/runtime/queue.json`, la file en cours) ;
|
||||
- `storage/permanent/`.
|
||||
- `storage/runtime/library.json`, `storage/runtime/sections.json` (sections de
|
||||
la bibliothèque) et `storage/runtime/queue.json` (la file en cours) ;
|
||||
- `storage/permanent/` (fichiers audio) et `storage/covers/` (pochettes).
|
||||
|
||||
Les fichiers placés dans `storage/temp/` sont temporaires et nettoyés après
|
||||
24 heures.
|
||||
|
|
@ -103,6 +104,12 @@ file d'attente.
|
|||
(réseau local, boucle locale…), y compris après une redirection.
|
||||
- Chaque morceau passe par `ffmpeg`, qui normalise le volume (EBU R128) et
|
||||
encode en Opus : Discord reçoit l'audio sans réencodage.
|
||||
- La page web range la bibliothèque en sections (chacune peut être ajoutée à
|
||||
la file d'un coup, mélangée ou non) et donne une pochette à chaque morceau :
|
||||
celle intégrée au fichier est reprise à l'ajout, et le bouton « Modifier »
|
||||
permet d'en envoyer une autre (PNG, JPEG, WebP ou GIF), réduite en JPEG de
|
||||
512 px. Les pochettes sont servies sous `/covers/` sans authentification,
|
||||
sous des noms aléatoires que seule l'API donne.
|
||||
|
||||
- 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.
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Enregistre les commandes slash auprès de Discord pour le serveur configuré (`npm run deploy`),
|
||||
* à relancer après l'ajout d'une commande ou un changement de ses options.
|
||||
*/
|
||||
|
||||
import { REST, Routes } from "discord.js";
|
||||
import { config } from "./src/config.js";
|
||||
import { loadCommands } from "./src/loadCommands.js";
|
||||
|
|
|
|||
15
index.js
15
index.js
|
|
@ -1,3 +1,18 @@
|
|||
/**
|
||||
* @file Point d'entrée du bot : connecte le client Discord, branche les commandes et les événements,
|
||||
* crée la file du jukebox et démarre le serveur web.
|
||||
*
|
||||
* Contexte : lancé par `npm start` ; un seul processus sert le bot et le site du jukebox.
|
||||
* Points d'entrée : exporte `client` et `musicQueue` ; arrêt propre sur SIGTERM et SIGINT.
|
||||
* Utilisé par : `npm start` (package.json).
|
||||
* Dépend de : loadCommands.js, src/events/, music/queue.js, music/queuePersistence.js, web/server.js.
|
||||
* Attention :
|
||||
* - Les commandes trouvent la file par `interaction.client.musicQueue`.
|
||||
* - À l'arrêt, les flux en direct des pages ouvertes sont coupés de force : sinon le serveur HTTP
|
||||
* ne se ferme jamais.
|
||||
* @see README.md#déploiement
|
||||
*/
|
||||
|
||||
import { Client, Collection, GatewayIntentBits } from "discord.js";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
|
|
|||
|
|
@ -168,11 +168,12 @@
|
|||
<div>
|
||||
<h2 id="libraryTitle">Bibliothèque permanente</h2>
|
||||
<p class="panel__subtitle">
|
||||
Les fichiers conservés sont listés ici. Ajoute-les à la file,
|
||||
renomme-les ou supprime-les.
|
||||
Les fichiers conservés sont listés ici. Range-les en sections,
|
||||
donne-leur une pochette, ajoute-les à la file.
|
||||
</p>
|
||||
</div>
|
||||
<div class="toolbar">
|
||||
<button id="newSectionBtn" class="btn btn--secondary btn--small" type="button">Nouvelle section</button>
|
||||
<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é
|
||||
|
|
@ -186,10 +187,39 @@
|
|||
placeholder="Rechercher un morceau…"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<ul id="libraryList" class="list list--stack u-mt-1"></ul>
|
||||
<div id="libraryList" class="library"></div>
|
||||
<p id="libraryEmpty" class="text--muted">Aucun fichier permanent enregistré.</p>
|
||||
</section>
|
||||
|
||||
<dialog id="trackDialog" class="dialog" aria-labelledby="trackDialogTitle">
|
||||
<form id="trackForm">
|
||||
<h2 id="trackDialogTitle">Modifier le morceau</h2>
|
||||
|
||||
<div class="track-editor">
|
||||
<div id="trackCoverPreview" class="cover cover--large cover--empty" aria-hidden="true"></div>
|
||||
<div class="track-editor__cover-fields">
|
||||
<label for="trackCoverInput">Pochette</label>
|
||||
<input type="file" id="trackCoverInput" accept="image/png,image/jpeg,image/webp,image/gif" />
|
||||
<p class="hint">PNG, JPEG, WebP ou GIF, 10 Mo au plus. Recadrée à 512 px.</p>
|
||||
<button id="trackCoverRemoveBtn" class="btn btn--ghost btn--small u-mt-1" type="button">
|
||||
Retirer la pochette
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label for="trackTitleInput" class="u-mt-1">Titre</label>
|
||||
<input type="text" id="trackTitleInput" maxlength="200" required />
|
||||
|
||||
<label for="trackSectionSelect" class="u-mt-1">Section</label>
|
||||
<select id="trackSectionSelect"></select>
|
||||
|
||||
<div class="form-actions toolbar">
|
||||
<button id="trackCancelBtn" class="btn btn--ghost" type="button">Annuler</button>
|
||||
<button id="trackSaveBtn" class="btn" type="submit">Enregistrer</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<section class="panel panel--glass" id="uploadSection" aria-labelledby="uploadTitle">
|
||||
<div class="panel__header">
|
||||
<div>
|
||||
|
|
@ -213,6 +243,11 @@
|
|||
</label>
|
||||
</div>
|
||||
|
||||
<div id="uploadSectionField" class="u-mt-1" hidden>
|
||||
<label for="uploadSectionSelect">Section de la bibliothèque</label>
|
||||
<select id="uploadSectionSelect"></select>
|
||||
</div>
|
||||
|
||||
<form id="uploadForm" class="u-mt-1">
|
||||
<label for="musicFile">Fichiers audio</label>
|
||||
<input type="file" id="musicFile" name="musicFile" accept="audio/*,video/*" multiple required />
|
||||
|
|
|
|||
|
|
@ -1,3 +1,12 @@
|
|||
/**
|
||||
* @file Outils de la page du jukebox indépendants de son affichage : mémoire du mot de passe et du nom,
|
||||
* messages d'état, échappement HTML, formats de taille, durée et date, client de l'API.
|
||||
*
|
||||
* Utilisé par : public/scripts/jukebox.js.
|
||||
* Attention : chargé tel quel par le navigateur (module ES, sans compilation). Le texte venu de l'API
|
||||
* passe par escapeHtml avant d'être inséré en HTML.
|
||||
*/
|
||||
|
||||
const API_KEY_STORAGE_KEY = "palico-api-key";
|
||||
const DISPLAY_NAME_STORAGE_KEY = "palico-display-name";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,24 @@
|
|||
/**
|
||||
* @file Page du jukebox : connexion (Discord ou mot de passe), lecteur, file d'attente, bibliothèque
|
||||
* (sections, pochettes) et ajout de morceaux.
|
||||
*
|
||||
* Contexte : servi tel quel au navigateur (module ES, sans compilation) ; ne parle qu'à l'API de
|
||||
* src/web/.
|
||||
* Points d'entrée : initialize (au chargement), connectEvents (flux en direct), refreshAll.
|
||||
* Utilisé par : public/jukebox.html.
|
||||
* Dépend de : common.js, et des identifiants des éléments de jukebox.html (objet `elements`).
|
||||
* Attention :
|
||||
* - L'état arrive par le flux /api/events ; tant qu'il est coupé, chaque action recharge tout.
|
||||
* - Le flux est lu avec fetch, et non EventSource, qui ne permet pas d'envoyer la clé.
|
||||
* - Connecté avec Discord, la session (cookie) remplace la clé : pas d'en-tête Authorization.
|
||||
* - Tout texte venu de l'API passe par escapeHtml avant d'aller dans innerHTML.
|
||||
* - Les morceaux de la file n'ont pas de pochette : elle est prise sur leur morceau de bibliothèque
|
||||
* (libraryTrackId), d'où le nouvel affichage de la file à chaque changement de la bibliothèque.
|
||||
* - L'aperçu d'une pochette choisie passe par une URL data: ; la politique de sécurité des contenus
|
||||
* (helmet) refuse les URL blob:.
|
||||
* @see README.md#jukebox
|
||||
*/
|
||||
|
||||
import {
|
||||
createApiClient,
|
||||
createStatusManager,
|
||||
|
|
@ -27,6 +48,10 @@ const state = {
|
|||
queue: [],
|
||||
current: null,
|
||||
library: [],
|
||||
libraryById: new Map(),
|
||||
sections: [],
|
||||
// Sections repliées par la personne ("" : les morceaux sans section).
|
||||
collapsedSections: new Set(),
|
||||
status: "idle",
|
||||
loop: false,
|
||||
// Position du morceau en cours (ms) au moment où l'état a été reçu.
|
||||
|
|
@ -64,6 +89,7 @@ const elements = {
|
|||
libraryList: $("libraryList"),
|
||||
libraryEmpty: $("libraryEmpty"),
|
||||
librarySearch: $("librarySearch"),
|
||||
newSectionBtn: $("newSectionBtn"),
|
||||
enqueueAllBtn: $("enqueueAllBtn"),
|
||||
enqueueAllShuffledBtn: $("enqueueAllShuffledBtn"),
|
||||
uploadSection: $("uploadSection"),
|
||||
|
|
@ -73,6 +99,8 @@ const elements = {
|
|||
notesInput: $("uploadNotes"),
|
||||
permanentCheckbox: $("permanentFile"),
|
||||
enqueueCheckbox: $("enqueueFile"),
|
||||
uploadSectionField: $("uploadSectionField"),
|
||||
uploadSectionSelect: $("uploadSectionSelect"),
|
||||
uploadList: $("uploadList"),
|
||||
urlForm: $("urlForm"),
|
||||
urlInput: $("musicUrl"),
|
||||
|
|
@ -80,6 +108,15 @@ const elements = {
|
|||
heroUploadBtn: $("heroUploadBtn"),
|
||||
heroQueueBtn: $("heroQueueBtn"),
|
||||
queueSection: $("queueSection"),
|
||||
trackDialog: $("trackDialog"),
|
||||
trackForm: $("trackForm"),
|
||||
trackCoverPreview: $("trackCoverPreview"),
|
||||
trackCoverInput: $("trackCoverInput"),
|
||||
trackCoverRemoveBtn: $("trackCoverRemoveBtn"),
|
||||
trackTitleInput: $("trackTitleInput"),
|
||||
trackSectionSelect: $("trackSectionSelect"),
|
||||
trackCancelBtn: $("trackCancelBtn"),
|
||||
trackSaveBtn: $("trackSaveBtn"),
|
||||
};
|
||||
|
||||
const { setStatus, clearStatus } = createStatusManager(elements.status);
|
||||
|
|
@ -120,7 +157,7 @@ async function performRefresh() {
|
|||
apiFetch("/library"),
|
||||
]);
|
||||
applySnapshot(queueData);
|
||||
applyLibrary(libraryData.tracks || []);
|
||||
applyLibrary(libraryData);
|
||||
} catch (error) {
|
||||
handleApiError(error);
|
||||
}
|
||||
|
|
@ -128,8 +165,7 @@ async function performRefresh() {
|
|||
|
||||
async function refreshLibrary() {
|
||||
try {
|
||||
const libraryData = await apiFetch("/library");
|
||||
applyLibrary(libraryData.tracks || []);
|
||||
applyLibrary(await apiFetch("/library"));
|
||||
} catch (error) {
|
||||
handleApiError(error);
|
||||
}
|
||||
|
|
@ -172,9 +208,14 @@ function applySnapshot(snapshot) {
|
|||
renderProgress();
|
||||
}
|
||||
|
||||
function applyLibrary(tracks) {
|
||||
function applyLibrary({ tracks = [], sections = [] }) {
|
||||
state.library = tracks;
|
||||
state.libraryById = new Map(tracks.map((track) => [track.id, track]));
|
||||
state.sections = sections;
|
||||
renderLibrary();
|
||||
renderSectionChoices();
|
||||
renderCurrentTrack();
|
||||
renderQueue();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
@ -267,6 +308,19 @@ async function connectEvents() {
|
|||
// ---------------------------------------------------------------------------
|
||||
// Affichage
|
||||
|
||||
// Pochette d'un morceau : la sienne (bibliothèque), sinon celle de son morceau de bibliothèque.
|
||||
function coverUrlOf(track) {
|
||||
return track.coverUrl ?? state.libraryById.get(track.libraryTrackId)?.coverUrl ?? null;
|
||||
}
|
||||
|
||||
// Les adresses viennent du serveur (/covers/<nom aléatoire>) mais passent quand même par escapeHtml.
|
||||
function coverHtml(url, modifier = "") {
|
||||
const className = `cover ${modifier}`.trim();
|
||||
return url
|
||||
? `<img class="${className}" src="${escapeHtml(url)}" alt="" loading="lazy" />`
|
||||
: `<div class="${className} cover--empty" aria-hidden="true"></div>`;
|
||||
}
|
||||
|
||||
function trackMeta(track) {
|
||||
const parts = [];
|
||||
const duration = formatDuration(track.duration);
|
||||
|
|
@ -290,9 +344,12 @@ function renderCurrentTrack() {
|
|||
|
||||
elements.currentTrack.classList.remove("player-current--empty");
|
||||
elements.currentTrack.innerHTML = `
|
||||
<div class="media-item__title">${escapeHtml(track.title || track.originalName)}</div>
|
||||
<div class="media-item__meta">${trackMeta(track)}</div>
|
||||
<div class="media-item__meta">Commencé à ${formatDate(track.startedAt || track.createdAt)}</div>
|
||||
${coverHtml(coverUrlOf(track), "cover--large")}
|
||||
<div class="media-item__info">
|
||||
<div class="media-item__title">${escapeHtml(track.title || track.originalName)}</div>
|
||||
<div class="media-item__meta">${trackMeta(track)}</div>
|
||||
<div class="media-item__meta">Commencé à ${formatDate(track.startedAt || track.createdAt)}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
|
|
@ -333,6 +390,7 @@ function renderQueue() {
|
|||
const li = document.createElement("li");
|
||||
li.className = "media-item media-item--queue";
|
||||
li.innerHTML = `
|
||||
${coverHtml(coverUrlOf(track))}
|
||||
<div class="media-item__info">
|
||||
<div class="media-item__title">${index + 1}. ${escapeHtml(track.title || track.originalName)}</div>
|
||||
<div class="media-item__meta">${trackMeta(track)}</div>
|
||||
|
|
@ -352,28 +410,114 @@ function renderQueue() {
|
|||
});
|
||||
}
|
||||
|
||||
// Groupes de la bibliothèque, dans l'ordre des sections ; « Sans section » en dernier.
|
||||
function libraryGroups() {
|
||||
const groups = state.sections.map((section) => ({ section, tracks: [] }));
|
||||
const bySection = new Map(groups.map((group) => [group.section.id, group]));
|
||||
const unsorted = { section: null, tracks: [] };
|
||||
for (const track of state.library) {
|
||||
(bySection.get(track.sectionId) ?? unsorted).tracks.push(track);
|
||||
}
|
||||
return [...groups, unsorted];
|
||||
}
|
||||
|
||||
function renderLibrary() {
|
||||
const query = elements.librarySearch.value.trim().toLowerCase();
|
||||
const tracks = state.library.filter((track) =>
|
||||
const matches = (track) =>
|
||||
`${track.title || ""} ${track.originalName || ""} ${track.artist || ""}`
|
||||
.toLowerCase()
|
||||
.includes(query)
|
||||
);
|
||||
.includes(query);
|
||||
const matchCount = state.library.filter(matches).length;
|
||||
|
||||
elements.libraryList.replaceChildren();
|
||||
elements.libraryEmpty.hidden = tracks.length > 0;
|
||||
elements.libraryEmpty.textContent =
|
||||
state.library.length === 0
|
||||
? "Aucun fichier permanent enregistré."
|
||||
: "Aucun morceau ne correspond à la recherche.";
|
||||
const isEmpty = state.library.length === 0 && state.sections.length === 0;
|
||||
elements.libraryEmpty.hidden = !isEmpty && (matchCount > 0 || !query);
|
||||
elements.libraryEmpty.textContent = isEmpty
|
||||
? "Aucun fichier permanent enregistré."
|
||||
: "Aucun morceau ne correspond à la recherche.";
|
||||
elements.enqueueAllBtn.disabled = state.library.length === 0;
|
||||
elements.enqueueAllShuffledBtn.disabled = state.library.length === 0;
|
||||
|
||||
tracks.forEach((track) => {
|
||||
// Sans section créée, la bibliothèque reste une simple liste.
|
||||
if (state.sections.length === 0) {
|
||||
elements.libraryList.append(renderTrackList(state.library.filter(matches)));
|
||||
return;
|
||||
}
|
||||
|
||||
const groups = libraryGroups();
|
||||
groups.forEach((group, index) => {
|
||||
const shown = group.tracks.filter(matches);
|
||||
if (shown.length === 0 && (query || !group.section)) return;
|
||||
elements.libraryList.append(
|
||||
renderSection(group, shown, {
|
||||
index,
|
||||
last: state.sections.length - 1,
|
||||
searching: Boolean(query),
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function renderSection({ section, tracks }, shown, { index, last, searching }) {
|
||||
const key = section?.id ?? "";
|
||||
const details = document.createElement("details");
|
||||
details.className = "library-section";
|
||||
details.open = searching || !state.collapsedSections.has(key);
|
||||
details.addEventListener("toggle", () => {
|
||||
if (searching) return;
|
||||
if (details.open) state.collapsedSections.delete(key);
|
||||
else state.collapsedSections.add(key);
|
||||
});
|
||||
|
||||
const total = tracks.reduce((sum, track) => sum + (track.duration || 0), 0);
|
||||
const count = searching ? `${shown.length} sur ${tracks.length}` : String(tracks.length);
|
||||
const disabledIfEmpty = tracks.length === 0 ? "disabled" : "";
|
||||
details.innerHTML = `
|
||||
<summary class="library-section__summary">
|
||||
<span class="library-section__name">${escapeHtml(section?.name ?? "Sans section")}</span>
|
||||
<span class="library-section__count">
|
||||
${count} morceau(x)${total ? ` • ${formatDuration(total)}` : ""}
|
||||
</span>
|
||||
</summary>
|
||||
<div class="library-section__toolbar toolbar">
|
||||
<button class="btn btn--secondary btn--small" type="button" data-action="enqueue" ${disabledIfEmpty}>Tout ajouter</button>
|
||||
<button class="btn btn--secondary btn--small" type="button" data-action="shuffle" ${disabledIfEmpty}>Mélangé</button>
|
||||
${
|
||||
section
|
||||
? `<button class="btn btn--secondary btn--small" type="button" data-action="rename">Renommer</button>
|
||||
<button class="btn btn--secondary btn--small" type="button" data-action="up" aria-label="Monter la section" title="Monter" ${index === 0 ? "disabled" : ""}>▲</button>
|
||||
<button class="btn btn--secondary btn--small" type="button" data-action="down" aria-label="Descendre la section" title="Descendre" ${index === last ? "disabled" : ""}>▼</button>
|
||||
<button class="btn btn--danger btn--small" type="button" data-action="delete">Supprimer</button>`
|
||||
: ""
|
||||
}
|
||||
</div>
|
||||
`;
|
||||
details.querySelectorAll(".library-section__toolbar button").forEach((button) => {
|
||||
button.addEventListener("click", () =>
|
||||
handleSectionAction(button.dataset.action, section, index, button)
|
||||
);
|
||||
});
|
||||
|
||||
if (tracks.length === 0) {
|
||||
const empty = document.createElement("p");
|
||||
empty.className = "hint library-section__empty";
|
||||
empty.textContent = "Aucun morceau dans cette section : choisis-la avec « Modifier » sur un morceau.";
|
||||
details.append(empty);
|
||||
} else {
|
||||
details.append(renderTrackList(shown));
|
||||
}
|
||||
return details;
|
||||
}
|
||||
|
||||
function renderTrackList(tracks) {
|
||||
const list = document.createElement("ul");
|
||||
list.className = "list list--stack";
|
||||
for (const track of tracks) {
|
||||
const li = document.createElement("li");
|
||||
li.className = "media-item media-item--library";
|
||||
const duration = formatDuration(track.duration);
|
||||
li.innerHTML = `
|
||||
${coverHtml(track.coverUrl)}
|
||||
<div class="media-item__info">
|
||||
<div class="media-item__title">${escapeHtml(track.title || track.originalName)}</div>
|
||||
<div class="media-item__meta">
|
||||
|
|
@ -382,7 +526,7 @@ function renderLibrary() {
|
|||
</div>
|
||||
<div class="media-item__actions">
|
||||
<button class="btn btn--small" type="button" data-action="enqueue">Ajouter</button>
|
||||
<button class="btn btn--secondary btn--small" type="button" data-action="rename">Renommer</button>
|
||||
<button class="btn btn--secondary btn--small" type="button" data-action="edit">Modifier</button>
|
||||
<button class="btn btn--danger btn--small" type="button" data-action="delete">Supprimer</button>
|
||||
</div>
|
||||
`;
|
||||
|
|
@ -391,8 +535,23 @@ function renderLibrary() {
|
|||
handleLibraryAction(button.dataset.action, track, button)
|
||||
);
|
||||
});
|
||||
elements.libraryList.appendChild(li);
|
||||
});
|
||||
list.append(li);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// Listes de sections du formulaire d'ajout et de la fenêtre de modification.
|
||||
function renderSectionChoices() {
|
||||
for (const select of [elements.uploadSectionSelect, elements.trackSectionSelect]) {
|
||||
const selected = select.value;
|
||||
select.replaceChildren(new Option("Sans section", ""));
|
||||
for (const section of state.sections) {
|
||||
select.append(new Option(section.name, section.id));
|
||||
}
|
||||
select.value = state.sections.some((section) => section.id === selected) ? selected : "";
|
||||
}
|
||||
elements.uploadSectionField.hidden =
|
||||
state.sections.length === 0 || !elements.permanentCheckbox.checked;
|
||||
}
|
||||
|
||||
function renderControls() {
|
||||
|
|
@ -463,13 +622,9 @@ async function handleLibraryAction(action, track, button) {
|
|||
})
|
||||
);
|
||||
setStatus(`« ${track.title || track.originalName} » ajouté à la file`, "success");
|
||||
} else if (action === "rename") {
|
||||
const title = prompt("Nouveau titre", track.title || track.originalName);
|
||||
if (!title || !title.trim()) return;
|
||||
await withBusyButton(button, () =>
|
||||
apiFetch(`/library/${track.id}`, { method: "PATCH", body: { title: title.trim() } })
|
||||
);
|
||||
if (!state.live) await refreshLibrary();
|
||||
} else if (action === "edit") {
|
||||
openTrackEditor(track);
|
||||
return;
|
||||
} else if (action === "delete") {
|
||||
if (!confirm(`Supprimer « ${track.title || track.originalName} » de la bibliothèque ?`)) {
|
||||
return;
|
||||
|
|
@ -485,12 +640,13 @@ async function handleLibraryAction(action, track, button) {
|
|||
}
|
||||
}
|
||||
|
||||
async function enqueueAll(shuffle, button) {
|
||||
// sectionId : undefined pour toute la bibliothèque, null pour les morceaux sans section.
|
||||
async function enqueueAll(shuffle, button, sectionId) {
|
||||
try {
|
||||
const { tracks } = await withBusyButton(button, () =>
|
||||
apiFetch("/library/enqueue-all", {
|
||||
method: "POST",
|
||||
body: { shuffle, requestedBy: requesterName() },
|
||||
body: { shuffle, sectionId, requestedBy: requesterName() },
|
||||
})
|
||||
);
|
||||
setStatus(`${tracks.length} morceau(x) ajouté(s) à la file`, "success");
|
||||
|
|
@ -500,8 +656,143 @@ async function enqueueAll(shuffle, button) {
|
|||
}
|
||||
}
|
||||
|
||||
async function createSection(button) {
|
||||
const name = prompt("Nom de la nouvelle section");
|
||||
if (!name || !name.trim()) return;
|
||||
try {
|
||||
await withBusyButton(button, () =>
|
||||
apiFetch("/library/sections", { method: "POST", body: { name: name.trim() } })
|
||||
);
|
||||
if (!state.live) await refreshLibrary();
|
||||
} catch (error) {
|
||||
setStatus(`Création de la section impossible : ${error.message}`, "error");
|
||||
}
|
||||
}
|
||||
|
||||
// section vaut null pour le groupe « Sans section », qui n'a que les actions d'ajout.
|
||||
async function handleSectionAction(action, section, index, button) {
|
||||
try {
|
||||
if (action === "enqueue" || action === "shuffle") {
|
||||
await enqueueAll(action === "shuffle", button, section?.id ?? null);
|
||||
return;
|
||||
}
|
||||
if (action === "rename") {
|
||||
const name = prompt("Nouveau nom de la section", section.name);
|
||||
if (!name || !name.trim()) return;
|
||||
await withBusyButton(button, () =>
|
||||
apiFetch(`/library/sections/${section.id}`, {
|
||||
method: "PATCH",
|
||||
body: { name: name.trim() },
|
||||
})
|
||||
);
|
||||
} else if (action === "up" || action === "down") {
|
||||
const position = index + (action === "up" ? -1 : 1);
|
||||
await withBusyButton(button, () =>
|
||||
apiFetch(`/library/sections/${section.id}`, { method: "PATCH", body: { position } })
|
||||
);
|
||||
} else if (action === "delete") {
|
||||
if (
|
||||
!confirm(
|
||||
`Supprimer la section « ${section.name} » ? Ses morceaux restent dans la bibliothèque, sans section.`
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await withBusyButton(button, () =>
|
||||
apiFetch(`/library/sections/${section.id}`, { method: "DELETE" })
|
||||
);
|
||||
}
|
||||
if (!state.live) await refreshLibrary();
|
||||
} catch (error) {
|
||||
setStatus(`Action sur la section impossible : ${error.message}`, "error");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fenêtre de modification d'un morceau (titre, section, pochette)
|
||||
|
||||
const MAX_COVER_SIZE = 10 * 1024 * 1024;
|
||||
let editedTrack = null;
|
||||
let removeCover = false;
|
||||
|
||||
function showCoverPreview(url) {
|
||||
const preview = elements.trackCoverPreview;
|
||||
preview.classList.toggle("cover--empty", !url);
|
||||
preview.style.backgroundImage = url ? `url("${url}")` : "";
|
||||
}
|
||||
|
||||
function openTrackEditor(track) {
|
||||
editedTrack = track;
|
||||
removeCover = false;
|
||||
elements.trackTitleInput.value = track.title || track.originalName;
|
||||
renderSectionChoices();
|
||||
elements.trackSectionSelect.value = track.sectionId ?? "";
|
||||
elements.trackCoverInput.value = "";
|
||||
elements.trackCoverRemoveBtn.hidden = !track.coverUrl;
|
||||
showCoverPreview(track.coverUrl);
|
||||
elements.trackDialog.showModal();
|
||||
}
|
||||
|
||||
function previewChosenCover() {
|
||||
const file = elements.trackCoverInput.files[0];
|
||||
if (!file) {
|
||||
showCoverPreview(removeCover ? null : editedTrack?.coverUrl);
|
||||
return;
|
||||
}
|
||||
if (file.size > MAX_COVER_SIZE) {
|
||||
setStatus("Image trop lourde : 10 Mo au plus", "error");
|
||||
elements.trackCoverInput.value = "";
|
||||
return;
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader.addEventListener("load", () => showCoverPreview(reader.result));
|
||||
reader.readAsDataURL(file);
|
||||
elements.trackCoverRemoveBtn.hidden = false;
|
||||
}
|
||||
|
||||
function clearChosenCover() {
|
||||
removeCover = true;
|
||||
elements.trackCoverInput.value = "";
|
||||
elements.trackCoverRemoveBtn.hidden = true;
|
||||
showCoverPreview(null);
|
||||
}
|
||||
|
||||
async function saveTrackEditor(event) {
|
||||
event.preventDefault();
|
||||
const track = editedTrack;
|
||||
if (!track) return;
|
||||
|
||||
const changes = {};
|
||||
const title = elements.trackTitleInput.value.trim();
|
||||
if (title && title !== (track.title || track.originalName)) changes.title = title;
|
||||
const sectionId = elements.trackSectionSelect.value || null;
|
||||
if (sectionId !== (track.sectionId ?? null)) changes.sectionId = sectionId;
|
||||
const coverFile = elements.trackCoverInput.files[0];
|
||||
|
||||
try {
|
||||
await withBusyButton(elements.trackSaveBtn, async () => {
|
||||
if (Object.keys(changes).length > 0) {
|
||||
await apiFetch(`/library/${track.id}`, { method: "PATCH", body: changes });
|
||||
}
|
||||
if (coverFile) {
|
||||
const data = new FormData();
|
||||
data.append("cover", coverFile);
|
||||
await apiFetch(`/library/${track.id}/cover`, { method: "PUT", body: data });
|
||||
} else if (removeCover && track.coverUrl) {
|
||||
await apiFetch(`/library/${track.id}/cover`, { method: "DELETE" });
|
||||
}
|
||||
});
|
||||
elements.trackDialog.close();
|
||||
if (!state.live) await refreshLibrary();
|
||||
} catch (error) {
|
||||
// La fenêtre reste ouverte : la personne peut corriger (autre image…) et réessayer.
|
||||
setStatus(`Modification impossible : ${error.message}`, "error");
|
||||
if (!state.live) await refreshLibrary();
|
||||
}
|
||||
}
|
||||
|
||||
// Envoi avec XMLHttpRequest : contrairement à fetch, il indique la progression de l'envoi.
|
||||
function uploadFile(file, { permanent, enqueue, title, onProgress }) {
|
||||
function uploadFile(file, { permanent, enqueue, section, title, onProgress }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const data = new FormData();
|
||||
data.append("file", file);
|
||||
|
|
@ -509,6 +800,7 @@ function uploadFile(file, { permanent, enqueue, title, onProgress }) {
|
|||
data.append("enqueue", String(enqueue));
|
||||
data.append("uploader", requesterName());
|
||||
if (title) data.append("notes", title);
|
||||
if (permanent && section) data.append("section", section);
|
||||
|
||||
const request = new XMLHttpRequest();
|
||||
request.open("POST", "/api/uploads");
|
||||
|
|
@ -567,6 +859,7 @@ async function handleUpload(event) {
|
|||
const options = {
|
||||
permanent: elements.permanentCheckbox.checked,
|
||||
enqueue: elements.enqueueCheckbox.checked,
|
||||
section: elements.uploadSectionSelect.value,
|
||||
};
|
||||
if (!options.permanent && !options.enqueue) {
|
||||
setStatus("Un fichier temporaire doit être ajouté à la file d'attente", "error");
|
||||
|
|
@ -621,6 +914,7 @@ async function handleUrlSubmit(event) {
|
|||
url,
|
||||
permanent: elements.permanentCheckbox.checked,
|
||||
enqueue: elements.enqueueCheckbox.checked,
|
||||
section: elements.uploadSectionSelect.value || undefined,
|
||||
uploader: requesterName(),
|
||||
},
|
||||
})
|
||||
|
|
@ -720,6 +1014,16 @@ function bindEvents() {
|
|||
});
|
||||
|
||||
elements.librarySearch.addEventListener("input", renderLibrary);
|
||||
elements.newSectionBtn.addEventListener("click", () => createSection(elements.newSectionBtn));
|
||||
elements.permanentCheckbox.addEventListener("change", renderSectionChoices);
|
||||
|
||||
elements.trackForm.addEventListener("submit", saveTrackEditor);
|
||||
elements.trackCancelBtn.addEventListener("click", () => elements.trackDialog.close());
|
||||
elements.trackCoverInput.addEventListener("change", previewChosenCover);
|
||||
elements.trackCoverRemoveBtn.addEventListener("click", clearChosenCover);
|
||||
elements.trackDialog.addEventListener("close", () => {
|
||||
editedTrack = null;
|
||||
});
|
||||
elements.enqueueAllBtn.addEventListener("click", () =>
|
||||
enqueueAll(false, elements.enqueueAllBtn)
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,20 +1,45 @@
|
|||
/*
|
||||
* Rôle : feuille de style unique du site, pour la page d'accueil (index.html) et la page du jukebox
|
||||
* (jukebox.html), y compris les éléments créés par public/scripts/jukebox.js.
|
||||
* Chargé par : public/index.html et public/jukebox.html.
|
||||
* Attention : servie telle quelle, sans compilation. Les couleurs viennent des variables de :root ;
|
||||
* leurs versions transparentes en dérivent avec color-mix() au lieu d'être recopiées en rgba().
|
||||
*/
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Variables
|
||||
*/
|
||||
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #06030d;
|
||||
--bg: #050109;
|
||||
--bg-card: rgba(22, 14, 36, 0.9);
|
||||
--bg-glass: rgba(42, 25, 66, 0.65);
|
||||
--border: rgba(255, 255, 255, 0.08);
|
||||
--accent: #b259ff;
|
||||
--accent-strong: #d66bff;
|
||||
--text: #f7f1ff;
|
||||
--muted: #cbc4d5;
|
||||
--muted-dark: #8c7ea7;
|
||||
--accent: #b259ff;
|
||||
--accent-strong: #d66bff;
|
||||
--accent-gradient: linear-gradient(120deg, var(--accent), var(--accent-strong));
|
||||
/* Texte posé sur l'accent (boutons principaux). */
|
||||
--on-accent: #08010f;
|
||||
--danger: #ff4d6d;
|
||||
--success: #59ffa7;
|
||||
/* Voiles blancs, du plus léger au plus marqué : fonds de champs, bordures, pastilles, boutons. */
|
||||
--surface-soft: rgba(255, 255, 255, 0.05);
|
||||
--border: rgba(255, 255, 255, 0.08);
|
||||
--border-strong: rgba(255, 255, 255, 0.12);
|
||||
--surface-strong: rgba(255, 255, 255, 0.15);
|
||||
--shadow: rgba(2, 0, 8, 0.45);
|
||||
--gradient: radial-gradient(circle at 20% 20%, #2d1a49, transparent 45%),
|
||||
radial-gradient(circle at 80% 0%, #551e8c, transparent 40%),
|
||||
radial-gradient(circle at 50% 80%, #150b28, transparent 30%);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Base
|
||||
*/
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
|
@ -33,7 +58,7 @@
|
|||
}
|
||||
|
||||
code {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
background: var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 0.1rem 0.35rem;
|
||||
}
|
||||
|
|
@ -42,8 +67,8 @@ body {
|
|||
margin: 0;
|
||||
min-height: 100vh;
|
||||
font-family: "Inter", "Segoe UI", system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
background: var(--gradient), #050109;
|
||||
color: #f7f1ff;
|
||||
background: var(--gradient), var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
main {
|
||||
|
|
@ -68,6 +93,10 @@ p {
|
|||
text-align: center;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* En-tête des pages (illustration, titre, connexion)
|
||||
*/
|
||||
|
||||
.hero {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
|
@ -79,33 +108,31 @@ p {
|
|||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* Page d'accueil : illustration plus grande. */
|
||||
.hero--home {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
text-align: left;
|
||||
gap: 2.75rem;
|
||||
}
|
||||
|
||||
.hero--home .hero__visual img {
|
||||
max-width: 320px;
|
||||
& .hero__visual img {
|
||||
max-width: 320px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero__content {
|
||||
flex: 1;
|
||||
min-width: 280px;
|
||||
}
|
||||
|
||||
.hero__content h1 {
|
||||
font-size: 2.2rem;
|
||||
line-height: 1.1;
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
& h1 {
|
||||
font-size: 2.2rem;
|
||||
line-height: 1.1;
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.hero__content p {
|
||||
color: var(--muted);
|
||||
font-size: 1.05rem;
|
||||
max-width: 500px;
|
||||
& p {
|
||||
color: var(--muted);
|
||||
font-size: 1.05rem;
|
||||
max-width: 500px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero__actions {
|
||||
|
|
@ -123,17 +150,13 @@ p {
|
|||
min-width: 200px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.hero__visual img {
|
||||
max-width: 200px;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
filter: drop-shadow(0 25px 45px rgba(0, 0, 0, 0.45));
|
||||
}
|
||||
|
||||
.hero__visual--large img {
|
||||
max-width: 270px;
|
||||
& img {
|
||||
max-width: 200px;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
filter: drop-shadow(0 25px 45px rgba(0, 0, 0, 0.45));
|
||||
}
|
||||
}
|
||||
|
||||
.hero__auth {
|
||||
|
|
@ -147,12 +170,16 @@ p {
|
|||
font-size: 0.9rem;
|
||||
padding: 0.35rem 0.85rem;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
background: var(--border);
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Panneaux
|
||||
*/
|
||||
|
||||
.panel {
|
||||
border-radius: 18px;
|
||||
padding: 1.75rem;
|
||||
|
|
@ -162,10 +189,11 @@ p {
|
|||
|
||||
.panel--glass {
|
||||
background: var(--bg-glass);
|
||||
box-shadow: 0 20px 38px rgba(2, 0, 8, 0.45);
|
||||
box-shadow: 0 20px 38px var(--shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
/* Fichiers glissés au-dessus de la section d'ajout. */
|
||||
.panel--dragover {
|
||||
border-color: var(--accent);
|
||||
border-style: dashed;
|
||||
|
|
@ -187,12 +215,16 @@ p {
|
|||
|
||||
.badge {
|
||||
padding: 0.35rem 0.9rem;
|
||||
background: rgba(178, 89, 255, 0.2);
|
||||
background: color-mix(in srgb, var(--accent) 20%, transparent);
|
||||
color: var(--accent);
|
||||
border-radius: 12px;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Formulaires
|
||||
*/
|
||||
|
||||
label {
|
||||
display: block;
|
||||
font-size: 0.95rem;
|
||||
|
|
@ -210,8 +242,8 @@ textarea {
|
|||
width: 100%;
|
||||
padding: 0.7rem 0.9rem;
|
||||
border-radius: 12px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--surface-soft);
|
||||
color: #fff;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
|
@ -223,8 +255,8 @@ input[type="file"] {
|
|||
input:focus,
|
||||
textarea:focus,
|
||||
select:focus {
|
||||
outline: 2px solid rgba(178, 89, 255, 0.5);
|
||||
border-color: rgba(178, 89, 255, 0.6);
|
||||
outline: 2px solid color-mix(in srgb, var(--accent) 50%, transparent);
|
||||
border-color: color-mix(in srgb, var(--accent) 60%, transparent);
|
||||
}
|
||||
|
||||
.form-checkbox {
|
||||
|
|
@ -238,36 +270,53 @@ select:focus {
|
|||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
/* Section repliable du mot de passe, quand la connexion avec Discord est proposée. */
|
||||
.key-login summary {
|
||||
cursor: pointer;
|
||||
color: var(--muted);
|
||||
margin: 1rem 0 0.75rem;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
margin-top: 1.25rem;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Boutons
|
||||
*/
|
||||
|
||||
.btn {
|
||||
border: none;
|
||||
border-radius: 999px;
|
||||
padding: 0.65rem 1.55rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
background: linear-gradient(120deg, var(--accent), var(--accent-strong));
|
||||
color: #08010f;
|
||||
background: var(--accent-gradient);
|
||||
color: var(--on-accent);
|
||||
transition: transform 0.15s ease, box-shadow 0.15s ease;
|
||||
}
|
||||
|
||||
.btn:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 10px 25px rgba(178, 89, 255, 0.35);
|
||||
}
|
||||
&:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 10px 25px color-mix(in srgb, var(--accent) 35%, transparent);
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
&:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
.btn--secondary {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
background: var(--surface-strong);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn--danger {
|
||||
background: linear-gradient(120deg, #ff4d6d, #ff89a5);
|
||||
background: linear-gradient(120deg, var(--danger), #ff89a5);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
|
|
@ -299,31 +348,30 @@ a.btn {
|
|||
padding: 0.6rem 0.9rem;
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.2;
|
||||
text-align: center;
|
||||
border: 1px solid #6f7bff;
|
||||
border-radius: 10px;
|
||||
background: #5865f2;
|
||||
box-shadow: 0 6px 16px rgba(35, 39, 96, 0.38), inset 0 1px 0 rgba(255, 255, 255, 0.14);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.btn.btn--discord svg {
|
||||
flex: 0 0 24px;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
|
||||
.btn.btn--discord:hover {
|
||||
border-color: #7c86ff;
|
||||
background: #4752c4;
|
||||
box-shadow: 0 8px 20px rgba(35, 39, 96, 0.46), inset 0 1px 0 rgba(255, 255, 255, 0.16);
|
||||
|
||||
& svg {
|
||||
flex: 0 0 24px;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
border-color: #7c86ff;
|
||||
background: #4752c4;
|
||||
box-shadow: 0 8px 20px rgba(35, 39, 96, 0.46), inset 0 1px 0 rgba(255, 255, 255, 0.16);
|
||||
}
|
||||
}
|
||||
|
||||
/* Bouton à bascule activé (boucle) : reprend l'aspect du bouton principal. */
|
||||
.btn[aria-pressed="true"] {
|
||||
background: linear-gradient(120deg, var(--accent), var(--accent-strong));
|
||||
color: #08010f;
|
||||
background: var(--accent-gradient);
|
||||
color: var(--on-accent);
|
||||
}
|
||||
|
||||
.btn:focus-visible {
|
||||
|
|
@ -337,12 +385,17 @@ a.btn {
|
|||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.key-login summary {
|
||||
cursor: pointer;
|
||||
color: var(--muted);
|
||||
margin: 1rem 0 0.75rem;
|
||||
.control-group {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1.25rem;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Lecteur : indicateur du flux en direct, morceau en cours, progression
|
||||
*/
|
||||
|
||||
.live-indicator {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
|
@ -350,23 +403,41 @@ a.btn {
|
|||
font-size: 0.85rem;
|
||||
color: var(--muted-dark);
|
||||
white-space: nowrap;
|
||||
|
||||
&::before {
|
||||
content: "";
|
||||
width: 0.55rem;
|
||||
height: 0.55rem;
|
||||
border-radius: 50%;
|
||||
background: var(--muted-dark);
|
||||
}
|
||||
|
||||
&[data-live="true"] {
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
&[data-live="true"]::before {
|
||||
background: var(--success);
|
||||
box-shadow: 0 0 0 4px color-mix(in srgb, var(--success) 15%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
.live-indicator::before {
|
||||
content: "";
|
||||
width: 0.55rem;
|
||||
height: 0.55rem;
|
||||
border-radius: 50%;
|
||||
background: var(--muted-dark);
|
||||
.player-current {
|
||||
background: rgba(0, 0, 0, 0.25);
|
||||
border-radius: 16px;
|
||||
padding: 1.2rem;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.live-indicator[data-live="true"] {
|
||||
color: var(--success);
|
||||
.player-current--empty {
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.live-indicator[data-live="true"]::before {
|
||||
background: var(--success);
|
||||
box-shadow: 0 0 0 4px rgba(89, 255, 167, 0.15);
|
||||
.player-current:not(.player-current--empty) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1.1rem;
|
||||
}
|
||||
|
||||
.progress {
|
||||
|
|
@ -383,7 +454,8 @@ a.btn {
|
|||
.progress__bar {
|
||||
height: 100%;
|
||||
width: 0;
|
||||
background: linear-gradient(120deg, var(--accent), var(--accent-strong));
|
||||
background: var(--accent-gradient);
|
||||
/* La largeur est mise à jour chaque seconde : la transition rend l'avancée continue. */
|
||||
transition: width 0.9s linear;
|
||||
}
|
||||
|
||||
|
|
@ -396,6 +468,10 @@ a.btn {
|
|||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Ajout de morceaux : envois en cours, ajout par lien
|
||||
*/
|
||||
|
||||
.upload-list {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
|
@ -407,6 +483,19 @@ a.btn {
|
|||
gap: 0.75rem;
|
||||
padding: 0.4rem 0;
|
||||
font-size: 0.9rem;
|
||||
|
||||
& progress {
|
||||
width: 100%;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
&[data-state="ok"] .upload-list__state {
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
&[data-state="error"] .upload-list__state {
|
||||
color: var(--danger);
|
||||
}
|
||||
}
|
||||
|
||||
.upload-list__name {
|
||||
|
|
@ -415,23 +504,10 @@ a.btn {
|
|||
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;
|
||||
|
|
@ -449,31 +525,9 @@ a.btn {
|
|||
margin: 0.5rem 0 0;
|
||||
}
|
||||
|
||||
.control-group {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1.25rem;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.grid--two {
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
}
|
||||
|
||||
.u-mt-1 {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
margin-top: 1.25rem;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Messages d'état (voir createStatusManager dans common.js)
|
||||
*/
|
||||
|
||||
.status {
|
||||
padding: 0.85rem 1.25rem;
|
||||
|
|
@ -484,20 +538,24 @@ a.btn {
|
|||
}
|
||||
|
||||
.status--info {
|
||||
background: rgba(178, 89, 255, 0.2);
|
||||
background: color-mix(in srgb, var(--accent) 20%, transparent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.status--error {
|
||||
background: rgba(255, 77, 109, 0.15);
|
||||
background: color-mix(in srgb, var(--danger) 15%, transparent);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.status--success {
|
||||
background: rgba(89, 255, 167, 0.15);
|
||||
background: color-mix(in srgb, var(--success) 15%, transparent);
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Listes de morceaux (file d'attente, bibliothèque)
|
||||
*/
|
||||
|
||||
.list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
|
|
@ -505,7 +563,7 @@ a.btn {
|
|||
}
|
||||
|
||||
.list--stack > li {
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.media-item {
|
||||
|
|
@ -536,18 +594,135 @@ a.btn {
|
|||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.player-current {
|
||||
background: rgba(0, 0, 0, 0.25);
|
||||
border-radius: 16px;
|
||||
padding: 1.2rem;
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
/* Pochette d'un morceau : <img>, ou <div> vide (note de musique) ou à image de fond (aperçu). */
|
||||
.cover {
|
||||
flex-shrink: 0;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 10px;
|
||||
object-fit: cover;
|
||||
background: var(--surface-soft) center / cover no-repeat;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.player-current--empty {
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
.cover--large {
|
||||
width: 96px;
|
||||
height: 96px;
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.cover--empty {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--muted-dark);
|
||||
|
||||
&::after {
|
||||
content: "♪";
|
||||
font-size: 1.4rem;
|
||||
}
|
||||
|
||||
&.cover--large::after {
|
||||
font-size: 2.4rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Bibliothèque : sections repliables et fenêtre de modification d'un morceau
|
||||
*/
|
||||
|
||||
.library {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.library-section {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
padding: 0 1rem;
|
||||
margin-bottom: 0.75rem;
|
||||
background: var(--surface-soft);
|
||||
|
||||
& .list--stack > li:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
.library-section__summary {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.25rem 0.75rem;
|
||||
padding: 0.85rem 0;
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
|
||||
&::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
&::before {
|
||||
content: "▸";
|
||||
color: var(--accent);
|
||||
transition: transform 0.15s ease;
|
||||
}
|
||||
|
||||
[open] > &::before {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
}
|
||||
|
||||
.library-section__name {
|
||||
font-weight: 600;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.library-section__count {
|
||||
color: var(--muted);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.library-section__toolbar {
|
||||
padding-bottom: 0.5rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.library-section__empty {
|
||||
padding: 0.75rem 0 1rem;
|
||||
}
|
||||
|
||||
.dialog {
|
||||
width: min(520px, calc(100% - 2rem));
|
||||
padding: 1.75rem;
|
||||
border-radius: 18px;
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--bg-card);
|
||||
color: var(--text);
|
||||
box-shadow: 0 20px 38px var(--shadow);
|
||||
|
||||
&::backdrop {
|
||||
background: color-mix(in srgb, var(--bg) 70%, transparent);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
& h2 {
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.track-editor {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.track-editor__cover-fields {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Page d'accueil : cartes vers les pages du site
|
||||
*/
|
||||
|
||||
.feature-grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
|
|
@ -563,20 +738,40 @@ a.btn {
|
|||
padding: 1.25rem 1.5rem;
|
||||
background: var(--bg-card);
|
||||
transition: transform 0.15s ease, box-shadow 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-3px);
|
||||
box-shadow: 0 15px 30px var(--shadow);
|
||||
}
|
||||
|
||||
& .pill {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.feature-grid__card:hover {
|
||||
transform: translateY(-3px);
|
||||
box-shadow: 0 15px 30px rgba(2, 0, 8, 0.45);
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Utilitaires de mise en page
|
||||
*/
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.feature-grid__card .pill {
|
||||
margin-bottom: 0.5rem;
|
||||
.grid--two {
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
}
|
||||
|
||||
.u-mt-1 {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------
|
||||
* Petits écrans
|
||||
*/
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.hero,
|
||||
.hero--home {
|
||||
.hero {
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
}
|
||||
|
|
@ -596,18 +791,11 @@ a.btn {
|
|||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.btn,
|
||||
input[type="text"],
|
||||
input[type="file"],
|
||||
select,
|
||||
textarea {
|
||||
.btn {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.control-group {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.control-group,
|
||||
.url-form__row {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
|
@ -617,12 +805,26 @@ a.btn {
|
|||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
/* Pochette et titre côte à côte, boutons en dessous sur toute la largeur. */
|
||||
.media-item {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.media-item__actions .btn {
|
||||
.media-item__info {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.media-item__actions {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
.track-editor {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.media-item__actions .btn,
|
||||
.library-section__toolbar .btn {
|
||||
width: auto;
|
||||
flex: 1;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Vérifie la syntaxe de tous les fichiers JavaScript avec `node --check` (`npm run check:syntax`),
|
||||
* y compris les scripts du front, que les tests n'importent pas.
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Commande /dice : lance les dés un par un, avec une pause entre chacun, puis donne le total
|
||||
* (ou pile et face pour un dé à deux faces).
|
||||
*/
|
||||
|
||||
import { SlashCommandBuilder, subtext } from "discord.js";
|
||||
import { setTimeout } from "node:timers/promises";
|
||||
import { getRandomInt } from "../../features/utilities.js";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Commande /maketeam : répartit une liste de joueurs au hasard en équipes. Les noms sont séparés
|
||||
* par des espaces, ou seulement par des virgules dès qu'il y en a une.
|
||||
*/
|
||||
|
||||
import { MessageFlags, SlashCommandBuilder } from "discord.js";
|
||||
import { shuffle } from "../../features/utilities.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Commande /play : ajoute à la file un fichier joint, un lien direct ou un morceau de la
|
||||
* bibliothèque (avec autocomplétion), en passant par le même ajout que la page web.
|
||||
*/
|
||||
|
||||
import { MessageFlags, SlashCommandBuilder, escapeMarkdown } from "discord.js";
|
||||
import { downloadAudio } from "../../media/downloadAudio.js";
|
||||
import { ingestAudioFile } from "../../music/ingest.js";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Commande /queue : montre, à la seule personne qui la lance, le morceau en cours et les dix
|
||||
* suivants.
|
||||
*/
|
||||
|
||||
import { MessageFlags, SlashCommandBuilder, escapeMarkdown } from "discord.js";
|
||||
import { trackLabel } from "../../features/formatTrack.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,7 @@
|
|||
/**
|
||||
* @file Commande /skip : passe au morceau suivant du jukebox.
|
||||
*/
|
||||
|
||||
import { MessageFlags, SlashCommandBuilder, escapeMarkdown } from "discord.js";
|
||||
import { trackLabel } from "../../features/formatTrack.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Commande /deletemsgs : supprime les 100 derniers messages du salon, sauf les messages épinglés
|
||||
* et ceux de plus de 14 jours, que Discord refuse de supprimer en lot.
|
||||
*/
|
||||
|
||||
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
|
||||
import { requirePermission } from "../../features/permissions.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Commande /invitation : publie dans le salon le message d'invitation temporaire, après avoir
|
||||
* vérifié le lien (option `lien` ou INVITE_LINK) et le droit du bot à y écrire.
|
||||
*/
|
||||
|
||||
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
|
||||
import { config } from "../../config.js";
|
||||
import { requirePermission } from "../../features/permissions.js";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Commande /listcommand : liste les commandes chargées par catégorie, avec leur description ;
|
||||
* une nouvelle commande y apparaît sans rien modifier ici.
|
||||
*/
|
||||
|
||||
import { MessageFlags, SlashCommandBuilder } from "discord.js";
|
||||
|
||||
// Liste construite à partir des commandes chargées : une commande ajoutée y apparaît d'office,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,7 @@
|
|||
/**
|
||||
* @file Commande /ping : vérifie que le bot répond.
|
||||
*/
|
||||
|
||||
import { MessageFlags, SlashCommandBuilder } from "discord.js";
|
||||
|
||||
const command = {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Commande /deafall : rend sourds tous les membres humains du salon vocal de la personne qui la
|
||||
* lance (à défaut, du salon configuré).
|
||||
*/
|
||||
|
||||
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
|
||||
import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.js";
|
||||
import { requirePermission } from "../../features/permissions.js";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Commande /muteall : rend muets tous les membres humains du salon vocal de la personne qui la
|
||||
* lance (à défaut, du salon configuré).
|
||||
*/
|
||||
|
||||
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
|
||||
import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.js";
|
||||
import { requirePermission } from "../../features/permissions.js";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Commande /undeafall : rend l'ouïe à tous les membres humains du salon vocal de la personne qui
|
||||
* la lance (à défaut, du salon configuré).
|
||||
*/
|
||||
|
||||
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
|
||||
import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.js";
|
||||
import { requirePermission } from "../../features/permissions.js";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Commande /unmuteall : rend la parole à tous les membres humains du salon vocal de la personne
|
||||
* qui la lance (à défaut, du salon configuré).
|
||||
*/
|
||||
|
||||
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
|
||||
import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.js";
|
||||
import { requirePermission } from "../../features/permissions.js";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,12 @@
|
|||
/**
|
||||
* @file Lit et valide les variables d'environnement au chargement, puis expose la configuration figée.
|
||||
*
|
||||
* Utilisé par : la plupart des modules du bot et du serveur web, via `config`.
|
||||
* Attention : une variable obligatoire manquante ou invalide fait échouer le démarrage ; les tests
|
||||
* définissent donc process.env avant d'importer un module qui en dépend.
|
||||
* @see README.md#configuration
|
||||
*/
|
||||
|
||||
// OWNER_USER_ID : la personne qui gère les serveurs de jeux (mentionnée dans leur message).
|
||||
// Ancien nom, encore accepté : SHINUWA_USER_ID.
|
||||
process.env.OWNER_USER_ID ||= process.env.SHINUWA_USER_ID;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Aiguille les commandes slash et l'autocomplétion vers leur commande, et prévient la personne
|
||||
* quand une commande échoue.
|
||||
*/
|
||||
|
||||
import { Events, MessageFlags } from "discord.js";
|
||||
|
||||
const ERROR_MESSAGE = "Oups, une erreur est survenue pendant la commande 😿";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Au démarrage du bot, relance la file du jukebox si quelqu'un est déjà dans le salon vocal et
|
||||
* publie l'état des serveurs de jeux.
|
||||
*/
|
||||
|
||||
import { Events } from "discord.js";
|
||||
import { showGameServers } from "../features/showGameServers.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,13 @@
|
|||
// Envoie un message privé Discord à la demande d'une application de confiance (Sokko TCG : alertes d'expédition).
|
||||
// Le texte est envoyé tel quel, sans aucune mention active ; un embed et un bouton de lien peuvent l'accompagner.
|
||||
/**
|
||||
* @file Envoie un message privé Discord à la demande d'une application de confiance (Sokko TCG :
|
||||
* alertes d'expédition), avec un embed et un bouton de lien facultatifs.
|
||||
*
|
||||
* Utilisé par : web/routes/notifications.js.
|
||||
* Attention : le texte est envoyé tel quel, sans aucune mention active. Les erreurs attendues sont
|
||||
* des DirectMessageError, dont le statut HTTP est renvoyé à l'application.
|
||||
* @see README.md#messages-privés-pour-les-applications
|
||||
*/
|
||||
|
||||
import { ButtonStyle, ComponentType } from "discord.js";
|
||||
|
||||
const USER_ID_PATTERN = /^\d{17,20}$/;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,10 @@
|
|||
/**
|
||||
* @file Formate un morceau pour les messages Discord : titre et durée lisible.
|
||||
*
|
||||
* Utilisé par : les commandes /play, /queue et /skip.
|
||||
* Attention : la page web a son propre formatDuration (public/scripts/common.js).
|
||||
*/
|
||||
|
||||
// Durée lisible : 3:07, 1:05:09.
|
||||
function formatDuration(seconds) {
|
||||
if (!Number.isFinite(seconds) || seconds < 0) return null;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,13 @@
|
|||
// Message d'invitation : le serveur n'autorise pas ses membres à créer des invitations ; un seul
|
||||
// lien à adhésion temporaire est partagé par le bot. Pour garder quelqu'un, on lui donne un rôle.
|
||||
/**
|
||||
* @file Vérifie le lien et rédige le message d'invitation : les membres ne peuvent pas créer
|
||||
* d'invitations, le bot publie un seul lien à adhésion temporaire.
|
||||
*
|
||||
* Utilisé par : la commande /invitation.
|
||||
* Attention : une invitation permanente est refusée ; pour garder quelqu'un, on lui donne un rôle.
|
||||
* Sans la permission « Gérer le serveur », le bot ne peut pas vérifier qu'elle est temporaire.
|
||||
* @see README.md#invitations
|
||||
*/
|
||||
|
||||
import { codeBlock, DiscordjsErrorCodes } from "discord.js";
|
||||
|
||||
const INVITE_URL_PATTERN =
|
||||
|
|
|
|||
|
|
@ -1,3 +1,12 @@
|
|||
/**
|
||||
* @file Vérifie qu'une personne a une permission Discord avant une commande d'administration, et lui
|
||||
* répond sinon.
|
||||
*
|
||||
* Utilisé par : /deletemsgs, /invitation et les commandes vocales.
|
||||
* Attention : setDefaultMemberPermissions ne fait que masquer la commande, et les administrateurs du
|
||||
* serveur peuvent changer ce réglage : cette vérification reste la vraie protection.
|
||||
*/
|
||||
|
||||
import { MessageFlags } from "discord.js";
|
||||
|
||||
async function requirePermission(interaction, permission) {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,14 @@
|
|||
/**
|
||||
* @file Tient à jour le message des serveurs de jeux dans le salon textuel configuré : état sondé en
|
||||
* TCP ou saisi à la main, rafraîchi toutes les deux minutes.
|
||||
*
|
||||
* Utilisé par : events/ready.js, au démarrage.
|
||||
* Attention : la liste est relue dans src/static/gameservers-list.json (absent du dépôt, modèle
|
||||
* gameservers-list.example.json) à chaque rafraîchissement ; le message n'est réédité que si son
|
||||
* contenu change.
|
||||
* @see README.md#données-persistantes
|
||||
*/
|
||||
|
||||
import net from "node:net";
|
||||
import { config } from "../config.js";
|
||||
import { getJSONData } from "./utilities.js";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,11 @@
|
|||
/**
|
||||
* @file Petits outils partagés : salon vocal d'une commande, membres rendus muets ou sourds en groupe,
|
||||
* lecture d'un JSON, tirage au hasard et mélange.
|
||||
*
|
||||
* Utilisé par : les commandes vocales, /dice, /maketeam, showGameServers.js, music/queue.js et
|
||||
* web/routes/library.js.
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import { config } from "../config.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,11 @@
|
|||
/**
|
||||
* @file Charge les commandes slash de src/commands/<catégorie>/*.js et leur donne leur catégorie.
|
||||
*
|
||||
* Utilisé par : index.js (exécution) et deployCommands.js (enregistrement auprès de Discord).
|
||||
* Attention : un nouveau dossier de commandes s'ajoute à CATEGORY_LABELS pour avoir un nom lisible
|
||||
* dans /listcommand.
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
|
|
|
|||
76
src/media/coverArt.js
Normal file
76
src/media/coverArt.js
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
/**
|
||||
* @file Fabrique les pochettes des morceaux avec ffmpeg : une image envoyée, ou la pochette intégrée
|
||||
* à un fichier audio, devient un JPEG d'au plus 512 px de côté.
|
||||
*
|
||||
* Utilisé par : web/storage/libraryCovers.js.
|
||||
* Attention : une image envoyée n'est passée à ffmpeg qu'après lecture de sa signature (PNG, JPEG,
|
||||
* WebP ou GIF), avec le décodeur de ce format imposé : ffmpeg ne doit jamais deviner le format
|
||||
* d'un fichier inconnu (une liste de lecture HLS pourrait lui faire lire des fichiers locaux). Le
|
||||
* réencodage retire aussi les métadonnées de l'image d'origine.
|
||||
*/
|
||||
|
||||
import { execFile } from "node:child_process";
|
||||
import fs from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const COVER_SIZE = 512;
|
||||
|
||||
// Signature de début de fichier → décodeur ffmpeg à imposer.
|
||||
const IMAGE_FORMATS = [
|
||||
{ demuxer: "png_pipe", matches: (bytes) => bytes.subarray(0, 8).equals(Buffer.from("\x89PNG\r\n\x1a\n", "latin1")) },
|
||||
{ demuxer: "jpeg_pipe", matches: (bytes) => bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff },
|
||||
{ demuxer: "gif", matches: (bytes) => /^GIF8[79]a$/.test(bytes.toString("latin1", 0, 6)) },
|
||||
{
|
||||
demuxer: "webp_pipe",
|
||||
matches: (bytes) =>
|
||||
bytes.toString("latin1", 0, 4) === "RIFF" && bytes.toString("latin1", 8, 12) === "WEBP",
|
||||
},
|
||||
];
|
||||
|
||||
// Décodeur ffmpeg correspondant à l'image, ou null si ce n'est pas un format accepté.
|
||||
async function detectImageFormat(filePath) {
|
||||
const handle = await fs.open(filePath, "r");
|
||||
try {
|
||||
const bytes = Buffer.alloc(12);
|
||||
const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
|
||||
if (bytesRead < bytes.length) return null;
|
||||
return IMAGE_FORMATS.find((format) => format.matches(bytes))?.demuxer ?? null;
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
// Écrit en JPEG la première image de inputPath (image seule, ou pochette d'un fichier audio).
|
||||
// Échoue si le fichier n'en contient pas. inputFormat impose le décodeur ffmpeg.
|
||||
async function createCoverImage(inputPath, outputPath, { inputFormat, run = execFileAsync } = {}) {
|
||||
await run(
|
||||
"ffmpeg",
|
||||
[
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
...(inputFormat ? ["-f", inputFormat] : []),
|
||||
"-i",
|
||||
inputPath,
|
||||
"-map",
|
||||
"0:v:0",
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-vf",
|
||||
// Réduit à COVER_SIZE au plus, sans agrandir une image plus petite.
|
||||
`scale='min(${COVER_SIZE},iw)':'min(${COVER_SIZE},ih)':force_original_aspect_ratio=decrease`,
|
||||
"-c:v",
|
||||
"mjpeg",
|
||||
"-q:v",
|
||||
"3",
|
||||
"-f",
|
||||
"image2",
|
||||
"-y",
|
||||
outputPath,
|
||||
],
|
||||
{ timeout: 15_000, maxBuffer: 1024 * 1024 }
|
||||
);
|
||||
}
|
||||
|
||||
export { createCoverImage, detectImageFormat };
|
||||
|
|
@ -1,3 +1,13 @@
|
|||
/**
|
||||
* @file Télécharge un fichier audio depuis un lien donné par un utilisateur, en refusant les adresses
|
||||
* internes (même après une redirection) et les fichiers de plus de 150 Mo.
|
||||
*
|
||||
* Utilisé par : /play et l'ajout par lien de la page web (web/routes/uploads.js).
|
||||
* Attention : l'adresse est vérifiée pendant la résolution DNS de la connexion elle-même
|
||||
* (safeLookup), pas avant : un autre client HTTP devrait lui aussi passer par safeLookup, sinon la
|
||||
* protection disparaît.
|
||||
*/
|
||||
|
||||
import dns from "node:dns";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,13 @@
|
|||
/**
|
||||
* @file Vérifie avec ffprobe qu'un fichier est de l'audio (durée, titre, artiste), et le convertit
|
||||
* avec ffmpeg en Ogg Opus au volume normalisé, prêt pour Discord.
|
||||
*
|
||||
* Utilisé par : music/ingest.js et storage/libraryMetadata.js (probeAudioFile), music/queue.js
|
||||
* (createOpusStream).
|
||||
* Attention : ffmpeg et ffprobe doivent être installés sur la machine. Fermer le flux Opus arrête
|
||||
* ffmpeg.
|
||||
*/
|
||||
|
||||
import { execFile, spawn } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,15 @@
|
|||
/**
|
||||
* @file Étape commune à tous les nouveaux morceaux (envoi web, lien, pièce jointe Discord) : vérifie
|
||||
* que le fichier est de l'audio, l'enregistre, le met en file et, s'il rejoint la
|
||||
* bibliothèque, reprend sa pochette intégrée.
|
||||
*
|
||||
* Utilisé par : /play et web/routes/uploads.js.
|
||||
* Attention : le fichier doit déjà être dans storage/temp ; en cas d'échec, il est supprimé. La
|
||||
* pochette est cherchée après la mise en file, pour ne pas retarder la lecture.
|
||||
*/
|
||||
|
||||
import { probeAudioFile } from "../media/validateAudioFile.js";
|
||||
import { fillEmbeddedCover } from "../web/storage/libraryCovers.js";
|
||||
import {
|
||||
discardUploadedFile,
|
||||
registerUploadedFile,
|
||||
|
|
@ -25,9 +36,10 @@ function defaultTitle({ title, artist }, originalName) {
|
|||
// En cas d'échec, le fichier est supprimé.
|
||||
async function ingestAudioFile(
|
||||
file,
|
||||
{ permanent = false, enqueue = true, uploader, title } = {},
|
||||
{ queue, probe = probeAudioFile }
|
||||
{ permanent = false, enqueue = true, uploader, title, sectionId = null } = {},
|
||||
{ queue, probe = probeAudioFile, createCover }
|
||||
) {
|
||||
let track;
|
||||
try {
|
||||
if (!permanent && !enqueue) {
|
||||
const error = new Error("Un fichier temporaire doit être ajouté à la file d'attente");
|
||||
|
|
@ -36,25 +48,28 @@ async function ingestAudioFile(
|
|||
}
|
||||
|
||||
const metadata = await probe(file.path);
|
||||
const track = registerUploadedFile(file, {
|
||||
track = registerUploadedFile(file, {
|
||||
permanent,
|
||||
uploader: cleanText(uploader, 80) || "inconnu",
|
||||
title: cleanText(title, 200) || defaultTitle(metadata, file.originalname),
|
||||
duration: metadata.duration,
|
||||
artist: metadata.artist,
|
||||
sectionId,
|
||||
});
|
||||
|
||||
if (permanent) {
|
||||
queue.emit("libraryUpdate");
|
||||
}
|
||||
if (enqueue) {
|
||||
queue.enqueue(track);
|
||||
}
|
||||
return track;
|
||||
} catch (error) {
|
||||
discardUploadedFile(file);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (permanent) {
|
||||
await fillEmbeddedCover(track.libraryTrackId, track.path, { create: createCover });
|
||||
queue.emit("libraryUpdate");
|
||||
}
|
||||
return track;
|
||||
}
|
||||
|
||||
export { defaultTitle, ingestAudioFile };
|
||||
|
|
|
|||
|
|
@ -1,3 +1,22 @@
|
|||
/**
|
||||
* @file File d'attente et lecteur du jukebox : joue les morceaux dans le salon vocal configuré et
|
||||
* prévient les pages web à chaque changement.
|
||||
*
|
||||
* Contexte : une seule instance, créée par index.js et partagée par les commandes Discord
|
||||
* (client.musicQueue) et le serveur web.
|
||||
* Points d'entrée : enqueue, remove, move, skip, stop, start, snapshot ; événements « queueUpdate »
|
||||
* (état de la file, émis ici) et « libraryUpdate » (bibliothèque modifiée, émis par les routes).
|
||||
* Utilisé par : index.js, /play, /queue, /skip, web/routes/ et music/ingest.js.
|
||||
* Dépend de : @discordjs/voice, media/validateAudioFile.js (flux Opus),
|
||||
* web/storage/storageManager.js (fichiers), une persistance passée au constructeur.
|
||||
* Attention :
|
||||
* - Sans morceau ou sans auditeur pendant 5 min, le bot quitte le salon. Parti faute d'auditeurs,
|
||||
* il revient dès que quelqu'un le rejoint.
|
||||
* - Un morceau temporaire est supprimé une fois joué, retiré ou en erreur, sauf en mode boucle.
|
||||
* - Toute modification de la file émet « queueUpdate » : c'est aussi ce qui l'enregistre.
|
||||
* @see README.md#jukebox
|
||||
*/
|
||||
|
||||
import { EventEmitter } from "events";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,11 @@
|
|||
/**
|
||||
* @file Enregistre la file du jukebox dans storage/runtime/queue.json pour la retrouver au redémarrage.
|
||||
*
|
||||
* Utilisé par : index.js, qui le passe à MusicQueue (option `persistence`).
|
||||
* Attention : l'écriture passe par un fichier temporaire renommé, pour ne jamais laisser un JSON à
|
||||
* moitié écrit ; au chargement, les morceaux dont le fichier a disparu sont ignorés.
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,13 @@
|
|||
/**
|
||||
* @file Sessions de la connexion avec Discord, sans stockage côté serveur : jeton signé par HMAC dans
|
||||
* un cookie, et lecture et écriture des cookies.
|
||||
*
|
||||
* Utilisé par : web/routes/auth.js.
|
||||
* Attention : changer SESSION_SECRET déconnecte tout le monde ; une session dure 30 jours et ne peut
|
||||
* pas être révoquée avant.
|
||||
* @see README.md#connexion-avec-discord
|
||||
*/
|
||||
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
|
||||
const SESSION_COOKIE = "palico_session";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,12 @@
|
|||
/**
|
||||
* @file Contrôles d'accès des routes web : clé d'API (Bearer), clé ou session Discord pour le jukebox,
|
||||
* connexions locales seulement pour les applications.
|
||||
*
|
||||
* Utilisé par : web/server.js.
|
||||
* Attention : avec une session (cookie), une requête qui modifie quelque chose doit venir du site
|
||||
* lui-même (en-tête Origin). localOnly lit l'adresse de la socket, pas req.ip.
|
||||
*/
|
||||
|
||||
import { config } from "../../config.js";
|
||||
import { createHash, timingSafeEqual } from "node:crypto";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,13 @@
|
|||
/**
|
||||
* @file Connexion avec Discord (OAuth2, portée « identify ») réservée aux membres du serveur, et
|
||||
* lecture de la session à chaque requête.
|
||||
*
|
||||
* Utilisé par : web/server.js (routes /auth et sessionMiddleware).
|
||||
* Attention : sans DISCORD_CLIENT_SECRET, WEB_PUBLIC_URL et SESSION_SECRET, les routes de connexion
|
||||
* répondent 404 ; /auth/me répond toujours, pour que la page sache quoi proposer.
|
||||
* @see README.md#connexion-avec-discord
|
||||
*/
|
||||
|
||||
import { Router } from "express";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,12 @@
|
|||
/**
|
||||
* @file Flux d'événements en direct (Server-Sent Events) vers la page du jukebox : état de la file à
|
||||
* chaque changement, et signal quand la bibliothèque change.
|
||||
*
|
||||
* Utilisé par : web/server.js (/api/events) ; lu par public/scripts/jukebox.js.
|
||||
* Attention : chaque page ouverte garde une connexion ; ses écoutes sur la file sont retirées à la
|
||||
* fermeture. Un commentaire envoyé toutes les 25 s empêche le proxy de couper la connexion.
|
||||
*/
|
||||
|
||||
import { Router } from "express";
|
||||
|
||||
const HEARTBEAT_INTERVAL = 25_000;
|
||||
|
|
|
|||
|
|
@ -1,19 +1,47 @@
|
|||
/**
|
||||
* @file Routes /api/library : liste la bibliothèque et ses sections, modifie un morceau (titre,
|
||||
* section, pochette), le supprime, et ajoute à la file un morceau, une section ou tout.
|
||||
*
|
||||
* Utilisé par : web/server.js ; appelé par la page du jukebox.
|
||||
* Attention : chaque changement émet « libraryUpdate » sur la file, que le flux /api/events relaie
|
||||
* aux pages ouvertes.
|
||||
*/
|
||||
|
||||
import { Router } from "express";
|
||||
import multer from "multer";
|
||||
import { saveCoverFromImage, setTrackCover } from "../storage/libraryCovers.js";
|
||||
import { findSection, getSections } from "../storage/librarySections.js";
|
||||
import {
|
||||
createQueueTrackFromLibrary,
|
||||
deletePermanentTrack,
|
||||
discardUploadedFile,
|
||||
findPermanentTrack,
|
||||
getPermanentLibrary,
|
||||
TEMP_DIR,
|
||||
updatePermanentTracks,
|
||||
} from "../storage/storageManager.js";
|
||||
import { serializeTrack, serializeTracks } from "../serializers.js";
|
||||
import { shuffle } from "../../features/utilities.js";
|
||||
import { librarySectionsRouter } from "./librarySections.js";
|
||||
|
||||
const coverUpload = multer({
|
||||
dest: TEMP_DIR,
|
||||
limits: { fileSize: 10 * 1024 * 1024, files: 1, fields: 0 },
|
||||
});
|
||||
|
||||
function cleanTitle(value) {
|
||||
return String(value ?? "")
|
||||
.replace(/[\u0000-\u001f]/g, "")
|
||||
.trim()
|
||||
.slice(0, 200);
|
||||
}
|
||||
|
||||
function libraryRouter({ queue }) {
|
||||
const router = Router();
|
||||
router.use("/sections", librarySectionsRouter({ queue }));
|
||||
|
||||
router.get("/", (req, res) => {
|
||||
res.json({ tracks: serializeTracks(getPermanentLibrary()) });
|
||||
res.json({ tracks: serializeTracks(getPermanentLibrary()), sections: getSections() });
|
||||
});
|
||||
|
||||
router.delete("/:libraryId", (req, res) => {
|
||||
|
|
@ -28,28 +56,75 @@ function libraryRouter({ queue }) {
|
|||
res.json({ removed: serializeTrack(track) });
|
||||
});
|
||||
|
||||
// Corps : title et/ou sectionId (null : sans section).
|
||||
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 fields = {};
|
||||
if (req.body?.title !== undefined) {
|
||||
fields.title = cleanTitle(req.body.title);
|
||||
if (!fields.title) {
|
||||
return res.status(400).json({ error: "Titre manquant" });
|
||||
}
|
||||
}
|
||||
if (req.body?.sectionId !== undefined) {
|
||||
const { sectionId } = req.body;
|
||||
if (sectionId !== null && !findSection(sectionId)) {
|
||||
return res.status(400).json({ error: "Section introuvable" });
|
||||
}
|
||||
fields.sectionId = sectionId;
|
||||
}
|
||||
if (Object.keys(fields).length === 0) {
|
||||
return res.status(400).json({ error: "Rien à modifier" });
|
||||
}
|
||||
|
||||
const [track] = updatePermanentTracks(new Map([[req.params.libraryId, { title }]]));
|
||||
const [track] = updatePermanentTracks(new Map([[req.params.libraryId, fields]]));
|
||||
if (!track) {
|
||||
return res.status(404).json({ error: "Fichier permanent introuvable" });
|
||||
}
|
||||
|
||||
queue.renameLibraryTrack(track.id, title);
|
||||
if (fields.title) {
|
||||
queue.renameLibraryTrack(track.id, fields.title);
|
||||
}
|
||||
queue.emit("libraryUpdate");
|
||||
res.json({ track: serializeTrack(track) });
|
||||
});
|
||||
|
||||
// Ajoute toute la bibliothèque à la file, mélangée si shuffle vaut true.
|
||||
// Remplace la pochette par l'image envoyée (champ « cover »).
|
||||
router.put("/:libraryId/cover", coverUpload.single("cover"), async (req, res) => {
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ error: "Aucune image reçue" });
|
||||
}
|
||||
try {
|
||||
if (!findPermanentTrack(req.params.libraryId)) {
|
||||
return res.status(404).json({ error: "Fichier permanent introuvable" });
|
||||
}
|
||||
const cover = await saveCoverFromImage(req.file.path);
|
||||
const track = setTrackCover(req.params.libraryId, cover);
|
||||
if (!track) {
|
||||
return res.status(404).json({ error: "Fichier permanent introuvable" });
|
||||
}
|
||||
queue.emit("libraryUpdate");
|
||||
res.json({ track: serializeTrack(track) });
|
||||
} finally {
|
||||
discardUploadedFile(req.file);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete("/:libraryId/cover", (req, res) => {
|
||||
const track = setTrackCover(req.params.libraryId, null);
|
||||
if (!track) {
|
||||
return res.status(404).json({ error: "Fichier permanent introuvable" });
|
||||
}
|
||||
queue.emit("libraryUpdate");
|
||||
res.json({ track: serializeTrack(track) });
|
||||
});
|
||||
|
||||
// Ajoute la bibliothèque à la file, mélangée si shuffle vaut true. Avec sectionId, seulement
|
||||
// cette section (null : les morceaux sans section).
|
||||
router.post("/enqueue-all", (req, res) => {
|
||||
const entries = getPermanentLibrary();
|
||||
let entries = getPermanentLibrary();
|
||||
if (req.body?.sectionId !== undefined) {
|
||||
entries = entries.filter((entry) => (entry.sectionId ?? null) === req.body.sectionId);
|
||||
}
|
||||
if (req.body?.shuffle === true) {
|
||||
shuffle(entries);
|
||||
}
|
||||
|
|
|
|||
44
src/web/routes/librarySections.js
Normal file
44
src/web/routes/librarySections.js
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
/**
|
||||
* @file Routes /api/library/sections : crée, renomme, déplace et supprime les sections de la
|
||||
* bibliothèque.
|
||||
*/
|
||||
|
||||
import { Router } from "express";
|
||||
import { createSection, deleteSection, updateSection } from "../storage/librarySections.js";
|
||||
|
||||
function librarySectionsRouter({ queue }) {
|
||||
const router = Router();
|
||||
|
||||
router.post("/", (req, res) => {
|
||||
const section = createSection(req.body?.name);
|
||||
queue.emit("libraryUpdate");
|
||||
res.status(201).json({ section });
|
||||
});
|
||||
|
||||
// Corps : name (nouveau nom) et/ou position (nouvel emplacement, 0 en tête).
|
||||
router.patch("/:sectionId", (req, res) => {
|
||||
const { name, position } = req.body ?? {};
|
||||
if (name === undefined && position === undefined) {
|
||||
return res.status(400).json({ error: "Rien à modifier" });
|
||||
}
|
||||
const section = updateSection(req.params.sectionId, { name, position });
|
||||
if (!section) {
|
||||
return res.status(404).json({ error: "Section introuvable" });
|
||||
}
|
||||
queue.emit("libraryUpdate");
|
||||
res.json({ section });
|
||||
});
|
||||
|
||||
router.delete("/:sectionId", (req, res) => {
|
||||
const section = deleteSection(req.params.sectionId);
|
||||
if (!section) {
|
||||
return res.status(404).json({ error: "Section introuvable" });
|
||||
}
|
||||
queue.emit("libraryUpdate");
|
||||
res.json({ removed: section });
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
export { librarySectionsRouter };
|
||||
|
|
@ -1,3 +1,11 @@
|
|||
/**
|
||||
* @file Route /api/notifications/dm : envoie un message privé Discord pour une application de
|
||||
* confiance (Sokko TCG) et journalise chaque demande sans son contenu.
|
||||
*
|
||||
* Utilisé par : web/server.js, derrière localOnly et la clé NOTIFICATIONS_API_KEY.
|
||||
* @see README.md#messages-privés-pour-les-applications
|
||||
*/
|
||||
|
||||
import { Router } from "express";
|
||||
import { DirectMessageError, sendDirectMessage } from "../../features/directMessages.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Routes /api/player : boutons du lecteur (lecture, pause, reprise, suivant, arrêt, mélange,
|
||||
* boucle) ; chacune renvoie le nouvel état de la file.
|
||||
*/
|
||||
|
||||
import { Router } from "express";
|
||||
|
||||
function playerRouter({ queue }) {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Routes /api/queue : état de la file, ajout d'un morceau de la bibliothèque, retrait et
|
||||
* déplacement d'un morceau.
|
||||
*/
|
||||
|
||||
import { Router } from "express";
|
||||
import { createQueueTrackFromLibrary, findPermanentTrack } from "../storage/storageManager.js";
|
||||
import { serializeTrack } from "../serializers.js";
|
||||
|
|
|
|||
|
|
@ -1,8 +1,18 @@
|
|||
/**
|
||||
* @file Routes /api/uploads : ajout d'un morceau par envoi de fichier ou par lien direct, mis en file
|
||||
* et, si demandé, gardé dans la bibliothèque (dans la section choisie).
|
||||
*
|
||||
* Utilisé par : web/server.js ; appelé par les formulaires d'ajout de la page du jukebox.
|
||||
* Attention : le type MIME annoncé par le navigateur n'est pas filtré ; ffprobe vérifie le contenu
|
||||
* réel après l'envoi (music/ingest.js).
|
||||
*/
|
||||
|
||||
import { Router } from "express";
|
||||
import multer from "multer";
|
||||
import { downloadAudio } from "../../media/downloadAudio.js";
|
||||
import { ingestAudioFile } from "../../music/ingest.js";
|
||||
import { serializeTrack } from "../serializers.js";
|
||||
import { findSection } from "../storage/librarySections.js";
|
||||
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
|
||||
|
|
@ -12,7 +22,7 @@ const upload = multer({
|
|||
dest: TEMP_DIR,
|
||||
limits: {
|
||||
fileSize: 150 * 1024 * 1024,
|
||||
fields: 4,
|
||||
fields: 5,
|
||||
fieldSize: 512,
|
||||
},
|
||||
fileFilter: (_req, file, callback) => {
|
||||
|
|
@ -35,6 +45,8 @@ function uploadsRouter({ queue }) {
|
|||
enqueue: body?.enqueue !== "false" && body?.enqueue !== false,
|
||||
uploader: user?.name || body?.uploader || "web-ui",
|
||||
title: body?.notes,
|
||||
// Section inconnue (supprimée entre-temps) : le morceau est rangé sans section.
|
||||
sectionId: findSection(body?.section)?.id ?? null,
|
||||
});
|
||||
|
||||
router.post("/", upload.single("file"), async (req, res, next) => {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,20 @@
|
|||
/**
|
||||
* @file Prépare les morceaux pour l'API : retire le chemin et le nom du fichier sur le disque, et
|
||||
* remplace le nom de la pochette par son adresse.
|
||||
*
|
||||
* Utilisé par : music/queue.js (snapshot) et les routes web.
|
||||
* Attention : tout morceau envoyé à une page ou à un client passe par ici.
|
||||
*/
|
||||
|
||||
function serializeTrack(track) {
|
||||
if (!track) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { path: _path, storedName: _storedName, ...publicTrack } = track;
|
||||
const { path: _path, storedName: _storedName, cover, ...publicTrack } = track;
|
||||
if (cover) {
|
||||
publicTrack.coverUrl = `/covers/${encodeURIComponent(cover)}`;
|
||||
}
|
||||
return publicTrack;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,23 @@
|
|||
/**
|
||||
* @file Serveur web du jukebox : API protégée, connexion avec Discord, flux en direct, pages statiques
|
||||
* et messages privés pour les applications locales.
|
||||
*
|
||||
* Contexte : démarré par index.js dans le même processus que le bot, derrière Caddy en production.
|
||||
* Points d'entrée : createApp (application Express seule, utilisée par les tests) et startWebServer
|
||||
* (écoute, nettoyage horaire de storage/temp, complément des métadonnées de la bibliothèque).
|
||||
* Utilisé par : index.js et les tests web.
|
||||
* Dépend de : routes/, middlewares/auth.js, storage/.
|
||||
* Attention :
|
||||
* - Chaque groupe de routes a sa propre limite de requêtes ; seules les réponses 401 comptent dans
|
||||
* la limite contre la force brute.
|
||||
* - /api/notifications n'accepte que les connexions locales et sa propre clé, distincte de celle du
|
||||
* jukebox.
|
||||
* - Les pochettes (/covers) sont servies sans authentification : une balise <img> n'envoie pas la
|
||||
* clé. Leurs noms aléatoires ne sont donnés que par l'API, et un nom ne change jamais de
|
||||
* contenu (cache d'un an).
|
||||
* @see README.md#jukebox
|
||||
*/
|
||||
|
||||
import express from "express";
|
||||
import helmet from "helmet";
|
||||
import { rateLimit } from "express-rate-limit";
|
||||
|
|
@ -19,6 +39,7 @@ import { uploadsRouter } from "./routes/uploads.js";
|
|||
import { backfillLibraryMetadata } from "./storage/libraryMetadata.js";
|
||||
import {
|
||||
cleanupTemporaryFiles,
|
||||
COVERS_DIR,
|
||||
ensureStorageLayout,
|
||||
} from "./storage/storageManager.js";
|
||||
|
||||
|
|
@ -128,6 +149,10 @@ function createApp(
|
|||
apiRouter.use("/events", eventsRouter(dependencies));
|
||||
|
||||
app.use("/api", apiRouter);
|
||||
app.use(
|
||||
"/covers",
|
||||
express.static(COVERS_DIR, { immutable: true, maxAge: "365d", index: false, redirect: false })
|
||||
);
|
||||
app.get(["/jukebox", "/jukebox/"], (_req, res) =>
|
||||
res.sendFile(path.join(PUBLIC_DIR, "jukebox.html"))
|
||||
);
|
||||
|
|
|
|||
89
src/web/storage/libraryCovers.js
Normal file
89
src/web/storage/libraryCovers.js
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
/**
|
||||
* @file Pochettes des morceaux de la bibliothèque : reprise de la pochette intégrée au fichier audio,
|
||||
* remplacement par une image envoyée depuis la page, retrait.
|
||||
*
|
||||
* Utilisé par : music/ingest.js (nouveau morceau), storage/libraryMetadata.js (morceaux plus
|
||||
* anciens), web/routes/library.js (envoi et retrait depuis la page).
|
||||
* Attention :
|
||||
* - Le champ `cover` d'une entrée vaut le nom du fichier dans storage/covers, null si le morceau
|
||||
* n'a pas de pochette, et il est absent tant que la pochette intégrée n'a pas été cherchée.
|
||||
* - Chaque pochette reçoit un nouveau nom aléatoire et l'ancienne est supprimée : le navigateur
|
||||
* peut garder une pochette en cache indéfiniment (servie sous /covers par web/server.js).
|
||||
*/
|
||||
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createCoverImage, detectImageFormat } from "../../media/coverArt.js";
|
||||
import {
|
||||
COVERS_DIR,
|
||||
deleteCoverFile,
|
||||
findPermanentTrack,
|
||||
updatePermanentTracks,
|
||||
} from "./storageManager.js";
|
||||
|
||||
function httpError(status, message, cause) {
|
||||
return Object.assign(new Error(message, { cause }), { status });
|
||||
}
|
||||
|
||||
// create : remplace createCoverImage (tests).
|
||||
async function writeCover(inputPath, { create = createCoverImage, inputFormat } = {}) {
|
||||
const name = `${randomUUID()}.jpg`;
|
||||
try {
|
||||
await create(inputPath, path.join(COVERS_DIR, name), { inputFormat });
|
||||
return name;
|
||||
} catch (error) {
|
||||
deleteCoverFile(name);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Pochette intégrée au fichier audio, ou null s'il n'en a pas (ou si ffmpeg ne la lit pas).
|
||||
async function saveCoverFromAudio(audioPath, options) {
|
||||
try {
|
||||
return await writeCover(audioPath, options);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Pochette tirée d'une image envoyée. Erreur 400 si ce n'est pas une image PNG, JPEG, WebP ou GIF.
|
||||
async function saveCoverFromImage(imagePath, options) {
|
||||
const inputFormat = await detectImageFormat(imagePath);
|
||||
if (!inputFormat) {
|
||||
throw httpError(400, "Image non reconnue : PNG, JPEG, WebP ou GIF attendu");
|
||||
}
|
||||
try {
|
||||
return await writeCover(imagePath, { ...options, inputFormat });
|
||||
} catch (error) {
|
||||
throw httpError(400, "Impossible de lire cette image", error);
|
||||
}
|
||||
}
|
||||
|
||||
// Donne la pochette `name` (null : aucune) au morceau et supprime l'ancienne. Renvoie l'entrée,
|
||||
// ou null si le morceau n'existe plus : la nouvelle pochette est alors supprimée.
|
||||
function setTrackCover(trackId, name) {
|
||||
const previous = findPermanentTrack(trackId);
|
||||
if (!previous) {
|
||||
deleteCoverFile(name);
|
||||
return null;
|
||||
}
|
||||
const [track] = updatePermanentTracks(new Map([[trackId, { cover: name }]]));
|
||||
if (previous.cover && previous.cover !== name) {
|
||||
deleteCoverFile(previous.cover);
|
||||
}
|
||||
return track;
|
||||
}
|
||||
|
||||
// Cherche la pochette intégrée d'un morceau jamais examiné. Si une pochette lui a été donnée
|
||||
// pendant la recherche, elle est gardée. Renvoie l'entrée mise à jour, ou null.
|
||||
async function fillEmbeddedCover(trackId, audioPath, options) {
|
||||
const name = await saveCoverFromAudio(audioPath, options);
|
||||
const current = findPermanentTrack(trackId);
|
||||
if (!current || current.cover !== undefined) {
|
||||
deleteCoverFile(name);
|
||||
return null;
|
||||
}
|
||||
return updatePermanentTracks(new Map([[trackId, { cover: name }]]))[0];
|
||||
}
|
||||
|
||||
export { fillEmbeddedCover, saveCoverFromImage, setTrackCover };
|
||||
|
|
@ -1,13 +1,22 @@
|
|||
/**
|
||||
* @file Complète au démarrage la durée, l'artiste et la pochette intégrée des morceaux de la
|
||||
* bibliothèque ajoutés avant que l'envoi ne les relève.
|
||||
*
|
||||
* Utilisé par : web/server.js (startWebServer).
|
||||
* Attention : un fichier illisible est ignoré et retenté au démarrage suivant, sauf pour la
|
||||
* pochette : un morceau examiné une fois sans pochette garde `cover: null`.
|
||||
*/
|
||||
|
||||
import { probeAudioFile } from "../../media/validateAudioFile.js";
|
||||
import { fillEmbeddedCover } from "./libraryCovers.js";
|
||||
import { getPermanentLibrary, updatePermanentTracks } from "./storageManager.js";
|
||||
|
||||
// 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);
|
||||
// Renvoie les entrées modifiées. probe et createCover remplacent ffprobe et ffmpeg (tests).
|
||||
async function backfillLibraryMetadata({ probe = probeAudioFile, createCover } = {}) {
|
||||
const library = getPermanentLibrary();
|
||||
const updates = new Map();
|
||||
|
||||
for (const entry of missing) {
|
||||
for (const entry of library.filter((item) => item.duration == null)) {
|
||||
try {
|
||||
const { duration, artist } = await probe(entry.path);
|
||||
if (duration != null) {
|
||||
|
|
@ -17,8 +26,16 @@ async function backfillLibraryMetadata({ probe = probeAudioFile } = {}) {
|
|||
console.error(`Unable to read metadata of library entry ${entry.id}`, error.cause ?? error);
|
||||
}
|
||||
}
|
||||
const updated = new Map(updatePermanentTracks(updates).map((entry) => [entry.id, entry]));
|
||||
|
||||
return updatePermanentTracks(updates);
|
||||
for (const entry of library.filter((item) => item.cover === undefined)) {
|
||||
const withCover = await fillEmbeddedCover(entry.id, entry.path, { create: createCover });
|
||||
if (withCover?.cover) {
|
||||
updated.set(withCover.id, withCover);
|
||||
}
|
||||
}
|
||||
|
||||
return [...updated.values()];
|
||||
}
|
||||
|
||||
export { backfillLibraryMetadata };
|
||||
|
|
|
|||
107
src/web/storage/librarySections.js
Normal file
107
src/web/storage/librarySections.js
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
/**
|
||||
* @file Sections de la bibliothèque : liste ordonnée de groupes nommés, enregistrée dans
|
||||
* storage/runtime/sections.json. Chaque morceau désigne la sienne par son champ `sectionId`.
|
||||
*
|
||||
* Utilisé par : web/routes/librarySections.js, web/routes/library.js et uploads.js (section
|
||||
* choisie pour un morceau).
|
||||
* Attention : supprimer une section remet ses morceaux « sans section », sans les supprimer. Un
|
||||
* fichier absent vaut une liste vide.
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { getPermanentLibrary, RUNTIME_DIR, updatePermanentTracks } from "./storageManager.js";
|
||||
|
||||
const SECTIONS_FILE = path.join(RUNTIME_DIR, "sections.json");
|
||||
const MAX_SECTIONS = 100;
|
||||
const MAX_NAME_LENGTH = 80;
|
||||
|
||||
function httpError(status, message) {
|
||||
return Object.assign(new Error(message), { status });
|
||||
}
|
||||
|
||||
function cleanName(value) {
|
||||
const name = String(value ?? "")
|
||||
.replace(/[\u0000-\u001f]/g, "")
|
||||
.trim()
|
||||
.slice(0, MAX_NAME_LENGTH);
|
||||
if (!name) {
|
||||
throw httpError(400, "Nom de section manquant");
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
function getSections() {
|
||||
try {
|
||||
const sections = JSON.parse(fs.readFileSync(SECTIONS_FILE, "utf8"));
|
||||
if (!Array.isArray(sections)) {
|
||||
throw new TypeError("sections.json doit contenir un tableau");
|
||||
}
|
||||
return sections.filter(
|
||||
(section) => typeof section?.id === "string" && typeof section.name === "string"
|
||||
);
|
||||
} catch (error) {
|
||||
if (error.code === "ENOENT") return [];
|
||||
console.error("Failed to read sections file", error);
|
||||
throw new Error("Impossible de lire les sections", { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
function writeSections(sections) {
|
||||
fs.mkdirSync(RUNTIME_DIR, { recursive: true });
|
||||
const temporaryFile = `${SECTIONS_FILE}.${process.pid}.tmp`;
|
||||
fs.writeFileSync(temporaryFile, JSON.stringify(sections, null, 2));
|
||||
fs.renameSync(temporaryFile, SECTIONS_FILE);
|
||||
}
|
||||
|
||||
function findSection(id) {
|
||||
return typeof id === "string" ? getSections().find((section) => section.id === id) : undefined;
|
||||
}
|
||||
|
||||
function createSection(name) {
|
||||
const sections = getSections();
|
||||
if (sections.length >= MAX_SECTIONS) {
|
||||
throw httpError(409, `Pas plus de ${MAX_SECTIONS} sections`);
|
||||
}
|
||||
const section = { id: randomUUID(), name: cleanName(name) };
|
||||
sections.push(section);
|
||||
writeSections(sections);
|
||||
return section;
|
||||
}
|
||||
|
||||
// Renomme la section et/ou la déplace à `position` (0 : en tête). null si elle n'existe pas.
|
||||
function updateSection(id, { name, position } = {}) {
|
||||
const sections = getSections();
|
||||
const index = sections.findIndex((section) => section.id === id);
|
||||
if (index === -1) return null;
|
||||
|
||||
const section = sections[index];
|
||||
if (name !== undefined) {
|
||||
section.name = cleanName(name);
|
||||
}
|
||||
if (position !== undefined) {
|
||||
if (!Number.isInteger(position) || position < 0 || position >= sections.length) {
|
||||
throw httpError(400, "Position invalide");
|
||||
}
|
||||
sections.splice(index, 1);
|
||||
sections.splice(position, 0, section);
|
||||
}
|
||||
writeSections(sections);
|
||||
return section;
|
||||
}
|
||||
|
||||
// Supprime la section ; ses morceaux restent dans la bibliothèque, sans section.
|
||||
function deleteSection(id) {
|
||||
const sections = getSections();
|
||||
const index = sections.findIndex((section) => section.id === id);
|
||||
if (index === -1) return null;
|
||||
|
||||
const [removed] = sections.splice(index, 1);
|
||||
writeSections(sections);
|
||||
const orphans = getPermanentLibrary().filter((entry) => entry.sectionId === id);
|
||||
updatePermanentTracks(new Map(orphans.map((entry) => [entry.id, { sectionId: null }])));
|
||||
return removed;
|
||||
}
|
||||
|
||||
export { createSection, deleteSection, findSection, getSections, updateSection };
|
||||
|
|
@ -1,3 +1,25 @@
|
|||
/**
|
||||
* @file Stockage des fichiers audio : storage/temp pour les morceaux joués une seule fois,
|
||||
* storage/permanent et sa liste storage/runtime/library.json pour la bibliothèque, et
|
||||
* storage/covers pour les pochettes.
|
||||
*
|
||||
* Contexte : seul module qui crée, déplace ou supprime les fichiers audio et la liste de la
|
||||
* bibliothèque. Les pochettes sont créées par libraryCovers.js et les sections rangées par
|
||||
* librarySections.js ; une entrée n'en garde que le nom de fichier (`cover`) et l'identifiant
|
||||
* (`sectionId`).
|
||||
* Points d'entrée : registerUploadedFile (nouveau fichier), getPermanentLibrary,
|
||||
* createQueueTrackFromLibrary, cleanupTemporaryFiles, deleteTrackFile.
|
||||
* Utilisé par : music/ (ajout, file), web/routes/library.js et queue.js, /play, web/server.js.
|
||||
* Attention :
|
||||
* - Les dossiers sont fixés au chargement d'après le répertoire de travail : le bot se lance depuis
|
||||
* la racine du projet, et les tests changent de répertoire avant d'importer ce module.
|
||||
* - library.json ne garde que les noms de fichiers ; le chemin complet est recalculé à la lecture,
|
||||
* pour que le dossier puisse être déplacé.
|
||||
* - La bibliothèque est limitée à 2 Go. Les fichiers temporaires de plus de 24 h sont supprimés,
|
||||
* sauf ceux encore dans la file.
|
||||
* @see README.md#données-persistantes
|
||||
*/
|
||||
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
|
@ -6,13 +28,14 @@ const STORAGE_ROOT = path.join(process.cwd(), "storage");
|
|||
const PERMANENT_DIR = path.join(STORAGE_ROOT, "permanent");
|
||||
const TEMP_DIR = path.join(STORAGE_ROOT, "temp");
|
||||
const RUNTIME_DIR = path.join(STORAGE_ROOT, "runtime");
|
||||
const COVERS_DIR = path.join(STORAGE_ROOT, "covers");
|
||||
const LIBRARY_FILE = path.join(RUNTIME_DIR, "library.json");
|
||||
const LEGACY_LIBRARY_FILE = path.join(STORAGE_ROOT, "library.json");
|
||||
const TEMP_FILE_MAX_AGE = 24 * 60 * 60 * 1000;
|
||||
const MAX_LIBRARY_SIZE = 2 * 1024 * 1024 * 1024;
|
||||
|
||||
function ensureStorageLayout() {
|
||||
for (const directory of [PERMANENT_DIR, TEMP_DIR, RUNTIME_DIR]) {
|
||||
for (const directory of [PERMANENT_DIR, TEMP_DIR, RUNTIME_DIR, COVERS_DIR]) {
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
}
|
||||
|
||||
|
|
@ -81,6 +104,7 @@ function registerUploadedFile(
|
|||
title = file.originalname,
|
||||
duration = null,
|
||||
artist = null,
|
||||
sectionId = null,
|
||||
}
|
||||
) {
|
||||
ensureStorageLayout();
|
||||
|
|
@ -118,6 +142,7 @@ function registerUploadedFile(
|
|||
mimetype: file.mimetype,
|
||||
duration,
|
||||
artist,
|
||||
sectionId,
|
||||
uploader,
|
||||
createdAt,
|
||||
};
|
||||
|
|
@ -217,6 +242,13 @@ function discardUploadedFile(file) {
|
|||
deleteFileSafe(file?.path);
|
||||
}
|
||||
|
||||
// Supprime une pochette d'après son nom de fichier (champ `cover` d'une entrée).
|
||||
function deleteCoverFile(name) {
|
||||
if (typeof name === "string" && name && path.basename(name) === name) {
|
||||
deleteFileSafe(path.join(COVERS_DIR, name));
|
||||
}
|
||||
}
|
||||
|
||||
// Modifie des champs d'entrées de la bibliothèque : updates est une Map id → champs.
|
||||
// Relit le fichier juste avant d'écrire, pour ne pas écraser un ajout fait entre-temps.
|
||||
function updatePermanentTracks(updates) {
|
||||
|
|
@ -245,6 +277,7 @@ function deletePermanentTrack(id) {
|
|||
const [removed] = library.splice(index, 1);
|
||||
writeLibrary(library);
|
||||
deleteFileSafe(removed.path);
|
||||
deleteCoverFile(removed.cover);
|
||||
return removed;
|
||||
}
|
||||
|
||||
|
|
@ -266,7 +299,9 @@ function deleteTrackFile(track) {
|
|||
}
|
||||
|
||||
export {
|
||||
COVERS_DIR,
|
||||
PERMANENT_DIR,
|
||||
RUNTIME_DIR,
|
||||
TEMP_DIR,
|
||||
ensureStorageLayout,
|
||||
registerUploadedFile,
|
||||
|
|
@ -275,6 +310,7 @@ export {
|
|||
createQueueTrackFromLibrary,
|
||||
cleanupTemporaryFiles,
|
||||
discardUploadedFile,
|
||||
deleteCoverFile,
|
||||
deletePermanentTrack,
|
||||
updatePermanentTracks,
|
||||
handleTrackCompletion,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Vérifie la lecture des tags et la conversion en Opus avec les vrais ffprobe et ffmpeg ;
|
||||
* ignoré s'ils ne sont pas installés.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,7 @@
|
|||
/**
|
||||
* @file Vérifie que l'API du jukebox n'accepte que la clé exacte dans l'en-tête Authorization.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Vérifie que toutes les commandes se chargent, puis /listcommand, /maketeam, /queue, les
|
||||
* commandes vocales et les permissions des commandes d'administration.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
|
|
|
|||
87
test/coverArt.test.js
Normal file
87
test/coverArt.test.js
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
/**
|
||||
* @file Vérifie la fabrication des pochettes avec le vrai ffmpeg (image envoyée, pochette intégrée à
|
||||
* un MP3) et le refus des fichiers qui ne sont pas des images ; ignoré sans ffmpeg.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { createCoverImage, detectImageFormat } from "../src/media/coverArt.js";
|
||||
|
||||
const hasFfmpeg =
|
||||
spawnSync("ffmpeg", ["-version"]).status === 0 &&
|
||||
spawnSync("ffprobe", ["-version"]).status === 0;
|
||||
const skip = hasFfmpeg ? false : "ffmpeg et ffprobe sont nécessaires";
|
||||
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-cover-"));
|
||||
test.after(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
|
||||
function ffmpeg(...args) {
|
||||
const result = spawnSync("ffmpeg", ["-v", "error", "-y", ...args]);
|
||||
assert.equal(result.status, 0, result.stderr?.toString());
|
||||
}
|
||||
|
||||
function imageSize(file) {
|
||||
const result = spawnSync("ffprobe", [
|
||||
"-v", "error", "-select_streams", "v:0",
|
||||
"-show_entries", "stream=width,height,codec_name", "-of", "json", file,
|
||||
]);
|
||||
return JSON.parse(result.stdout.toString()).streams[0];
|
||||
}
|
||||
|
||||
test("image signatures are recognised, other files are not", async () => {
|
||||
const samples = {
|
||||
"a.png": Buffer.from("89504e470d0a1a0a0000000d", "hex"),
|
||||
"a.jpg": Buffer.from("ffd8ffe000104a4649460001", "hex"),
|
||||
"a.gif": Buffer.from("GIF89a\x01\x00\x01\x00\x00\x00", "latin1"),
|
||||
"a.webp": Buffer.from("RIFF\x24\x00\x00\x00WEBPVP8 ", "latin1"),
|
||||
"playlist.png": Buffer.from("#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:0\n"),
|
||||
"short.png": Buffer.from("89504e47", "hex"),
|
||||
};
|
||||
const formats = {};
|
||||
for (const [name, bytes] of Object.entries(samples)) {
|
||||
const file = path.join(directory, name);
|
||||
fs.writeFileSync(file, bytes);
|
||||
formats[name] = await detectImageFormat(file);
|
||||
}
|
||||
assert.deepEqual(formats, {
|
||||
"a.png": "png_pipe",
|
||||
"a.jpg": "jpeg_pipe",
|
||||
"a.gif": "gif",
|
||||
"a.webp": "webp_pipe",
|
||||
"playlist.png": null,
|
||||
"short.png": null,
|
||||
});
|
||||
});
|
||||
|
||||
test("an uploaded image becomes a JPEG of at most 512 px", { skip }, async () => {
|
||||
const input = path.join(directory, "wide.png");
|
||||
ffmpeg("-f", "lavfi", "-i", "color=c=purple:s=1024x256", "-frames:v", "1", input);
|
||||
const output = path.join(directory, "wide.jpg");
|
||||
|
||||
await createCoverImage(input, output, { inputFormat: await detectImageFormat(input) });
|
||||
|
||||
assert.deepEqual(imageSize(output), { codec_name: "mjpeg", width: 512, height: 128 });
|
||||
});
|
||||
|
||||
test("the cover embedded in an MP3 is extracted, and its absence is an error", { skip }, async () => {
|
||||
const picture = path.join(directory, "picture.jpg");
|
||||
ffmpeg("-f", "lavfi", "-i", "color=c=orange:s=300x300", "-frames:v", "1", picture);
|
||||
const withCover = path.join(directory, "with-cover.mp3");
|
||||
ffmpeg(
|
||||
"-f", "lavfi", "-i", "sine=frequency=440:duration=1", "-i", picture,
|
||||
"-map", "0:a", "-map", "1:v", "-c:a", "libmp3lame", "-c:v", "copy",
|
||||
"-disposition:v", "attached_pic", withCover
|
||||
);
|
||||
const withoutCover = path.join(directory, "without-cover.mp3");
|
||||
ffmpeg("-f", "lavfi", "-i", "sine=frequency=440:duration=1", "-c:a", "libmp3lame", withoutCover);
|
||||
|
||||
const output = path.join(directory, "extracted.jpg");
|
||||
await createCoverImage(withCover, output);
|
||||
assert.deepEqual(imageSize(output), { codec_name: "mjpeg", width: 300, height: 300 });
|
||||
|
||||
await assert.rejects(createCoverImage(withoutCover, path.join(directory, "none.jpg")));
|
||||
});
|
||||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Vérifie l'envoi des messages privés : mentions désactivées, contrôle du texte, des embeds et
|
||||
* des liens, erreurs Discord traduites en erreurs pour l'application.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { DirectMessageError, sendDirectMessage } from "../src/features/directMessages.js";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Couvre la connexion avec Discord : membres et non-membres, état OAuth, origine des requêtes,
|
||||
* jetons falsifiés ou expirés, et le mot de passe quand OAuth est désactivé.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Vérifie le téléchargement par lien avec un serveur local : nom du fichier, adresses internes
|
||||
* refusées (même après une redirection), taille maximale et protocoles acceptés.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import dns from "node:dns";
|
||||
|
|
|
|||
68
test/fileHeaders.test.js
Normal file
68
test/fileHeaders.test.js
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
/**
|
||||
* @file Vérifie que chaque fichier JavaScript et la feuille de style commencent par leur en-tête, et que
|
||||
* les fichiers centraux ont un en-tête complet.
|
||||
*
|
||||
* Attention : le test ne lit que la présence des rubriques ; leur contenu reste à écrire avec soin.
|
||||
* @see CONTRIBUTING.md#en-têtes-de-fichiers
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const JS_ROOTS = ["index.js", "deployCommands.js", "src", "public/scripts", "scripts", "test"];
|
||||
// Fichiers centraux : en-tête complet exigé. Un fichier qui le devient s'ajoute ici.
|
||||
const CENTRAL_FILES = [
|
||||
"index.js",
|
||||
"public/scripts/jukebox.js",
|
||||
"src/music/queue.js",
|
||||
"src/web/server.js",
|
||||
"src/web/storage/storageManager.js",
|
||||
];
|
||||
const LONG_FILE_LINES = 300;
|
||||
|
||||
function collectJavaScriptFiles(entry) {
|
||||
const absolutePath = path.join(ROOT, entry);
|
||||
if (fs.statSync(absolutePath).isFile()) {
|
||||
return entry.endsWith(".js") ? [entry] : [];
|
||||
}
|
||||
return fs
|
||||
.readdirSync(absolutePath)
|
||||
.flatMap((child) => collectJavaScriptFiles(path.posix.join(entry, child)));
|
||||
}
|
||||
|
||||
function header(content) {
|
||||
const end = content.indexOf("*/");
|
||||
return end === -1 ? "" : content.slice(0, end);
|
||||
}
|
||||
|
||||
const jsFiles = JS_ROOTS.flatMap(collectJavaScriptFiles);
|
||||
|
||||
test("every JavaScript file starts with a @file header", () => {
|
||||
const missing = jsFiles.filter((file) => {
|
||||
const content = fs.readFileSync(path.join(ROOT, file), "utf8");
|
||||
return !content.startsWith("/**\n * @file ");
|
||||
});
|
||||
assert.deepEqual(missing, []);
|
||||
});
|
||||
|
||||
test("central and long files have a complete header", () => {
|
||||
const long = jsFiles.filter(
|
||||
(file) =>
|
||||
!file.startsWith("test/") &&
|
||||
fs.readFileSync(path.join(ROOT, file), "utf8").split("\n").length > LONG_FILE_LINES
|
||||
);
|
||||
const incomplete = [...new Set([...CENTRAL_FILES, ...long])].filter((file) => {
|
||||
const text = header(fs.readFileSync(path.join(ROOT, file), "utf8"));
|
||||
return !["Contexte :", "Utilisé par :", "@see "].every((rubric) => text.includes(rubric));
|
||||
});
|
||||
assert.deepEqual(incomplete, []);
|
||||
});
|
||||
|
||||
test("the stylesheet starts with its role", () => {
|
||||
const content = fs.readFileSync(path.join(ROOT, "public/style/styles.css"), "utf8");
|
||||
assert.ok(content.startsWith("/*\n * Rôle : "));
|
||||
});
|
||||
|
|
@ -1,3 +1,7 @@
|
|||
/**
|
||||
* @file Vérifie le sondage TCP des serveurs de jeux, l'état saisi à la main et le message publié.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import net from "node:net";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Vérifie l'ajout d'un fichier : titre par défaut, mise en file avec ses métadonnées et
|
||||
* suppression d'un fichier qui n'est pas de l'audio.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { EventEmitter } from "node:events";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Vérifie la lecture des liens d'invitation, le refus des invitations permanentes ou inconnues
|
||||
* et les avertissements joints au message.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { DiscordjsErrorCodes } from "discord.js";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Vérifie que /invitation publie le lien vérifié, ou explique pourquoi le bot ne peut pas écrire
|
||||
* dans le salon.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
|
|
|
|||
118
test/libraryCovers.test.js
Normal file
118
test/libraryCovers.test.js
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
/**
|
||||
* @file Vérifie le stockage des pochettes sans ffmpeg : pochette intégrée reprise à l'ajout,
|
||||
* remplacement, refus d'un fichier qui n'est pas une image, suppression avec le morceau, et
|
||||
* adresse donnée par l'API.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { EventEmitter } from "node:events";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
// storageManager.js fixe ses dossiers au chargement, d'après le répertoire de travail.
|
||||
const originalDirectory = process.cwd();
|
||||
const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-covers-"));
|
||||
process.chdir(temporaryDirectory);
|
||||
const storage = await import("../src/web/storage/storageManager.js");
|
||||
const covers = await import("../src/web/storage/libraryCovers.js");
|
||||
const { ingestAudioFile } = await import("../src/music/ingest.js");
|
||||
const { backfillLibraryMetadata } = await import("../src/web/storage/libraryMetadata.js");
|
||||
const { serializeTrack } = await import("../src/web/serializers.js");
|
||||
storage.ensureStorageLayout();
|
||||
test.after(() => {
|
||||
process.chdir(originalDirectory);
|
||||
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// Remplace ffmpeg : écrit un faux JPEG, ou échoue comme pour un fichier sans pochette.
|
||||
const fakeCreate = async (_input, output) => fs.writeFileSync(output, "jpeg");
|
||||
const noCover = async () => {
|
||||
throw new Error("Output file does not contain any stream");
|
||||
};
|
||||
const probe = async () => ({ duration: 10, title: null, artist: null });
|
||||
|
||||
function tempFile(name, content = "audio") {
|
||||
const filePath = path.join(storage.TEMP_DIR, `upload-${name}`);
|
||||
fs.writeFileSync(filePath, Buffer.from(content, "latin1"));
|
||||
return { path: filePath, originalname: name, size: content.length, mimetype: "audio/mpeg" };
|
||||
}
|
||||
|
||||
function fakeQueue() {
|
||||
const queue = new EventEmitter();
|
||||
queue.enqueue = () => {};
|
||||
return queue;
|
||||
}
|
||||
|
||||
const coverPath = (name) => path.join(storage.COVERS_DIR, name);
|
||||
|
||||
test("a kept track takes the cover embedded in its file", async () => {
|
||||
const track = await ingestAudioFile(
|
||||
tempFile("with.mp3"),
|
||||
{ permanent: true },
|
||||
{ queue: fakeQueue(), probe, createCover: fakeCreate }
|
||||
);
|
||||
const entry = storage.findPermanentTrack(track.libraryTrackId);
|
||||
assert.match(entry.cover, /^[0-9a-f-]{36}\.jpg$/);
|
||||
assert.equal(fs.existsSync(coverPath(entry.cover)), true);
|
||||
assert.equal(serializeTrack(entry).coverUrl, `/covers/${entry.cover}`);
|
||||
assert.equal("cover" in serializeTrack(entry), false);
|
||||
|
||||
const without = await ingestAudioFile(
|
||||
tempFile("without.mp3"),
|
||||
{ permanent: true },
|
||||
{ queue: fakeQueue(), probe, createCover: noCover }
|
||||
);
|
||||
const withoutEntry = storage.findPermanentTrack(without.libraryTrackId);
|
||||
// Examiné une fois : null, pour ne pas être retenté à chaque démarrage.
|
||||
assert.equal(withoutEntry.cover, null);
|
||||
assert.equal("coverUrl" in serializeTrack(withoutEntry), false);
|
||||
});
|
||||
|
||||
test("a new cover replaces the old file, and only images are accepted", async () => {
|
||||
const id = (
|
||||
await ingestAudioFile(tempFile("c.mp3"), { permanent: true }, {
|
||||
queue: fakeQueue(), probe, createCover: fakeCreate,
|
||||
})
|
||||
).libraryTrackId;
|
||||
const oldCover = storage.findPermanentTrack(id).cover;
|
||||
|
||||
const png = tempFile("cover.png", "\x89PNG\r\n\x1a\n0000");
|
||||
const newCover = await covers.saveCoverFromImage(png.path, { create: fakeCreate });
|
||||
covers.setTrackCover(id, newCover);
|
||||
assert.equal(storage.findPermanentTrack(id).cover, newCover);
|
||||
assert.equal(fs.existsSync(coverPath(oldCover)), false);
|
||||
|
||||
const text = tempFile("cover.txt", "#EXTM3U\nfile:///etc/passwd\n");
|
||||
await assert.rejects(covers.saveCoverFromImage(text.path, { create: fakeCreate }), {
|
||||
status: 400,
|
||||
});
|
||||
|
||||
covers.setTrackCover(id, null);
|
||||
assert.equal(storage.findPermanentTrack(id).cover, null);
|
||||
assert.equal(fs.existsSync(coverPath(newCover)), false);
|
||||
});
|
||||
|
||||
test("deleting a track deletes its cover", async () => {
|
||||
const { libraryTrackId } = await ingestAudioFile(tempFile("d.mp3"), { permanent: true }, {
|
||||
queue: fakeQueue(), probe, createCover: fakeCreate,
|
||||
});
|
||||
const { cover } = storage.findPermanentTrack(libraryTrackId);
|
||||
storage.deletePermanentTrack(libraryTrackId);
|
||||
assert.equal(fs.existsSync(coverPath(cover)), false);
|
||||
});
|
||||
|
||||
test("the startup backfill looks once for the covers of older tracks", async () => {
|
||||
const older = storage.registerUploadedFile(tempFile("old.mp3"), {
|
||||
permanent: true,
|
||||
duration: 10,
|
||||
}).libraryTrackId;
|
||||
assert.equal(storage.findPermanentTrack(older).cover, undefined);
|
||||
|
||||
const updated = await backfillLibraryMetadata({ probe, createCover: fakeCreate });
|
||||
assert.deepEqual(updated.map((entry) => entry.id), [older]);
|
||||
assert.ok(storage.findPermanentTrack(older).cover);
|
||||
|
||||
assert.deepEqual(await backfillLibraryMetadata({ probe, createCover: fakeCreate }), []);
|
||||
});
|
||||
68
test/librarySections.test.js
Normal file
68
test/librarySections.test.js
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
/**
|
||||
* @file Vérifie les sections de la bibliothèque : création, renommage, déplacement, et suppression qui
|
||||
* remet ses morceaux sans section.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
// storageManager.js fixe ses dossiers au chargement, d'après le répertoire de travail.
|
||||
const originalDirectory = process.cwd();
|
||||
const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-sections-"));
|
||||
process.chdir(temporaryDirectory);
|
||||
const storage = await import("../src/web/storage/storageManager.js");
|
||||
const sections = await import("../src/web/storage/librarySections.js");
|
||||
storage.ensureStorageLayout();
|
||||
test.after(() => {
|
||||
process.chdir(originalDirectory);
|
||||
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function addTrack(name, sectionId) {
|
||||
const filePath = path.join(storage.TEMP_DIR, `upload-${name}`);
|
||||
fs.writeFileSync(filePath, "audio");
|
||||
return storage.registerUploadedFile(
|
||||
{ path: filePath, originalname: name, size: 5, mimetype: "audio/mpeg" },
|
||||
{ permanent: true, uploader: "test", sectionId }
|
||||
).libraryTrackId;
|
||||
}
|
||||
|
||||
test("sections are created, renamed and reordered", () => {
|
||||
assert.deepEqual(sections.getSections(), []);
|
||||
const chill = sections.createSection(" Chill\u0007 ");
|
||||
const boss = sections.createSection("Combats de boss");
|
||||
const menu = sections.createSection("Menus");
|
||||
assert.equal(chill.name, "Chill");
|
||||
|
||||
sections.updateSection(menu.id, { name: "Écrans titres", position: 0 });
|
||||
assert.deepEqual(
|
||||
sections.getSections().map((section) => section.name),
|
||||
["Écrans titres", "Chill", "Combats de boss"]
|
||||
);
|
||||
assert.equal(sections.findSection(boss.id).name, "Combats de boss");
|
||||
assert.equal(sections.updateSection("unknown", { name: "x" }), null);
|
||||
});
|
||||
|
||||
test("invalid names and positions are refused", () => {
|
||||
const [first] = sections.getSections();
|
||||
assert.throws(() => sections.createSection(" "), { status: 400 });
|
||||
assert.throws(() => sections.updateSection(first.id, { position: 99 }), { status: 400 });
|
||||
assert.throws(() => sections.updateSection(first.id, { position: "1" }), { status: 400 });
|
||||
});
|
||||
|
||||
test("deleting a section keeps its tracks, without a section", () => {
|
||||
const doomed = sections.createSection("À supprimer");
|
||||
const kept = sections.createSection("Gardée");
|
||||
const inDoomed = addTrack("a.mp3", doomed.id);
|
||||
const inKept = addTrack("b.mp3", kept.id);
|
||||
|
||||
assert.equal(sections.deleteSection(doomed.id).id, doomed.id);
|
||||
|
||||
assert.equal(sections.findSection(doomed.id), undefined);
|
||||
assert.equal(storage.findPermanentTrack(inDoomed).sectionId, null);
|
||||
assert.equal(storage.findPermanentTrack(inKept).sectionId, kept.id);
|
||||
assert.equal(sections.deleteSection(doomed.id), null);
|
||||
});
|
||||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Couvre la file du jukebox sans Discord : lecture, reconnexion, départ et retour du bot dans le
|
||||
* salon, mode boucle, mélange et reprise après un redémarrage.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { EventEmitter } from "node:events";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,7 @@
|
|||
/**
|
||||
* @file Vérifie que les morceaux envoyés par l'API ne montrent pas leurs chemins sur le disque.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { serializeTrack, serializeTracks } from "../src/web/serializers.js";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Vérifie la bibliothèque dans un dossier temporaire : chemins portables, migration de l'ancien
|
||||
* fichier et complément des durées manquantes.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @file Couvre l'application web : route des messages privés (clé, limite, connexions locales),
|
||||
* /readyz et flux d'événements.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue