source: Klonkt/src/routes/posts.js@ 5bf63b7

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

feat(activitypub): phase 1b — Follow/Accept, HTTP Signatures, delivery

Inbox handles Follow (store follower + send signed Accept) and Undo Follow;
incoming requests are signature-verified (best-effort). Outgoing POSTs to inboxes
are signed (draft-cavage RSA-SHA256). New published public posts are delivered as
Create(Note) to followers' inboxes. Makes a Klonkt actor truly followable from
Mastodon; live interop test pending with Bart.

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

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