Add library sections and track covers
Sections: - The library can be split into named, ordered sections, stored in storage/runtime/sections.json; each track keeps its sectionId. - Sections are created, renamed, reordered and deleted from the page (/api/library/sections). Deleting one keeps its tracks, without a section. - A section, or the tracks without one, can be queued in one go, shuffled or not (enqueue-all takes a sectionId). - The upload form (file or link) picks the section of a kept track. - Without any section, the library stays a plain list. Covers: - A kept track takes the cover embedded in its file (MP3, FLAC...), from the web page or /play garder:. Older tracks are looked at once on startup; a track without one keeps cover: null. - "Renommer" becomes "Modifier": a dialog to change the title, the section and the cover (upload with preview, or removal). - ffmpeg turns covers into JPEGs of at most 512 px, stored in storage/covers and deleted with their track. An uploaded image is only passed to ffmpeg after its signature is checked (PNG, JPEG, WebP, GIF), with that decoder forced, so ffmpeg never guesses the format of an unknown file. - Covers are served under /covers without authentication, since an <img> cannot send the key; their random names are only given by the API and never change content (one-year cache). - The current track and the queue show the cover of their library track. Docs: README lists the new data to back up; storage/covers is ignored. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
3795ee06cb
commit
11ee972636
19 changed files with 1258 additions and 76 deletions
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,12 +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 et le met en file.
|
||||
* 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é.
|
||||
* 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,
|
||||
|
|
@ -33,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");
|
||||
|
|
@ -44,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,24 +1,47 @@
|
|||
/**
|
||||
* @file Routes /api/library : liste, renomme et supprime les morceaux de la bibliothèque, et les
|
||||
* ajoute à la file un par un ou tous d'un coup (mélangés ou non).
|
||||
* @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) => {
|
||||
|
|
@ -33,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,6 +1,6 @@
|
|||
/**
|
||||
* @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.
|
||||
* 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
|
||||
|
|
@ -12,6 +12,7 @@ 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
|
||||
|
|
@ -21,7 +22,7 @@ const upload = multer({
|
|||
dest: TEMP_DIR,
|
||||
limits: {
|
||||
fileSize: 150 * 1024 * 1024,
|
||||
fields: 4,
|
||||
fields: 5,
|
||||
fieldSize: 512,
|
||||
},
|
||||
fileFilter: (_req, file, callback) => {
|
||||
|
|
@ -44,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,5 +1,6 @@
|
|||
/**
|
||||
* @file Prépare les morceaux pour l'API : retire le chemin et le nom du fichier sur le disque.
|
||||
* @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.
|
||||
|
|
@ -10,7 +11,10 @@ function serializeTrack(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;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -12,6 +12,9 @@
|
|||
* 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
|
||||
*/
|
||||
|
||||
|
|
@ -36,6 +39,7 @@ import { uploadsRouter } from "./routes/uploads.js";
|
|||
import { backfillLibraryMetadata } from "./storage/libraryMetadata.js";
|
||||
import {
|
||||
cleanupTemporaryFiles,
|
||||
COVERS_DIR,
|
||||
ensureStorageLayout,
|
||||
} from "./storage/storageManager.js";
|
||||
|
||||
|
|
@ -145,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,21 +1,22 @@
|
|||
/**
|
||||
* @file Complète au démarrage la durée et l'artiste des morceaux de la bibliothèque ajoutés avant que
|
||||
* l'envoi ne les relève.
|
||||
* @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.
|
||||
* 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) {
|
||||
|
|
@ -25,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,9 +1,12 @@
|
|||
/**
|
||||
* @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.
|
||||
* 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.
|
||||
* 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.
|
||||
|
|
@ -25,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 });
|
||||
}
|
||||
|
||||
|
|
@ -100,6 +104,7 @@ function registerUploadedFile(
|
|||
title = file.originalname,
|
||||
duration = null,
|
||||
artist = null,
|
||||
sectionId = null,
|
||||
}
|
||||
) {
|
||||
ensureStorageLayout();
|
||||
|
|
@ -137,6 +142,7 @@ function registerUploadedFile(
|
|||
mimetype: file.mimetype,
|
||||
duration,
|
||||
artist,
|
||||
sectionId,
|
||||
uploader,
|
||||
createdAt,
|
||||
};
|
||||
|
|
@ -236,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) {
|
||||
|
|
@ -264,6 +277,7 @@ function deletePermanentTrack(id) {
|
|||
const [removed] = library.splice(index, 1);
|
||||
writeLibrary(library);
|
||||
deleteFileSafe(removed.path);
|
||||
deleteCoverFile(removed.cover);
|
||||
return removed;
|
||||
}
|
||||
|
||||
|
|
@ -285,7 +299,9 @@ function deleteTrackFile(track) {
|
|||
}
|
||||
|
||||
export {
|
||||
COVERS_DIR,
|
||||
PERMANENT_DIR,
|
||||
RUNTIME_DIR,
|
||||
TEMP_DIR,
|
||||
ensureStorageLayout,
|
||||
registerUploadedFile,
|
||||
|
|
@ -294,6 +310,7 @@ export {
|
|||
createQueueTrackFromLibrary,
|
||||
cleanupTemporaryFiles,
|
||||
discardUploadedFile,
|
||||
deleteCoverFile,
|
||||
deletePermanentTrack,
|
||||
updatePermanentTracks,
|
||||
handleTrackCompletion,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue