source: Klonkt/src/routes/admin-audio.js@ 8f6225c

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

feat(images): new uploads automatically converted to WebP

Shared ImageWebpService.toWebp() converts uploaded images via cwebp (q82)
and removes the original; cwebp absent/error → original preserved (graceful).
Wired up in all upload routes: post images/cover, avatar, site photo, hub
hero, audio cover. GIF stays GIF, already-webp skipped.

Co-Authored-By: Claude <noreply@…>

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