palico-bot/src/web/storage/storageManager.js
Shinuwa 11ee972636
All checks were successful
Deploy Palico Bot / check (push) Successful in 9s
Deploy Palico Bot / deploy (push) Successful in 7s
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>
2026-12-01 21:27:49 +01:00

318 lines
9 KiB
JavaScript

/**
* @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";
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, COVERS_DIR]) {
fs.mkdirSync(directory, { recursive: true });
}
if (!fs.existsSync(LIBRARY_FILE)) {
let initialEntries = [];
if (fs.existsSync(LEGACY_LIBRARY_FILE)) {
try {
initialEntries = JSON.parse(
fs.readFileSync(LEGACY_LIBRARY_FILE, { encoding: "utf8" })
);
} catch (error) {
throw new Error("Impossible de migrer l'ancienne bibliothèque", {
cause: error,
});
}
}
const portableEntries = Array.isArray(initialEntries)
? initialEntries.map(({ path: _path, ...entry }) => entry)
: [];
fs.writeFileSync(LIBRARY_FILE, JSON.stringify(portableEntries, null, 2));
if (portableEntries.length > 0) {
console.log(
`[${new Date().toLocaleString()}] Migrated ${portableEntries.length} library entries`
);
}
}
}
function readLibrary() {
try {
const raw = fs.readFileSync(LIBRARY_FILE, { encoding: "utf8" });
const entries = JSON.parse(raw);
if (!Array.isArray(entries)) {
throw new TypeError("library.json doit contenir un tableau");
}
return entries
.filter(
(entry) =>
entry &&
typeof entry.storedName === "string" &&
path.basename(entry.storedName) === entry.storedName
)
.map((entry) => ({
...entry,
path: path.join(PERMANENT_DIR, entry.storedName),
}));
} catch (error) {
console.error("Failed to read library file", error);
throw new Error("Impossible de lire la bibliothèque", { cause: error });
}
}
function writeLibrary(entries) {
const persistedEntries = entries.map(({ path: _path, ...entry }) => entry);
const temporaryFile = `${LIBRARY_FILE}.${process.pid}.tmp`;
fs.writeFileSync(temporaryFile, JSON.stringify(persistedEntries, null, 2));
fs.renameSync(temporaryFile, LIBRARY_FILE);
}
function registerUploadedFile(
file,
{
permanent,
uploader = "unknown",
title = file.originalname,
duration = null,
artist = null,
sectionId = null,
}
) {
ensureStorageLayout();
const createdAt = new Date().toISOString();
let finalPath = file.path;
let storedName = path.basename(file.path);
let permanentEntry = null;
if (permanent) {
const library = readLibrary();
const librarySize = library.reduce(
(total, entry) => total + (Number(entry.size) || 0),
0
);
if (librarySize + file.size > MAX_LIBRARY_SIZE) {
const error = new Error("La bibliothèque permanente a atteint sa limite de 2 Go");
error.status = 413;
throw error;
}
const rawExtension = path.extname(file.originalname).toLowerCase();
const extension = /^\.[a-z0-9]{1,10}$/.test(rawExtension)
? rawExtension
: "";
storedName = `${randomUUID()}${extension}`;
finalPath = path.join(PERMANENT_DIR, storedName);
fs.renameSync(file.path, finalPath);
permanentEntry = {
id: randomUUID(),
originalName: file.originalname,
title,
storedName,
path: finalPath,
size: file.size,
mimetype: file.mimetype,
duration,
artist,
sectionId,
uploader,
createdAt,
};
library.push(permanentEntry);
writeLibrary(library);
}
return {
id: randomUUID(),
title,
originalName: file.originalname,
path: finalPath,
storedName,
size: file.size,
mimetype: file.mimetype,
duration,
artist,
permanent,
uploader,
libraryTrackId: permanentEntry ? permanentEntry.id : null,
createdAt,
};
}
function getPermanentLibrary() {
ensureStorageLayout();
return readLibrary();
}
function findPermanentTrack(id) {
return getPermanentLibrary().find((entry) => entry.id === id);
}
function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") {
if (!libraryTrack) {
return null;
}
return {
id: randomUUID(),
title: libraryTrack.title || libraryTrack.originalName,
originalName: libraryTrack.originalName,
path: libraryTrack.path,
storedName: libraryTrack.storedName,
size: libraryTrack.size,
mimetype: libraryTrack.mimetype,
duration: libraryTrack.duration ?? null,
artist: libraryTrack.artist ?? null,
permanent: true,
uploader:
String(requestedBy ?? "")
.replace(/[\u0000-\u001f]/g, "")
.trim()
.slice(0, 80) || "library",
libraryTrackId: libraryTrack.id,
createdAt: new Date().toISOString(),
};
}
// keep : chemins encore utilisés (file d'attente, morceau en cours), jamais supprimés.
function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE, { keep = new Set() } = {}) {
ensureStorageLayout();
const cutoff = Date.now() - maxAge;
for (const entry of fs.readdirSync(TEMP_DIR, { withFileTypes: true })) {
if (!entry.isFile() || entry.name === ".gitkeep") {
continue;
}
const filePath = path.join(TEMP_DIR, entry.name);
if (keep.has(filePath)) {
continue;
}
try {
if (fs.statSync(filePath).mtimeMs < cutoff) {
fs.unlinkSync(filePath);
}
} catch (error) {
console.error(`Failed to clean temporary file ${filePath}`, error);
}
}
}
function deleteFileSafe(filePath) {
if (!filePath) {
return;
}
try {
fs.rmSync(filePath, { force: true });
} catch (error) {
console.error(`Failed to delete file ${filePath}`, error);
}
}
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) {
const library = getPermanentLibrary();
const updated = [];
for (const entry of library) {
const fields = updates.get(entry.id);
if (fields) {
Object.assign(entry, fields);
updated.push(entry);
}
}
if (updated.length > 0) {
writeLibrary(library);
}
return updated;
}
function deletePermanentTrack(id) {
const library = getPermanentLibrary();
const index = library.findIndex((entry) => entry.id === id);
if (index === -1) {
return null;
}
const [removed] = library.splice(index, 1);
writeLibrary(library);
deleteFileSafe(removed.path);
deleteCoverFile(removed.cover);
return removed;
}
function handleTrackCompletion(track) {
if (!track || track.permanent) {
return;
}
deleteFileSafe(track.path);
}
function deleteTrackFile(track) {
if (!track) {
return;
}
if (!track.permanent) {
deleteFileSafe(track.path);
}
}
export {
COVERS_DIR,
PERMANENT_DIR,
RUNTIME_DIR,
TEMP_DIR,
ensureStorageLayout,
registerUploadedFile,
getPermanentLibrary,
findPermanentTrack,
createQueueTrackFromLibrary,
cleanupTemporaryFiles,
discardUploadedFile,
deleteCoverFile,
deletePermanentTrack,
updatePermanentTracks,
handleTrackCompletion,
deleteTrackFile,
};