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