source: Klonkt/src/routes/posts.js@ 2248cd2

main
Last change on this file since 2248cd2 was d549549, checked in by roboburr <roboburr@…>, 3 months ago

Statistics module (Phase 3): cookie-free tracking + premium stats page

Counters: posts.view_count, audio_tracks.play_count, stat_daily
(pageviews/day) + stat_visitor_day (unique visitors via daily rotating
salted hash of IP+UA, never stored → no cookie, no consent needed).
StatsService records pageview on home + post-view (skips admins), play on
the initial player stream fetch. /admin/stats (god-only +
premiumUnlocked-gated): cards + 14-day cookie-free bar chart
(visitors/views) + top posts/tracks. Dashboard button is premium-gated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@…>

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