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

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

i18n: translate Dutch code comments to English across src/

Comments in routes/services/views/config/middleware/assets translated to
English for the public repo. A few dev-facing throw/console message strings
were Englished too. No user-facing UI strings or i18n dictionary values changed
(src/services/i18n.js untouched). Logic unchanged.

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

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