source: Klonkt/src/routes/posts.js@ 9a34d31

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

feat(meldingen): notifications — reply on comment, comment on post, like on post

For every logged-in user (Google visitors/fans and admin). Bell icon in the
header with unread counter + notifications page /notifications (via user menu
desktop + profile sheet mobile; badge also on the mobile Profile tab). Opening =
read. Triggers in comments (reply→comment author, top-level→post author) and
like (→post author); notify() skips notifying yourself. Table notifications
+ NotificationService. NL/EN/DE.

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

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