palico-bot/src/web/storage/storageManager.js
Shinuwa 98f4d29ac7 Encode jukebox audio with native ffmpeg, normalise loudness, read metadata
- Play every track through an ffmpeg process that normalises loudness
  (EBU R128) and outputs Ogg Opus, handed to Discord as is: no more Opus
  encoding in JavaScript with opusscript. Measured at over 40x real time,
  about 2% of a core while playing. Closing the stream kills ffmpeg.
- Encoding at upload instead was ruled out: over two minutes for an 85-minute
  mix, during which the upload would hang.
- Read duration, title and artist with ffprobe at upload; default the title
  to "Artist - Title" or the file name without extension.
- Fill the duration of existing library entries at startup.
- Expose the position of the current track in queue snapshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:10:49 +01:00

288 lines
7.4 KiB
JavaScript

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 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() {
if (!fs.existsSync(STORAGE_ROOT)) {
fs.mkdirSync(STORAGE_ROOT, { recursive: true });
}
if (!fs.existsSync(PERMANENT_DIR)) {
fs.mkdirSync(PERMANENT_DIR, { recursive: true });
}
if (!fs.existsSync(TEMP_DIR)) {
fs.mkdirSync(TEMP_DIR, { recursive: true });
}
if (!fs.existsSync(RUNTIME_DIR)) {
fs.mkdirSync(RUNTIME_DIR, { 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,
}
) {
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) {
throw new Error("La bibliothèque permanente a atteint sa limite de 2 Go");
}
const rawExtension = path.extname(file.originalname).toLowerCase();
const extension = /^\.[a-z0-9]{1,10}$/.test(rawExtension)
? rawExtension
: "";
storedName = `${randomUUID()}${extension.toLowerCase()}`;
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,
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: requestedBy,
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.existsSync(filePath) && fs.unlinkSync(filePath);
} catch (error) {
console.error(`Failed to delete file ${filePath}`, error);
}
}
function discardUploadedFile(file) {
deleteFileSafe(file?.path);
}
// Modifie des champs d'entrées de la bibliothèque : updates est une Map id → champs.
// Relit le fichier juste avant d'écrire, pour ne pas écraser un ajout fait entre-temps.
function updatePermanentTracks(updates) {
const library = getPermanentLibrary();
const updated = [];
for (const entry of library) {
const fields = updates.get(entry.id);
if (fields) {
Object.assign(entry, fields);
updated.push(entry);
}
}
if (updated.length > 0) {
writeLibrary(library);
}
return updated;
}
function deletePermanentTrack(id) {
const library = getPermanentLibrary();
const index = library.findIndex((entry) => entry.id === id);
if (index === -1) {
return null;
}
const [removed] = library.splice(index, 1);
writeLibrary(library);
deleteFileSafe(removed.path);
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 {
PERMANENT_DIR,
TEMP_DIR,
ensureStorageLayout,
registerUploadedFile,
getPermanentLibrary,
findPermanentTrack,
createQueueTrackFromLibrary,
cleanupTemporaryFiles,
discardUploadedFile,
deletePermanentTrack,
updatePermanentTracks,
handleTrackCompletion,
deleteTrackFile,
};