feat(history): persist render history and keep files for 7 days

This commit is contained in:
Jannik committed 2026-08-09 20:20:09 +02:00
1 parent 7993df5d38
commit 08c59e7689
1 file changed
+87 -17
+87 -17
View File
@@ -19,29 +19,92 @@ const UPLOADS_DIR = path.join(DATA_DIR, 'uploads');
fs.mkdirSync(TEMP_DIR, { recursive: true });
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
// Cleanup on startup / rebuild
console.log('🧹 Cleaning up temporary directories on startup/rebuild...');
try {
const cleanFolder = (dir) => {
// Active export sessions and History Persistence
const HISTORY_FILE = path.join(DATA_DIR, 'history.json');
const activeSessions = new Map();
function saveHistory() {
try {
const historyData = {};
for (const [id, sess] of activeSessions.entries()) {
const { ffmpegProc, ...sessData } = sess;
historyData[id] = sessData;
}
fs.writeFileSync(HISTORY_FILE, JSON.stringify(historyData));
} catch (err) {
console.error('⚠️ Failed to save history:', err.message);
}
}
function loadHistory() {
try {
if (fs.existsSync(HISTORY_FILE)) {
const data = JSON.parse(fs.readFileSync(HISTORY_FILE, 'utf-8'));
for (const [id, sess] of Object.entries(data)) {
if (!sess.done) {
sess.error = 'Abgebrochen durch Server-Neustart';
sess.done = true;
sess.currentStatus = 'Fehler';
}
activeSessions.set(id, sess);
}
console.log(`✅ Loaded ${activeSessions.size} past sessions from history.json`);
}
} catch (err) {
console.error('⚠️ Failed to load history:', err.message);
}
}
function cleanupOldRenders() {
console.log('🧹 Running 7-day retention cleanup...');
const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
const now = Date.now();
let deletedCount = 0;
for (const [id, sess] of activeSessions.entries()) {
if (now - sess.createdAt > MAX_AGE_MS) {
if (sess.formats) {
for (const fmt of Object.values(sess.formats)) {
if (fmt.path && fs.existsSync(fmt.path)) {
try { fs.unlinkSync(fmt.path); } catch (e) {}
}
}
}
activeSessions.delete(id);
deletedCount++;
}
}
if (deletedCount > 0) {
console.log(`🗑️ Deleted ${deletedCount} old sessions.`);
saveHistory();
}
// Cleanup orphan files in TEMP_DIR and UPLOADS_DIR older than 7 days
[TEMP_DIR, UPLOADS_DIR].forEach(dir => {
if (fs.existsSync(dir)) {
const files = fs.readdirSync(dir);
for (const file of files) {
const curPath = path.join(dir, file);
if (fs.lstatSync(curPath).isDirectory()) {
fs.rmSync(curPath, { recursive: true, force: true });
} else {
fs.unlinkSync(curPath);
}
try {
const stats = fs.statSync(curPath);
if (now - stats.mtimeMs > MAX_AGE_MS) {
if (stats.isDirectory()) {
fs.rmSync(curPath, { recursive: true, force: true });
} else {
fs.unlinkSync(curPath);
}
}
} catch (e) {}
}
}
};
cleanFolder(TEMP_DIR);
cleanFolder(UPLOADS_DIR);
console.log('✅ Temporary directories cleaned successfully.');
} catch (err) {
console.error('⚠️ Warning during startup cleanup:', err.message);
});
}
loadHistory();
cleanupOldRenders();
setInterval(cleanupOldRenders, 60 * 60 * 1000);
// Multer Storage Configuration (200MB limit for high-res WAV/FLAC audio files)
const storage = multer.diskStorage({
destination: (req, file, cb) => {
@@ -83,8 +146,7 @@ app.get('/health', (req, res) => {
});
});
// Active export sessions
const activeSessions = new Map();
// Removed duplicate map init
function cleanupSession(id) {
const sess = activeSessions.get(id);
@@ -191,6 +253,7 @@ app.post('/api/export/transcode', upload.fields([
currentStatus: 'Startet...'
};
activeSessions.set(sessionId, session);
saveHistory();
// Run sequentially in background
runSequentialEncodes(session, videoPath, audioPath, ['prores', 'webm_alpha', 'qtrle', 'mp4']).catch(err => {
@@ -283,15 +346,18 @@ app.post('/api/export/start', upload.single('audio'), async (req, res) => {
currentStatus: 'Live Empfang & ProRes Render...'
};
activeSessions.set(sessionId, session);
saveHistory();
ffmpegProc.on('close', (code) => {
if (code !== 0) {
session.error = `FFmpeg Fehler beim Live-Render (Code ${code}): ${errorLog.slice(-400)}`;
console.error(`[${sessionId}] ❌ Live Render failed:`, session.error);
session.done = true;
saveHistory();
} else {
console.log(`[${sessionId}] ✅ Live Render (ProRes) complete! Starting background queue...`);
session.formats.prores.ready = true;
saveHistory();
// Start remaining encodes from the ProRes master file using the original audioPath
runSequentialEncodes(session, formats.prores.path, audioPath, ['webm_alpha', 'qtrle', 'mp4']).catch(err => {
console.error(`[${sessionId}] Background Queue Error:`, err);
@@ -302,6 +368,7 @@ app.post('/api/export/start', upload.single('audio'), async (req, res) => {
ffmpegProc.on('error', (err) => {
session.done = true;
session.error = err.message;
saveHistory();
});
res.json({ sessionId, format });
@@ -318,6 +385,7 @@ async function runSequentialEncodes(session, inputVideoPath, inputAudioPath, tar
if (!formatInfo) continue;
session.currentStatus = `Rendere ${i+1}/${targetFormats.length}: ${formatId.toUpperCase()}...`;
saveHistory();
const ffmpegArgs = ['-y', '-i', inputVideoPath];
if (inputAudioPath) {
@@ -383,6 +451,7 @@ async function runSequentialEncodes(session, inputVideoPath, inputAudioPath, tar
} else {
if (session.formats[formatId]) {
session.formats[formatId].ready = true;
saveHistory();
}
resolve();
}
@@ -404,6 +473,7 @@ async function runSequentialEncodes(session, inputVideoPath, inputAudioPath, tar
session.currentStatus = 'Fertig';
session.done = true;
saveHistory();
}
// Stream raw RGBA frame or multi-frame batch