source: Klonkt/src/routes/posts.js@ bbbfa3c

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

feat: lite mode (KLONKT_AUDIO=off) — audio disabled, single codebase

Boot flag that skips the entire audio feature: no audio/playlist/download/
embed routes (no ffmpeg calls), no tracks loaded, own-audio shortcodes
(track/album/playlist) stripped, audio buttons in admin/profile
hidden. Hub and Circles keep working; external embeds (YouTube/SoundCloud/
Spotify) keep working too. Default = on (full version unchanged).
This lets Klonkt run as a lightweight blog/photo/EPK site on an environment
without ffmpeg.

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

  • Property mode set to 100644
File size: 29.8 KB
Line 
1import express from 'express';
2import { v4 as uuid } from 'uuid';
3import path from 'path';
4import fs from 'fs';
5import { fileURLToPath } from 'url';
6import multer from 'multer';
7import ejs from 'ejs';
8import db from '../config/database.js';
9import { requireAuth } from '../middleware/auth.js';
10import { renderPage } from '../middleware/render.js';
11import { recordPageview, recordPostView } from '../services/StatsService.js';
12import { notify } from '../services/NotificationService.js';
13import PermissionsService from '../services/PermissionsService.js';
14import MarkdownService from '../services/MarkdownService.js';
15import HtmlSanitizerService from '../services/HtmlSanitizerService.js';
16import AudioEmbedService from '../services/AudioEmbedService.js';
17import PlaylistService from '../services/PlaylistService.js';
18import { audioEnabled } from '../config/features.js';
19import { audioUrl } from '../services/AudioStreamService.js';
20import { toWebp } from '../services/ImageWebpService.js';
21
22const __dirname = path.dirname(fileURLToPath(import.meta.url));
23const POST_IMAGES_DIR = path.resolve(
24 process.env.POST_IMAGES_PATH ||
25 path.join(__dirname, '..', '..', 'storage', 'media', 'post-images')
26);
27fs.mkdirSync(POST_IMAGES_DIR, { recursive: true });
28
29const ALLOWED_IMAGE_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
30const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
31
32const imageStorage = multer.diskStorage({
33 destination: (req, file, cb) => cb(null, POST_IMAGES_DIR),
34 filename: (req, file, cb) => {
35 const ext = path.extname(file.originalname).toLowerCase();
36 cb(null, `${uuid()}${ext}`);
37 },
38});
39const imageUpload = multer({
40 storage: imageStorage,
41 limits: { fileSize: MAX_IMAGE_BYTES },
42 fileFilter: (req, file, cb) => {
43 const ext = path.extname(file.originalname).toLowerCase();
44 if (!ALLOWED_IMAGE_EXT.has(ext)) {
45 return cb(new Error('Image must be jpg/png/webp/gif'));
46 }
47 cb(null, true);
48 },
49});
50
51// Maakt een unieke slug binnen de site: 'titel', 'titel-2', 'titel-3', …
52// Zo wordt een tweede post met dezelfde titel NIET geweigerd ("bestaat al"),
53// maar krijgt 'ie automatisch een vrij achtervoegsel. exceptId = de post die
54// we bijwerken (mag z'n eigen slug houden).
55function uniqueSlug(siteId, base, exceptId = null) {
56 let candidate = base;
57 let n = 2;
58 for (;;) {
59 const row = exceptId
60 ? db.prepare('SELECT id FROM posts WHERE site_id = ? AND slug = ? AND id != ?').get(siteId, candidate, exceptId)
61 : db.prepare('SELECT id FROM posts WHERE site_id = ? AND slug = ?').get(siteId, candidate);
62 if (!row) return candidate;
63 candidate = `${base}-${n++}`;
64 }
65}
66
67const router = express.Router();
68
69// ==================== UPLOAD IMAGE (cover or content) ====================
70// Returns JSON {url} so the editor can stick it into the cover field or
71// insert a markdown ![](url) into content.
72router.post('/posts/upload-image', requireAuth, (req, res) => {
73 imageUpload.single('image')(req, res, (err) => {
74 if (err) return res.status(400).json({ error: err.message });
75 if (!req.file) return res.status(400).json({ error: 'No file' });
76 const url = '/media/post-images/' + toWebp(req.file);
77 res.json({ url, size: req.file.size, mime: req.file.mimetype });
78 });
79});
80
81const RESERVED_SLUGS = new Set([
82 'auth', 'admin', 'login', 'register', 'logout',
83 'archive', 'search', 'account', 'sites', 'comments',
84 'posts', 'media', 'audio', 'forum',
85 'tag', 'type', 'user', 'users', 'artiesten', 'leden', 'favorieten', 'feed.xml', 'atom.xml', 'sitemap.xml',
86 'manifest.webmanifest', 'sw.js', 'favicon.ico', 'favicon.svg', 'assets',
87]);
88
89/**
90 * Parse the form's `pinned` field into a non-negative integer rank.
91 * Empty / undefined / NaN / negative → 0 (= not pinned).
92 * Otherwise: integer rank (1 = top of pinned stack, 2 = below, ...).
93 *
94 * Multiple posts CAN share the same rank — UI shows them tiebroken by
95 * published_at DESC. Saying #2 twice doesn't error, it just duplicates.
96 * (We don't enforce uniqueness at this layer because race conditions and
97 * "swap two ranks" workflows are easier without a UNIQUE constraint.)
98 */
99function parsePinnedRank(raw) {
100 const n = parseInt(raw, 10);
101 if (!Number.isFinite(n) || n < 0) return 0;
102 return n;
103}
104
105// ==================== HOME (Posts list) ====================
106router.get('/', (req, res) => {
107 const site = res.locals.site;
108
109 if (!site) {
110 return renderPage(req, res, 'pages/welcome', {
111 pageTitle: 'Welcome',
112 bodyClass: 'on-special',
113 });
114 }
115
116 // Pinned first — ordered by their rank (1 = top, 2 = below, etc).
117 // pinned column is now an integer rank: 0 = not pinned, 1+ = pinned at
118 // that position. Older boolean usage where pinned was always 1 still
119 // works because integer ranks 1, 2, 3 sort the same as a flat 1.
120 const pinnedPosts = db.prepare(`
121 SELECT p.*, u.username as author_username
122 FROM posts p JOIN users u ON p.author_id = u.id
123 WHERE p.site_id = ? AND p.status = 'published' AND p.pinned > 0
124 ORDER BY p.pinned ASC, p.published_at DESC
125 `).all(site.id);
126
127 // Regular posts: anything with pinned = 0
128 const posts = db.prepare(`
129 SELECT p.*, u.username as author_username
130 FROM posts p JOIN users u ON p.author_id = u.id
131 WHERE p.site_id = ? AND p.status = 'published' AND p.pinned = 0
132 ORDER BY p.published_at DESC
133 LIMIT 30
134 `).all(site.id);
135
136 recordPageview(site.id, req);
137
138 renderPage(req, res, 'pages/home', {
139 pinnedPosts,
140 posts,
141 pageTitle: site.title,
142 socialDescr: site.description || site.tagline || '',
143 bodyClass: 'on-home',
144 });
145});
146
147// ==================== NEW POST FORM ====================
148router.get('/posts/new', requireAuth, (req, res) => {
149 const site = res.locals.site;
150 if (!site) return res.status(404).send('Site required');
151 if (!PermissionsService.canCreatePost(req.session.user, site)) {
152 return res.status(403).send('No permission');
153 }
154
155 renderPage(req, res, 'pages/post-edit', {
156 post: {
157 id: uuid(),
158 title: '', slug: '', content: '', excerpt: '',
159 status: 'draft', pinned: 0, tags: [],
160 cover_image_url: '',
161 },
162 isNew: true,
163 pageTitle: 'New post',
164 bodyClass: 'on-special',
165 });
166});
167
168// ==================== CREATE POST ====================
169router.post('/posts/create', requireAuth, (req, res) => {
170 const site = res.locals.site;
171 if (!site || !PermissionsService.canCreatePost(req.session.user, site)) {
172 return res.status(403).send('No permission');
173 }
174
175 const { title, slug, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
176 const fanOnly = req.body.fan_only ? 1 : 0;
177
178 // Content arrives as user-authored HTML from the WYSIWYG editor — sanitize
179 // before storage. Shortcode text tokens like [[track:UUID]] live in text
180 // nodes and pass through untouched.
181 const cleanContent = HtmlSanitizerService.sanitize(content || '');
182
183 // Generate slug from title if empty
184 let finalSlug = (slug || title || '')
185 .toLowerCase()
186 .replace(/[^a-z0-9]+/g, '-')
187 .replace(/^-|-$/g, '');
188
189 if (!finalSlug) return res.status(400).send('Title or slug required');
190 if (RESERVED_SLUGS.has(finalSlug)) finalSlug = `${finalSlug}-post`;
191
192 // Dubbele titel/slug? Automatisch uniek maken (titel-2, titel-3, …) i.p.v. weigeren.
193 finalSlug = uniqueSlug(site.id, finalSlug);
194
195 const validTypes = new Set(['post', 'foto', 'video', 'audio']);
196 const finalType = validTypes.has(type) ? type : 'post';
197 const postId = uuid();
198 const now = new Date().toISOString();
199 let finalStatus = status || 'draft';
200 let publishedAt = finalStatus === 'published' ? now : null;
201 // Release-planning: gepubliceerd + een toekomstige publish_at -> 'scheduled'
202 // (de Scheduler zet 'm live op het moment zelf). Verleden/leeg -> meteen live.
203 let publishAt = null;
204 const pa = Date.parse(req.body.publish_at || '');
205 if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
206 finalStatus = 'scheduled';
207 publishAt = new Date(pa).toISOString();
208 publishedAt = null;
209 }
210
211 db.prepare(`
212 INSERT INTO posts (
213 id, site_id, slug, author_id, title, content, excerpt,
214 status, cover_image_url, pinned, tags, type, noindex, fan_only, publish_at,
215 created_at, updated_at, published_at
216 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
217 `).run(
218 postId, site.id, finalSlug, req.session.user.id,
219 title || finalSlug, cleanContent, excerpt || '',
220 finalStatus, cover_image_url || null, parsePinnedRank(pinned),
221 JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
222 finalType, noindex ? 1 : 0, fanOnly, publishAt,
223 now, now, publishedAt
224 );
225
226 if (finalStatus === 'published') {
227 try {
228 db.prepare(
229 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
230 ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, postId);
231 } catch (e) { /* FTS index issues are non-fatal */ }
232 }
233
234 // HTMX request -> return redirect header
235 if (req.headers['hx-request']) {
236 res.setHeader('HX-Redirect', `${res.locals.siteUrlBase || ''}/${finalSlug}`);
237 return res.send('OK');
238 }
239
240 res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
241});
242
243// ==================== EDIT POST FORM ====================
244router.get('/posts/:slug/edit', requireAuth, (req, res) => {
245 const site = res.locals.site;
246 if (!site) return res.status(404).send('Site required');
247
248 const post = db.prepare(
249 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
250 ).get(site.id, req.params.slug);
251
252 if (!post) return res.status(404).send('Post not found');
253 if (!PermissionsService.canEditPost(req.session.user, post, site)) {
254 return res.status(403).send('No permission');
255 }
256
257 if (post.tags) {
258 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
259 } else {
260 post.tags = [];
261 }
262
263 renderPage(req, res, 'pages/post-edit', {
264 post,
265 isNew: false,
266 pageTitle: 'Edit: ' + (post.title || 'Untitled'),
267 bodyClass: 'on-special',
268 });
269});
270
271// ==================== SAVE POST ====================
272router.post('/posts/:slug/save', requireAuth, (req, res) => {
273 const site = res.locals.site;
274 if (!site) return res.status(404).send('Site required');
275
276 const post = db.prepare(
277 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
278 ).get(site.id, req.params.slug);
279
280 if (!post) return res.status(404).send('Post not found');
281 if (!PermissionsService.canEditPost(req.session.user, post, site)) {
282 return res.status(403).send('No permission');
283 }
284
285 const { title, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
286 const fanOnly = req.body.fan_only ? 1 : 0;
287 const newSlug = req.body.slug;
288 const action = req.body.action || 'save';
289 const validTypes = new Set(['post', 'foto', 'video', 'audio']);
290 const finalType = validTypes.has(type) ? type : (post.type || 'post');
291
292 // Sanitize before storage — same pipeline as create.
293 const cleanContent = HtmlSanitizerService.sanitize(content || '');
294
295 let finalSlug = post.slug;
296 if (newSlug && newSlug !== post.slug) {
297 const cleaned = newSlug.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
298 const safe = RESERVED_SLUGS.has(cleaned) ? `${cleaned}-post` : cleaned;
299 // Dubbele slug? Automatisch uniek maken i.p.v. weigeren (eigen post mag z'n slug houden).
300 finalSlug = uniqueSlug(site.id, safe, post.id);
301 }
302
303 const now = new Date().toISOString();
304 let finalStatus = status || post.status;
305 let publishedAt = post.published_at;
306
307 if (action === 'publish') {
308 finalStatus = 'published';
309 if (!publishedAt) publishedAt = now;
310 }
311
312 // Release-planning: gepubliceerd + toekomstige publish_at -> 'scheduled'.
313 let publishAt = null;
314 const pa = Date.parse(req.body.publish_at || '');
315 if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
316 finalStatus = 'scheduled';
317 publishAt = new Date(pa).toISOString();
318 publishedAt = null;
319 }
320
321 db.prepare(`
322 UPDATE posts SET
323 title = ?, content = ?, excerpt = ?, status = ?,
324 cover_image_url = ?, pinned = ?, tags = ?,
325 type = ?, noindex = ?, fan_only = ?, publish_at = ?,
326 slug = ?, published_at = ?, updated_at = ?
327 WHERE id = ?
328 `).run(
329 title, cleanContent, excerpt, finalStatus,
330 cover_image_url || null, parsePinnedRank(pinned),
331 JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
332 finalType, noindex ? 1 : 0, fanOnly, publishAt,
333 finalSlug, publishedAt, now, post.id
334 );
335
336 // Update FTS
337 try {
338 db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id);
339 if (finalStatus === 'published') {
340 db.prepare(
341 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
342 ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, post.id);
343 }
344 } catch (e) { /* FTS issues non-fatal */ }
345
346 res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
347});
348
349// ==================== DELETE POST ====================
350router.post('/posts/:slug/delete', requireAuth, (req, res) => {
351 const site = res.locals.site;
352 if (!site) return res.status(404).send('Site required');
353
354 const post = db.prepare(
355 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
356 ).get(site.id, req.params.slug);
357
358 if (!post) return res.status(404).send('Not found');
359 if (!PermissionsService.canDeletePost(req.session.user, post, site)) {
360 return res.status(403).send('No permission');
361 }
362
363 // Cascade: comments + FTS row, THEN the post itself.
364 // FK constraints are ON (config/database.js), so a bare DELETE on posts
365 // fails when comments still reference it.
366 const cascade = db.transaction(() => {
367 db.prepare('DELETE FROM comments WHERE post_id = ?').run(post.id);
368 try { db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id); } catch {}
369 db.prepare('DELETE FROM posts WHERE id = ?').run(post.id);
370 });
371 cascade();
372
373 if (req.headers['hx-request']) {
374 res.setHeader('HX-Redirect', res.locals.siteUrlBase || '/');
375 return res.send('OK');
376 }
377 res.redirect(res.locals.siteUrlBase || '/');
378});
379
380// ==================== ARCHIVE ====================
381router.get('/archive', (req, res) => {
382 const site = res.locals.site;
383 if (!site) return res.status(404).send('No site');
384
385 const posts = db.prepare(`
386 SELECT p.*, u.username as author_username
387 FROM posts p JOIN users u ON p.author_id = u.id
388 WHERE p.site_id = ? AND p.status = 'published'
389 ORDER BY p.published_at DESC
390 `).all(site.id);
391
392 // Group by year/month
393 const grouped = {};
394 for (const post of posts) {
395 if (!post.published_at) continue;
396 const d = new Date(post.published_at);
397 const year = d.getFullYear();
398 const month = d.getMonth();
399 const monthName = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'][month];
400
401 if (!grouped[year]) grouped[year] = {};
402 if (!grouped[year][monthName]) grouped[year][monthName] = [];
403 grouped[year][monthName].push(post);
404 }
405
406 renderPage(req, res, 'pages/archive', {
407 grouped,
408 totalPosts: posts.length,
409 pageTitle: 'Archive - ' + site.title,
410 bodyClass: 'on-archive',
411 });
412});
413
414// Pad naar de like-knop-partial (voor de htmx-toggle re-render).
415const LIKE_PARTIAL = path.join(__dirname, '..', 'views', 'partials', 'like-button.ejs');
416
417// ==================== LIKE / FAVORIET ====================
418// Een ingelogde gebruiker (geen kijker — de globale guard blokkeert non-GET voor
419// kijkers) togglet een like op een gepubliceerde post. Geeft de her-gerenderde
420// knop terug (htmx outerHTML-swap).
421router.post('/posts/:id/like', requireAuth, (req, res) => {
422 const userId = req.session.user.id;
423 const post = db.prepare('SELECT id, status, slug, title, author_id FROM posts WHERE id = ?').get(req.params.id);
424 if (!post) return res.status(404).send('Post niet gevonden');
425 if (post.status !== 'published') return res.status(403).send('Niet beschikbaar');
426
427 const exists = db.prepare('SELECT 1 FROM post_likes WHERE post_id = ? AND user_id = ?').get(post.id, userId);
428 if (exists) {
429 db.prepare('DELETE FROM post_likes WHERE post_id = ? AND user_id = ?').run(post.id, userId);
430 } else {
431 db.prepare('INSERT OR IGNORE INTO post_likes (post_id, user_id) VALUES (?, ?)').run(post.id, userId);
432 // Melding voor de post-auteur (notify slaat jezelf-liken over).
433 notify({
434 userId: post.author_id, actorId: userId, actorName: req.session.user.username, type: 'like',
435 postSlug: post.slug, postTitle: post.title, url: (res.locals.siteUrlBase || '') + '/' + post.slug,
436 });
437 }
438 const likeCount = db.prepare('SELECT COUNT(*) AS c FROM post_likes WHERE post_id = ?').get(post.id).c;
439
440 const html = ejs.render(fs.readFileSync(LIKE_PARTIAL, 'utf8'), {
441 post: { id: post.id }, likedByMe: !exists, likeCount, loggedIn: true, loginNext: '/',
442 });
443 res.send(html);
444});
445
446// Favorieten = de posts die de ingelogde gebruiker likete. Solo: binnen de
447// huidige site. Hub: over alle sites (met juiste /user/<slug>-links).
448router.get('/favorieten', requireAuth, (req, res) => {
449 const userId = req.session.user.id;
450 const isHub = res.locals.tenancy === 'hub';
451 const site = res.locals.site;
452 const rows = isHub
453 ? db.prepare(`
454 SELECT p.id, p.slug, p.title, p.excerpt, p.cover_image_url, p.published_at,
455 p.tags, p.type, p.pinned, p.status, s.slug AS site_slug
456 FROM post_likes pl JOIN posts p ON p.id = pl.post_id JOIN sites s ON s.id = p.site_id
457 WHERE pl.user_id = ? AND p.status = 'published'
458 ORDER BY pl.created_at DESC
459 `).all(userId)
460 : db.prepare(`
461 SELECT p.id, p.slug, p.title, p.excerpt, p.cover_image_url, p.published_at,
462 p.tags, p.type, p.pinned, p.status
463 FROM post_likes pl JOIN posts p ON p.id = pl.post_id
464 WHERE pl.user_id = ? AND p.site_id = ? AND p.status = 'published'
465 ORDER BY pl.created_at DESC
466 `).all(userId, site ? site.id : '');
467 const posts = rows.map((p) => ({ ...p, _urlBase: (isHub && p.site_slug) ? `/user/${p.site_slug}` : '' }));
468 renderPage(req, res, 'pages/favorites', { posts, pageTitle: 'Favorieten', bodyClass: 'on-favorites' });
469});
470
471// Newer/Older-buren over ALLE posts in feed-volgorde. Gedeeld door de volledige
472// post-render én de fan-gate (premium fan_only), zodat de navigatie overal gelijk
473// is. Solo: binnen de site (pinned eerst, dan datum). Hub: globaal op datum.
474function postNeighbors(site, post, isHub) {
475 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
476 const ordered = isHub
477 ? db.prepare(`
478 SELECT p.id, p.slug, p.title, p.pinned, s.slug AS site_slug
479 FROM posts p JOIN sites s ON s.id = p.site_id
480 WHERE p.status = 'published'
481 ORDER BY p.published_at DESC
482 `).all()
483 : db.prepare(`
484 SELECT id, slug, title, pinned FROM posts
485 WHERE site_id = ? AND status = 'published'
486 ORDER BY (pinned = 0) ASC, pinned ASC, published_at DESC
487 `).all(site.id);
488 const idx = ordered.findIndex((p) => p.id === post.id);
489 const newerPost = idx > 0 ? ordered[idx - 1] : null;
490 const olderPost = (idx >= 0 && idx < ordered.length - 1) ? ordered[idx + 1] : null;
491 if (newerPost) newerPost._urlBase = urlBaseFor(newerPost);
492 if (olderPost) olderPost._urlBase = urlBaseFor(olderPost);
493 return { newerPost, olderPost };
494}
495
496// ==================== VIEW POST (last route — catches /:slug) ====================
497router.get('/:slug', (req, res, next) => {
498 if (RESERVED_SLUGS.has(req.params.slug)) return next();
499
500 const site = res.locals.site;
501 if (!site) return next(); // -> nette 404 catch-all
502
503 const post = db.prepare(`
504 SELECT p.*, u.username as author_username, u.avatar_url as author_avatar
505 FROM posts p JOIN users u ON p.author_id = u.id
506 WHERE p.site_id = ? AND p.slug = ?
507 `).get(site.id, req.params.slug);
508
509 if (!post) return next(); // onbekende slug -> nette 404 catch-all
510
511 // Permission to view: published OR (logged in + can edit)
512 if (post.status !== 'published') {
513 const canEdit = req.session?.user && PermissionsService.canEditPost(req.session.user, post, site);
514 if (!canEdit) return res.status(403).send('Not published');
515 }
516
517 // Fan-only preview (premium #3): volledige inhoud alleen voor ingelogde fans.
518 // Anonieme bezoekers krijgen een nette login-gate i.p.v. de inhoud (de titel/
519 // teaser mag elders wel als lokkertje verschijnen).
520 if (post.fan_only && !(req.session && req.session.user)) {
521 // Zelfde Newer/Older-navigatie als op een gewone post, zodat de bezoeker op
522 // de fan-gate niet vastloopt maar verder kan bladeren.
523 const { newerPost, olderPost } = postNeighbors(site, post, res.locals.tenancy === 'hub');
524 return renderPage(req, res, 'pages/fan-gate', {
525 pageTitle: post.title || 'Alleen voor fans',
526 bodyClass: 'on-special',
527 fgTitle: post.title || '',
528 fgNext: (res.locals.siteUrlBase || '') + '/' + post.slug,
529 newerPost,
530 olderPost,
531 });
532 }
533
534 // Statistieken: tel de weergave (skipt beheerders + niet-gepubliceerd-eigen-preview).
535 if (post.status === 'published') recordPostView(post, req);
536
537 // Render content. Content is now user-authored HTML (already sanitized on
538 // save). The pipeline still adds autoembed iframes and shortcode embeds:
539 // stored HTML → autoembed → [[track]]/[[album]]/[[playlist]] → response
540 let html = post.content || '';
541 if (audioEnabled()) {
542 if (site.enable_audio_player !== 0) {
543 html = AudioEmbedService.autoembed(html);
544 html = AudioEmbedService.embedMediaShortcodes(html);
545 html = AudioEmbedService.embedExternalLinkShortcodes(html);
546
547 // Fetch any tracks referenced by [[track:id]] in this post.
548 // Cheap to do unconditionally — only matches if the post actually has shortcodes.
549 const trackIds = [...html.matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)].map(m => m[1]);
550 if (trackIds.length) {
551 const placeholders = trackIds.map(() => '?').join(',');
552 const rows = db.prepare(`
553 SELECT t.id, t.title, t.artist, t.cover_url, t.credit, t.license,
554 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
555 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
556 WHERE t.site_id = ? AND t.id IN (${placeholders})
557 `).all(site.id, ...trackIds);
558 const byId = new Map(rows.map(r => [r.id, r]));
559 html = AudioEmbedService.embedTrackShortcodes(html, (id) => {
560 const r = byId.get(id);
561 if (!r) return null;
562 return {
563 id: r.id,
564 title: r.title,
565 artist: r.artist,
566 cover: r.cover_url,
567 credit: r.credit || '',
568 license: r.license || '',
569 link_spotify: r.link_spotify || '',
570 link_youtube: r.link_youtube || '',
571 link_soundcloud: r.link_soundcloud || '',
572 url: r.filename ? audioUrl(r.filename) : '', // '' = link-only track
573 };
574 });
575 }
576
577 // Album shortcodes: [[album:Some Album Name]]
578 const albumNames = [...html.matchAll(/\[\[album:([^\]]+)\]\]/g)].map(m => m[1].trim());
579 if (albumNames.length) {
580 const placeholders = albumNames.map(() => '?').join(',');
581 const albumRows = db.prepare(`
582 SELECT t.id, t.title, t.artist, t.album, t.cover_url, t.position,
583 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
584 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
585 WHERE t.site_id = ? AND t.album IN (${placeholders})
586 ORDER BY t.position ASC, t.created_at ASC
587 `).all(site.id, ...albumNames);
588 const byAlbum = new Map();
589 for (const r of albumRows) {
590 // Link-only tracks (geen bestand) blijven in het album-overzicht (url '').
591 if (!byAlbum.has(r.album)) byAlbum.set(r.album, []);
592 byAlbum.get(r.album).push({
593 id: r.id,
594 url: r.filename ? audioUrl(r.filename) : '',
595 title: r.title || 'Untitled',
596 artist: r.artist || '',
597 cover: r.cover_url || '',
598 link_spotify: r.link_spotify || '',
599 link_youtube: r.link_youtube || '',
600 link_soundcloud: r.link_soundcloud || '',
601 });
602 }
603 html = AudioEmbedService.embedAlbumShortcodes(html, (name) => {
604 const tracks = byAlbum.get(name);
605 if (!tracks || !tracks.length) return null;
606 return {
607 title: name,
608 artist: tracks[0].artist || '',
609 cover: tracks[0].cover || '',
610 tracks,
611 };
612 });
613 }
614
615 // Playlist shortcodes: [[playlist:some-slug-id]] — first-class entity.
616 // Editing the playlist propagates to every post that embeds it.
617 const playlistIds = [...html.matchAll(/\[\[playlist:([a-z0-9][a-z0-9-]*)\]\]/gi)]
618 .map(m => m[1].toLowerCase());
619 if (playlistIds.length) {
620 const isAdmin = req.session?.user?.role === 'god';
621 html = AudioEmbedService.embedPlaylistShortcodes(html, (id) => {
622 return PlaylistService.get(site.id, id, audioUrl);
623 }, { isAdmin });
624 }
625 }
626 } else {
627 // LITE-modus (KLONKT_AUDIO=off): geen eigen audio (geen ffmpeg/stream-route).
628 // Externe embeds (YouTube/SoundCloud/Spotify) blijven wel; de eigen-audio-
629 // shortcodes ([[track]]/[[album]]/[[playlist]]) verwijderen we netjes.
630 html = AudioEmbedService.autoembed(html);
631 html = AudioEmbedService.embedMediaShortcodes(html);
632 html = AudioEmbedService.embedExternalLinkShortcodes(html);
633 html = html.replace(/\[\[(track|album|playlist):[^\]]+\]\]/gi, '');
634 }
635 post.content_html = html;
636
637 if (post.tags) {
638 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
639 } else {
640 post.tags = [];
641 }
642
643 // Comments: top-level + replies. Two-pass build: fetch all approved
644 // comments for the post, then group replies under their parent.
645 const commentRows = db.prepare(`
646 SELECT c.id, c.parent_comment_id, c.content, c.status, c.created_at,
647 c.author_id, u.username AS author_username, u.avatar_url AS author_avatar
648 FROM comments c JOIN users u ON u.id = c.author_id
649 WHERE c.post_id = ? AND c.status = 'approved'
650 ORDER BY c.created_at ASC
651 `).all(post.id);
652 const topLevel = [];
653 const repliesById = new Map();
654 for (const c of commentRows) {
655 if (c.parent_comment_id) {
656 if (!repliesById.has(c.parent_comment_id)) repliesById.set(c.parent_comment_id, []);
657 repliesById.get(c.parent_comment_id).push(c);
658 } else {
659 topLevel.push(c);
660 }
661 }
662 for (const c of topLevel) c.replies = repliesById.get(c.id) || [];
663 const totalComments = commentRows.length;
664
665 // Prev / next chronological (kept for back-compat — "post-nav" feature
666 // below the article still uses these as a simple linear navigation).
667 // Hub-modus: Gerelateerde posts + Newer/Older trekken uit ALLE users (alle
668 // sites), nieuwste->oudste. Solo-modus: binnen de huidige site (oud gedrag).
669 const isHub = res.locals.tenancy === 'hub';
670 // Per-post URL-basis: in hub wijst een link naar /user/<site-slug>/<post-slug>.
671 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
672
673 // Newer/Older over ALLE posts (gedeelde helper — ook door de fan-gate gebruikt).
674 const { newerPost, olderPost } = postNeighbors(site, post, isHub);
675
676 // ── Related posts: same-tag matching with recency fallback ─────
677 // Fetch ~50 candidates, score by tag overlap, take top 3.
678 // Excluding self via `id != ?`.
679 const candidates = isHub
680 ? db.prepare(`
681 SELECT p.id, p.slug, p.title, p.cover_image_url, p.published_at, p.tags, s.slug AS site_slug
682 FROM posts p JOIN sites s ON s.id = p.site_id
683 WHERE p.status = 'published' AND p.id != ?
684 ORDER BY p.published_at DESC LIMIT 50
685 `).all(post.id)
686 : db.prepare(`
687 SELECT id, slug, title, cover_image_url, published_at, tags
688 FROM posts
689 WHERE site_id = ? AND status = 'published' AND id != ?
690 ORDER BY published_at DESC LIMIT 50
691 `).all(site.id, post.id);
692
693 // Parse tags JSON safely; missing/malformed → empty array.
694 const parseTags = (raw) => {
695 if (!raw) return [];
696 try {
697 const v = JSON.parse(raw);
698 return Array.isArray(v) ? v.map(String) : [];
699 } catch { return []; }
700 };
701
702 const myTags = new Set(parseTags(post.tags));
703 let relatedPosts;
704 if (myTags.size > 0) {
705 // Score = number of overlapping tags. Posts with zero overlap are
706 // included only if we don't have 3 with-overlap candidates.
707 const scored = candidates.map(p => {
708 const theirTags = parseTags(p.tags);
709 const overlap = theirTags.reduce((n, t) => n + (myTags.has(t) ? 1 : 0), 0);
710 return { ...p, _overlap: overlap };
711 });
712 const withOverlap = scored.filter(p => p._overlap > 0)
713 .sort((a, b) => b._overlap - a._overlap || new Date(b.published_at) - new Date(a.published_at));
714 if (withOverlap.length >= 3) {
715 relatedPosts = withOverlap.slice(0, 3);
716 } else {
717 // Pad with most-recent non-overlap posts so the section is never empty
718 const overlapIds = new Set(withOverlap.map(p => p.id));
719 const filler = candidates.filter(p => !overlapIds.has(p.id));
720 relatedPosts = [...withOverlap, ...filler].slice(0, 3);
721 }
722 } else {
723 // No tags on current post → just show 3 most-recent
724 relatedPosts = candidates.slice(0, 3);
725 }
726 // Strip the internal _overlap field before sending to view
727 relatedPosts = relatedPosts.map(({ _overlap, tags, ...rest }) => ({ ...rest, _urlBase: urlBaseFor(rest) }));
728
729 // Likes / favorieten: aantal + of de ingelogde gebruiker deze post likete.
730 const likeCount = db.prepare('SELECT COUNT(*) AS c FROM post_likes WHERE post_id = ?').get(post.id).c;
731 const likedByMe = !!(req.session?.user &&
732 db.prepare('SELECT 1 FROM post_likes WHERE post_id = ? AND user_id = ?').get(post.id, req.session.user.id));
733
734 renderPage(req, res, 'pages/post', {
735 post,
736 newerPost,
737 olderPost,
738 relatedPosts,
739 comments: topLevel,
740 totalComments,
741 likeCount,
742 likedByMe,
743 pageTitle: post.title + ' - ' + site.title,
744 socialDescr: post.excerpt || '',
745 socialImage: post.cover_image_url || '',
746 bodyClass: 'on-post',
747 });
748});
749
750export default router;
751export { postNeighbors };
Note: See TracBrowser for help on using the repository browser.