source: Klonkt/src/routes/posts.js@ 43dbf9c

main
Last change on this file since 43dbf9c was 6117035, checked in by roboburr <roboburr@…>, 3 months ago

fix: post navigation over ALL posts incl. pinned (no more pinned-only stack)

A pinned post showed only the pinned-stack navigation at the bottom. Now
Newer/Older runs through all posts in canonical feed order: solo = pinned
first by rank, then by date (same as the homepage); hub = globally by date.
Pinned posts simply sit in the continuous sequence. Neighbours determined
by index in that ordered list. The separate pinned-stack navigation
(PREVIOUS PINNED / TOP / BOTTOM) has been removed.

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

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