source: Klonkt/src/routes/admin-audio.js@ 255e3d3

main
Last change on this file since 255e3d3 was fbc8628, checked in by roboburr <roboburr@…>, 3 months ago

Audio upload: WAV up to 100 MB (other formats remain 50 MB)

WAV is uncompressed → 50 MB was too tight. multer ceiling now 100 MB
(the highest), with a per-type check in the handler: .wav may be 100 MB,
compressed formats stay at 50 MB. Dropzone text updated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@…>

  • Property mode set to 100644
File size: 19.1 KB
Line 
1/**
2 * Admin: Audio Tracks management — Phase C MP3 player.
3 *
4 * GET /admin/audio -> list site tracks + upload form
5 * POST /admin/audio/upload -> multer upload, insert media + audio_tracks
6 * POST /admin/audio/:id/delete -> remove track row + file on disk
7 *
8 * Files land in storage/media/audio/ (NOT served by /media static handler —
9 * everything goes through the signed /audio/stream/ route).
10 */
11
12import express from 'express';
13import multer from 'multer';
14import path from 'path';
15import fs from 'fs';
16import { fileURLToPath } from 'url';
17import { v4 as uuid } from 'uuid';
18import db from '../config/database.js';
19import { renderPage } from '../middleware/render.js';
20import { requireGod } from '../middleware/auth.js';
21import { transcodeToMp3 } from '../services/AudioTranscoder.js';
22import { audioUrl } from '../services/AudioStreamService.js';
23
24const __dirname = path.dirname(fileURLToPath(import.meta.url));
25// Audio files live OUTSIDE storage/media so the public /media static
26// handler can't serve them — they must go through the signed /audio/stream/
27// endpoint (anti-hotlink). Covers are public and stay in /media.
28const AUDIO_DIR = path.resolve(
29 process.env.AUDIO_PATH || path.join(__dirname, '..', '..', 'storage', 'audio')
30);
31const COVER_DIR = path.resolve(
32 process.env.COVER_PATH || path.join(__dirname, '..', '..', 'storage', 'media', 'audio-covers')
33);
34fs.mkdirSync(AUDIO_DIR, { recursive: true });
35fs.mkdirSync(COVER_DIR, { recursive: true });
36
37const ALLOWED_AUDIO_EXT = new Set(['.mp3', '.m4a', '.mp4', '.aac', '.oga', '.ogg', '.opus', '.flac', '.wav', '.webm']);
38const ALLOWED_COVER_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
39const MAX_AUDIO_BYTES = 50 * 1024 * 1024; // 50 MB — gecomprimeerde formaten (mp3/m4a/ogg/…)
40const MAX_WAV_BYTES = 100 * 1024 * 1024; // 100 MB — WAV is ongecomprimeerd, dus ruimer
41const MAX_COVER_BYTES = 5 * 1024 * 1024; // 5 MB
42
43// Per-bestand bovengrens op basis van extensie. multer's globale limiet is de
44// hoogste (WAV); de echte controle per type gebeurt in de upload-handler.
45const audioByteLimitFor = (ext) => (ext.toLowerCase() === '.wav' ? MAX_WAV_BYTES : MAX_AUDIO_BYTES);
46
47// Multer routes audio + cover into separate dirs based on field name.
48const storage = multer.diskStorage({
49 destination: (req, file, cb) => {
50 cb(null, file.fieldname === 'cover' ? COVER_DIR : AUDIO_DIR);
51 },
52 filename: (req, file, cb) => {
53 const ext = path.extname(file.originalname).toLowerCase();
54 cb(null, `${uuid()}${ext}`);
55 },
56});
57
58const upload = multer({
59 storage,
60 limits: { fileSize: MAX_WAV_BYTES }, // hoogste bovengrens (WAV) — per-type check in de handler
61 fileFilter: (req, file, cb) => {
62 const ext = path.extname(file.originalname).toLowerCase();
63 if (file.fieldname === 'cover') {
64 if (!ALLOWED_COVER_EXT.has(ext)) return cb(new Error('Cover must be jpg/png/webp/gif'));
65 } else {
66 if (!ALLOWED_AUDIO_EXT.has(ext)) return cb(new Error('Unsupported audio type: ' + ext));
67 }
68 cb(null, true);
69 },
70});
71
72const router = express.Router();
73
74router.get('/', requireGod, (req, res) => {
75 const site = res.locals.site;
76 if (!site) return res.status(404).send('Site required');
77
78 const rows = db.prepare(`
79 SELECT t.id, t.title, t.artist, t.album, t.duration, t.cover_url,
80 t.position, t.created_at, m.filename, m.size, m.mime_type
81 FROM audio_tracks t
82 LEFT JOIN media m ON m.id = t.media_id
83 WHERE t.site_id = ?
84 ORDER BY t.position ASC, t.created_at ASC
85 `).all(site.id);
86
87 // Build each track's stream URL so admins can preview audio inline.
88 const tracks = rows.map(t => ({
89 ...t,
90 stream_url: t.filename ? audioUrl(t.filename) : null,
91 }));
92
93 renderPage(req, res, 'pages/admin-audio', {
94 pageTitle: 'Audio tracks',
95 bodyClass: 'on-admin',
96 tracks,
97 error: req.query.error || null,
98 success: req.query.success || null,
99 maxBytesMb: Math.round(MAX_AUDIO_BYTES / 1024 / 1024),
100 maxWavMb: Math.round(MAX_WAV_BYTES / 1024 / 1024),
101 });
102});
103
104router.post('/upload', requireGod, (req, res) => {
105 // Helper: respond appropriately to JSON-accepting callers (the bulk
106 // uploader fetch() calls) vs traditional form posts (redirect).
107 // Both code paths cover identical errors below.
108 const wantsJson = req.get('Accept')?.includes('application/json') || req.xhr;
109 const fail = (status, message) => wantsJson
110 ? res.status(status).json({ ok: false, error: message })
111 : res.redirect('/admin/audio?error=' + encodeURIComponent(message));
112 const ok = (data) => wantsJson
113 ? res.json({ ok: true, ...data })
114 : res.redirect('/admin/audio?success=' + encodeURIComponent('Uploaded: ' + data.title));
115
116 upload.fields([{ name: 'audio', maxCount: 1 }, { name: 'cover', maxCount: 1 }])(req, res, async (err) => {
117 if (err) return fail(400, err.message);
118
119 const site = res.locals.site;
120 const audioFile = req.files?.audio?.[0];
121 const coverFile = req.files?.cover?.[0];
122
123 if (!site || !audioFile) {
124 // Clean up any cover that snuck through without an audio file
125 if (coverFile) try { fs.unlinkSync(coverFile.path); } catch {}
126 return fail(400, 'missing audio file');
127 }
128
129 // Per-type audio size check. multer's globale limiet was de WAV-bovengrens
130 // (100MB); gecomprimeerde formaten blijven op 50MB.
131 const audioExt = path.extname(audioFile.originalname).toLowerCase();
132 const audioLimit = audioByteLimitFor(audioExt);
133 if (audioFile.size > audioLimit) {
134 try { fs.unlinkSync(audioFile.path); } catch {}
135 if (coverFile) try { fs.unlinkSync(coverFile.path); } catch {}
136 return fail(400, `audio te groot (max ${Math.round(audioLimit / 1024 / 1024)}MB voor ${audioExt || 'dit type'})`);
137 }
138
139 // Cover size check (multer's global limit was the audio upper bound)
140 if (coverFile && coverFile.size > MAX_COVER_BYTES) {
141 try { fs.unlinkSync(audioFile.path); } catch {}
142 try { fs.unlinkSync(coverFile.path); } catch {}
143 return fail(400, 'cover too large (max 5MB)');
144 }
145
146 const { title, artist, album } = req.body;
147 const trackId = uuid();
148 const mediaId = uuid();
149 const coverUrl = coverFile ? `/media/audio-covers/${coverFile.filename}` : null;
150
151 // ── TRANSCODE ────────────────────────────────────────────────
152 // Convert whatever the user uploaded to a uniform 192kbps stereo mp3.
153 // The original file (whatever its format) is deleted on success.
154 // multer named the upload <uuid>.<ext>; we re-use that uuid stem so
155 // the final file is just <uuid>.mp3, keeping things tidy.
156 const inputBaseName = path.basename(audioFile.filename, path.extname(audioFile.filename));
157 // Title fallback strategy:
158 // 1. Explicit `title` form field (single-upload form)
159 // 2. Original filename minus extension, with underscores → spaces
160 // (cleans up "Track_01_-_Title.mp3" patterns common from CD rips)
161 const fallbackTitle = path.basename(audioFile.originalname, path.extname(audioFile.originalname))
162 .replace(/_/g, ' ').trim();
163 const finalTitle = title?.trim() || fallbackTitle;
164 const finalArtist = artist?.trim() || null;
165 const finalAlbum = album?.trim() || null;
166
167 console.log('[admin-audio] upload received:', {
168 original: audioFile.originalname,
169 tempPath: audioFile.path,
170 size: audioFile.size,
171 hasC: !!coverFile,
172 });
173
174 let transcoded;
175 try {
176 transcoded = await transcodeToMp3({
177 inputPath: audioFile.path,
178 outputDir: AUDIO_DIR,
179 outputBaseName: inputBaseName,
180 tags: {
181 title: finalTitle,
182 artist: finalArtist || undefined,
183 album: finalAlbum || undefined,
184 },
185 });
186 console.log('[admin-audio] transcode OK:', transcoded);
187 } catch (transcodeErr) {
188 console.error('[admin-audio] Transcode failed:', transcodeErr);
189 // Transcoder kept the original on failure — clean it up ourselves
190 // since the upload as a whole has failed.
191 try { fs.unlinkSync(audioFile.path); } catch {}
192 if (coverFile) try { fs.unlinkSync(coverFile.path); } catch {}
193 return fail(500, 'Conversie mislukt: ' + transcodeErr.message);
194 }
195
196 try {
197 console.log('[admin-audio] inserting media row');
198 db.prepare(`
199 INSERT INTO media (id, site_id, filename, mime_type, size, storage_path)
200 VALUES (?, ?, ?, ?, ?, ?)
201 `).run(mediaId, site.id, transcoded.filename, transcoded.mimeType, transcoded.size, transcoded.path);
202
203 // Duur automatisch: primair uit de transcode (ffmpeg codecData), anders een
204 // optionele client-side waarde (bulk-uploader leest <audio>.duration uit),
205 // anders NULL (UI toont dan '—:—', handmatig bij te werken in de editor).
206 const clientDur = req.body.duration != null ? parseInt(req.body.duration, 10) : NaN;
207 const finalDuration =
208 (transcoded.durationSec != null && transcoded.durationSec > 0) ? transcoded.durationSec
209 : (Number.isFinite(clientDur) && clientDur > 0) ? clientDur
210 : null;
211
212 console.log('[admin-audio] inserting audio_tracks row (duration=' + finalDuration + ')');
213 db.prepare(`
214 INSERT INTO audio_tracks (id, site_id, title, artist, album, duration, cover_url, media_id, position)
215 VALUES (?, ?, ?, ?, ?, ?, ?, ?, COALESCE(
216 (SELECT MAX(position) + 1 FROM audio_tracks WHERE site_id = ?),
217 0
218 ))
219 `).run(
220 trackId, site.id,
221 finalTitle, finalArtist, finalAlbum,
222 finalDuration,
223 coverUrl,
224 mediaId, site.id
225 );
226 console.log('[admin-audio] DB inserts OK — track', trackId);
227 } catch (dbErr) {
228 console.error('[admin-audio] DB insert failed:', dbErr);
229 // DB failed — clean up the transcoded mp3 so we don't leak files
230 try { fs.unlinkSync(transcoded.path); } catch {}
231 if (coverFile) try { fs.unlinkSync(coverFile.path); } catch {}
232 return fail(500, dbErr.message);
233 }
234
235 return ok({
236 id: trackId,
237 title: finalTitle,
238 artist: finalArtist,
239 album: finalAlbum,
240 size: transcoded.size,
241 });
242 });
243});
244
245router.post('/:id/delete', requireGod, (req, res) => {
246 const site = res.locals.site;
247 if (!site) return res.status(404).send('Site required');
248
249 const track = db.prepare(`
250 SELECT t.id AS track_id, m.id AS media_id, m.storage_path
251 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
252 WHERE t.id = ? AND t.site_id = ?
253 `).get(req.params.id, site.id);
254
255 if (!track) return res.redirect('/admin/audio?error=Not+found');
256
257 db.prepare('DELETE FROM audio_tracks WHERE id = ?').run(track.track_id);
258 if (track.media_id) {
259 db.prepare('DELETE FROM media WHERE id = ?').run(track.media_id);
260 }
261 if (track.storage_path) {
262 try { fs.unlinkSync(track.storage_path); } catch {}
263 }
264 res.redirect('/admin/audio?success=Deleted');
265});
266
267// ─── Orphan cleanup: rows whose file is missing on disk ───────────
268//
269// Two-phase to prevent accidental data loss:
270// GET /admin/audio/cleanup → dry-run report (no changes, JSON list)
271// POST /admin/audio/cleanup → actually deletes the orphan rows
272//
273// "Orphan" = an audio_tracks row whose media_id either points nowhere or
274// points to a media row whose storage_path file doesn't exist on disk.
275// This is the recovery path when DB and disk drift apart (e.g. AUDIO_PATH
276// changed between uploads, disk was wiped, or migration left stragglers).
277function findOrphans(siteId) {
278 const rows = db.prepare(`
279 SELECT t.id AS track_id, t.title, t.artist, t.album,
280 m.id AS media_id, m.storage_path
281 FROM audio_tracks t
282 LEFT JOIN media m ON m.id = t.media_id
283 WHERE t.site_id = ?
284 `).all(siteId);
285 const orphans = [];
286 for (const r of rows) {
287 if (!r.storage_path) {
288 orphans.push({ ...r, reason: 'no media row' });
289 continue;
290 }
291 try { fs.statSync(r.storage_path); }
292 catch { orphans.push({ ...r, reason: 'file missing on disk' }); }
293 }
294 return { total: rows.length, orphans };
295}
296
297router.get('/cleanup', requireGod, (req, res) => {
298 const site = res.locals.site;
299 if (!site) return res.status(404).json({ error: 'Site required' });
300 const result = findOrphans(site.id);
301 res.json({
302 ok: true,
303 siteId: site.id,
304 totalTracks: result.total,
305 orphanCount: result.orphans.length,
306 orphans: result.orphans.map(o => ({
307 track_id: o.track_id,
308 title: o.title || '(zonder titel)',
309 artist: o.artist || '—',
310 reason: o.reason,
311 storage_path: o.storage_path || null,
312 })),
313 note: 'POST to this same URL to actually delete these rows.',
314 });
315});
316
317router.post('/cleanup', requireGod, (req, res) => {
318 const site = res.locals.site;
319 if (!site) return res.status(404).json({ error: 'Site required' });
320 const { orphans } = findOrphans(site.id);
321
322 // Wrap in a transaction so a partial failure doesn't leave half-deleted state
323 const deleteOne = db.transaction((o) => {
324 db.prepare('DELETE FROM audio_tracks WHERE id = ?').run(o.track_id);
325 if (o.media_id) db.prepare('DELETE FROM media WHERE id = ?').run(o.media_id);
326 });
327 for (const o of orphans) deleteOne(o);
328
329 res.json({ ok: true, deleted: orphans.length });
330});
331
332
333//
334// All write endpoints expect to be hit by the track-editor modal which
335// sends X-CSRF-Token and JSON. They return { ok: true, ... } on success
336// or { error: '...' } with a 4xx status on failure.
337
338/** GET /admin/audio/api/albums — distinct list of album names (for datalist) */
339router.get('/api/albums', requireGod, (req, res) => {
340 const site = res.locals.site;
341 if (!site) return res.status(404).json({ error: 'Site required' });
342 const rows = db.prepare(`
343 SELECT DISTINCT album FROM audio_tracks
344 WHERE site_id = ? AND album IS NOT NULL AND album != ''
345 ORDER BY album COLLATE NOCASE
346 `).all(site.id);
347 res.json({ ok: true, albums: rows.map(r => r.album) });
348});
349
350/** GET /admin/audio/api/:id — single track with all metadata */
351router.get('/api/:id', requireGod, (req, res) => {
352 const site = res.locals.site;
353 if (!site) return res.status(404).json({ error: 'Site required' });
354 const t = db.prepare(`
355 SELECT t.id, t.title, t.artist, t.album, t.duration, t.cover_url,
356 t.position, t.created_at, m.filename
357 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
358 WHERE t.id = ? AND t.site_id = ?
359 `).get(req.params.id, site.id);
360 if (!t) return res.status(404).json({ error: 'Track niet gevonden' });
361 // Stream URL so the modal can render an inline preview player.
362 const stream_url = t.filename ? audioUrl(t.filename) : null;
363 res.json({ ok: true, track: { ...t, stream_url } });
364});
365
366/**
367 * POST /admin/audio/api/:id — update track metadata.
368 * Accepts JSON body with any subset of: title, artist, album, duration, cover_url.
369 * `title` is required if present (can't be blanked). Empty strings on optional
370 * fields are stored as NULL so the audio embed renderer's `t.artist || ''`
371 * fallback keeps working.
372 */
373router.post('/api/:id', requireGod, express.json(), (req, res) => {
374 const site = res.locals.site;
375 if (!site) return res.status(404).json({ error: 'Site required' });
376
377 const exists = db.prepare(
378 'SELECT id FROM audio_tracks WHERE id = ? AND site_id = ?'
379 ).get(req.params.id, site.id);
380 if (!exists) return res.status(404).json({ error: 'Track niet gevonden' });
381
382 const fields = [];
383 const values = [];
384 const body = req.body || {};
385
386 if (Object.prototype.hasOwnProperty.call(body, 'title')) {
387 const v = String(body.title || '').trim();
388 if (!v) return res.status(400).json({ error: 'Titel is verplicht' });
389 fields.push('title = ?'); values.push(v);
390 }
391 if (Object.prototype.hasOwnProperty.call(body, 'artist')) {
392 fields.push('artist = ?'); values.push(String(body.artist || '').trim() || null);
393 }
394 if (Object.prototype.hasOwnProperty.call(body, 'album')) {
395 fields.push('album = ?'); values.push(String(body.album || '').trim() || null);
396 }
397 if (Object.prototype.hasOwnProperty.call(body, 'duration')) {
398 const d = parseInt(body.duration, 10);
399 fields.push('duration = ?');
400 values.push(Number.isFinite(d) && d > 0 ? d : null);
401 }
402 if (Object.prototype.hasOwnProperty.call(body, 'cover_url')) {
403 // Accept either a /media/... path or an absolute https URL.
404 // Anything else (javascript:, data:, etc) gets blanked for safety.
405 const raw = String(body.cover_url || '').trim();
406 let safe = null;
407 if (raw === '') {
408 safe = null;
409 } else if (raw.startsWith('/media/') || raw.startsWith('https://') || raw.startsWith('http://')) {
410 safe = raw;
411 }
412 fields.push('cover_url = ?'); values.push(safe);
413 }
414
415 if (fields.length === 0) {
416 return res.status(400).json({ error: 'Niks om te updaten' });
417 }
418
419 try {
420 db.prepare(`UPDATE audio_tracks SET ${fields.join(', ')} WHERE id = ? AND site_id = ?`)
421 .run(...values, req.params.id, site.id);
422 } catch (err) {
423 return res.status(500).json({ error: err.message });
424 }
425
426 // Return fresh row so the caller can update its UI without reloading
427 const fresh = db.prepare(`
428 SELECT id, title, artist, album, duration, cover_url
429 FROM audio_tracks WHERE id = ? AND site_id = ?
430 `).get(req.params.id, site.id);
431 res.json({ ok: true, track: fresh });
432});
433
434/**
435 * POST /admin/audio/api/:id/cover — upload a new cover image and set it on
436 * the track in one go. Returns { ok, url } so the modal can preview.
437 *
438 * Reuses the same multer config as the upload form (5MB limit, jpg/png/webp/gif).
439 * If the track already had a cover stored under /media/audio-covers/, the old
440 * file is deleted to avoid orphaned bytes piling up.
441 */
442router.post('/api/:id/cover', requireGod, (req, res) => {
443 const site = res.locals.site;
444 if (!site) return res.status(404).json({ error: 'Site required' });
445
446 const exists = db.prepare(
447 'SELECT id, cover_url FROM audio_tracks WHERE id = ? AND site_id = ?'
448 ).get(req.params.id, site.id);
449 if (!exists) return res.status(404).json({ error: 'Track niet gevonden' });
450
451 upload.single('cover')(req, res, (err) => {
452 if (err) return res.status(400).json({ error: err.message });
453 const file = req.file;
454 if (!file) return res.status(400).json({ error: 'Geen bestand' });
455 if (file.size > MAX_COVER_BYTES) {
456 try { fs.unlinkSync(file.path); } catch {}
457 return res.status(413).json({ error: 'Te groot (max 5 MB)' });
458 }
459
460 const newUrl = `/media/audio-covers/${file.filename}`;
461 try {
462 db.prepare('UPDATE audio_tracks SET cover_url = ? WHERE id = ? AND site_id = ?')
463 .run(newUrl, req.params.id, site.id);
464 } catch (dbErr) {
465 try { fs.unlinkSync(file.path); } catch {}
466 return res.status(500).json({ error: dbErr.message });
467 }
468
469 // Clean up the previous cover if it lived in our covers dir
470 if (exists.cover_url && exists.cover_url.startsWith('/media/audio-covers/')) {
471 const oldName = exists.cover_url.replace(/^\/media\/audio-covers\//, '');
472 const oldPath = path.join(COVER_DIR, oldName);
473 try { fs.unlinkSync(oldPath); } catch {}
474 }
475
476 // Return both keys so any caller using j.url OR j.cover_url works.
477 // Frontend (track-editor.ejs) reads j.cover_url — keep this in sync.
478 res.json({ ok: true, url: newUrl, cover_url: newUrl });
479 });
480});
481
482export default router;
Note: See TracBrowser for help on using the repository browser.