source: Klonkt/src/routes/admin-audio.js@ 7bc636b

main
Last change on this file since 7bc636b was 7bc636b, checked in by Robin <robin@…>, 4 months ago

Initial commit — PrutFolio v1 source (pulled from Hetzner /srv/prutfolio)

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