source: Klonkt/src/routes/posts.js@ 16ce669

main
Last change on this file since 16ce669 was 535f955, checked in by roboburr <roboburr@…>, 3 months ago

feat: post likes + favourites page for logged-in users

  • New post_likes table (unique per post+user).
  • ♥ like button on the post (shared partial, htmx toggle via POST /posts/:id/like); shows the like count. Anonymous → button links to login.
  • /favorieten page (requireAuth) shows your liked posts (solo: own site, hub: across all sites with correct links). Link in account menu (sheet + topnav).

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

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