source: Klonkt/src/routes/download.js@ eb5f978

main
Last change on this file since eb5f978 was 834bcc3, checked in by Robin Genis <roboburr@…>, 3 months ago

i18n: translate Dutch code comments to English across src/

Comments in routes/services/views/config/middleware/assets translated to
English for the public repo. A few dev-facing throw/console message strings
were Englished too. No user-facing UI strings or i18n dictionary values changed
(src/services/i18n.js untouched). Logic unchanged.

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

  • Property mode set to 100644
File size: 6.2 KB
RevLine 
[91094a4]1/**
[834bcc3]2 * Download-for-email (premium feature #2).
[91094a4]3 *
[834bcc3]4 * GET /downloads -> list of downloadable tracks (premium; 404 otherwise)
5 * GET /download/:id -> email capture page for a single track
6 * POST /download/:id -> save email (-> mailing list) + unlock download
7 * GET /download/:id/bestand -> serves the file (session-gated after capture)
[91094a4]8 *
[834bcc3]9 * The fan leaves their email and receives the file; the address is added to the
10 * subscribers list (source 'download', single opt-in — no confirm step before the
[91094a4]11 * download). Hub: via /user/:slug/... (resolveSite + siteUrlBase).
12 */
13
14import express from 'express';
15import path from 'path';
16import fs from 'fs';
17import { fileURLToPath } from 'url';
18import db from '../config/database.js';
19import { renderPage } from '../middleware/render.js';
20import { premiumUnlocked } from '../services/PatreonService.js';
21import { addSubscriber } from '../services/SubscriberService.js';
[d8c6a83]22import { postNeighbors } from './posts.js';
[91094a4]23
24const router = express.Router();
[d8c6a83]25
[834bcc3]26// If a real (pinned) post with slug 'downloads' exists, the downloads list is
27// effectively attached to that post. We then also show the Newer/Older post nav
28// so the visitor can browse just like on a regular post.
[d8c6a83]29function downloadsPostNav(req, res) {
30 const site = res.locals.site;
31 if (!site) return {};
32 const post = db.prepare(
33 "SELECT id, slug, pinned FROM posts WHERE site_id = ? AND slug = 'downloads' AND status = 'published'"
34 ).get(site.id);
35 if (!post) return {};
36 try { return postNeighbors(site, post, res.locals.tenancy === 'hub'); } catch (e) { return {}; }
37}
[91094a4]38const __dirname = path.dirname(fileURLToPath(import.meta.url));
39const AUDIO_DIR = path.resolve(process.env.AUDIO_PATH || path.join(__dirname, '..', '..', 'storage', 'audio'));
40
41const MIME = { '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.flac': 'audio/flac', '.m4a': 'audio/mp4', '.ogg': 'audio/ogg' };
[834bcc3]42const GRACE_MS = 15 * 60 * 1000; // download window after capture
[91094a4]43
44function dlTrack(siteId, id) {
45 return db.prepare(
[c9d48fc]46 `SELECT t.id, t.title, t.artist, t.cover_url, m.storage_path, m.filename
[91094a4]47 FROM audio_tracks t JOIN media m ON m.id = t.media_id
48 WHERE t.id = ? AND t.site_id = ? AND t.downloadable = 1`
49 ).get(id, siteId);
50}
51function safeName(title, storagePath) {
52 const ext = path.extname(storagePath || '').toLowerCase() || '.mp3';
53 const base = String(title || 'track').replace(/[^a-zA-Z0-9 _.-]/g, '').trim().slice(0, 80) || 'track';
54 return base + ext;
55}
56
[834bcc3]57// List of downloadable tracks.
[91094a4]58router.get('/downloads', (req, res, next) => {
59 if (!premiumUnlocked()) return next();
60 const site = res.locals.site;
61 if (!site) return next();
62 const tracks = db.prepare(
63 `SELECT id, title, artist, cover_url FROM audio_tracks
64 WHERE site_id = ? AND downloadable = 1 ORDER BY position ASC, created_at ASC`
65 ).all(site.id);
[d8c6a83]66 const nav = downloadsPostNav(req, res);
[91094a4]67 renderPage(req, res, 'pages/downloads', {
68 pageTitle: 'Downloads — ' + (site.title || ''),
[834bcc3]69 // on-special = compact profile header (like on a post); on-downloads = grey pill
70 // + feature-route behaviour. Together → downloads looks just like a post.
[cc22112]71 bodyClass: 'on-downloads on-special',
[91094a4]72 dlTracks: tracks,
[d8c6a83]73 newerPost: nav.newerPost || null,
74 olderPost: nav.olderPost || null,
[91094a4]75 });
76});
77
[834bcc3]78// Capture page for a single track.
[91094a4]79router.get('/download/:id', (req, res, next) => {
80 if (!premiumUnlocked()) return next();
81 const site = res.locals.site;
82 if (!site) return next();
83 const track = dlTrack(site.id, req.params.id);
84 if (!track) return next();
85 const fan = req.session && req.session.user;
86 renderPage(req, res, 'pages/download', {
87 pageTitle: track.title + ' — download',
88 bodyClass: 'on-download',
89 dlState: 'form',
90 dlTrack: track,
91 dlPrefill: (fan && fan.email && fan.email.includes('@')) ? fan.email : '',
92 });
93});
94
[834bcc3]95// Save email + unlock download.
[91094a4]96router.post('/download/:id', (req, res, next) => {
97 if (!premiumUnlocked()) return next();
98 const site = res.locals.site;
99 if (!site) return next();
100 const track = dlTrack(site.id, req.params.id);
101 if (!track) return next();
102 const email = (req.body.email || '').trim();
103 const r = addSubscriber(site.id, email, 'download', { doubleOptin: false });
104 if (!r.ok) {
105 return renderPage(req, res, 'pages/download', {
106 pageTitle: track.title + ' — download', bodyClass: 'on-download',
107 dlState: 'form', dlTrack: track, dlPrefill: email,
108 dlError: r.error === 'invalid_email' ? 'Controleer je e-mailadres.' : 'Er ging iets mis.',
109 });
110 }
[834bcc3]111 // Unlock download in the session (short window).
[91094a4]112 if (!req.session.dl) req.session.dl = {};
113 req.session.dl[track.id] = Date.now();
114 renderPage(req, res, 'pages/download', {
115 pageTitle: track.title + ' — download', bodyClass: 'on-download',
116 dlState: 'ready', dlTrack: track,
117 });
118});
119
[834bcc3]120// Serve the file — only if an email was just submitted (session-gated).
[91094a4]121router.get('/download/:id/bestand', (req, res, next) => {
122 if (!premiumUnlocked()) return next();
123 const site = res.locals.site;
124 if (!site) return next();
125 const track = dlTrack(site.id, req.params.id);
126 if (!track) return next();
127 const ts = req.session && req.session.dl && req.session.dl[track.id];
128 if (!ts || (Date.now() - ts) > GRACE_MS) {
129 return res.status(403).send('Laat eerst je e-mailadres achter om te downloaden.');
130 }
[834bcc3]131 // The playable/downloadable file = the BARE filename (storage_path is an
132 // absolute path → fails the slash-guard). Same approach as /audio/stream.
[c9d48fc]133 const sp = track.filename;
[91094a4]134 if (!sp || sp.includes('/') || sp.includes('\\') || sp.includes('..')) return res.status(400).send('Bad path');
135 const filePath = path.join(AUDIO_DIR, sp);
136 if (!filePath.startsWith(AUDIO_DIR + path.sep)) return res.status(400).send('Bad path');
137 let stat;
138 try { stat = fs.statSync(filePath); } catch { return res.status(404).send('Bestand niet gevonden'); }
139 if (!stat.isFile()) return res.status(404).send('Bestand niet gevonden');
140 const ext = path.extname(sp).toLowerCase();
141 res.setHeader('Content-Type', MIME[ext] || 'application/octet-stream');
142 res.setHeader('Content-Length', stat.size);
143 res.setHeader('Content-Disposition', 'attachment; filename="' + safeName(track.title, sp) + '"');
144 fs.createReadStream(filePath).pipe(res);
145});
146
147export default router;
Note: See TracBrowser for help on using the repository browser.