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

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

feat(activitypub): inbound interactions — replies, likes, boosts (Phase 2)

Inbox now stores incoming Create(reply to our note), Like and Announce (boost),
plus Undo(Like/Announce) and Delete(reply). New ap_interactions table; the post
page shows a 'From the fediverse' section (counts + replies with avatar/handle,
sanitized). Actor name/icon resolved best-effort; reply HTML sanitized.

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

  • Property mode set to 100644
File size: 30.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 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, cover_image_url: cover_image_url || null,
239 published_at: publishedAt, created_at: now,
240 }).catch(() => { /* best-effort */ });
241 }
242 }
243
244 // HTMX request -> return redirect header
245 if (req.headers['hx-request']) {
246 res.setHeader('HX-Redirect', `${res.locals.siteUrlBase || ''}/${finalSlug}`);
247 return res.send('OK');
248 }
249
250 res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
251});
252
253// ==================== EDIT POST FORM ====================
254router.get('/posts/:slug/edit', requireAuth, (req, res) => {
255 const site = res.locals.site;
256 if (!site) return res.status(404).send('Site required');
257
258 const post = db.prepare(
259 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
260 ).get(site.id, req.params.slug);
261
262 if (!post) return res.status(404).send('Post not found');
263 if (!PermissionsService.canEditPost(req.session.user, post, site)) {
264 return res.status(403).send('No permission');
265 }
266
267 if (post.tags) {
268 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
269 } else {
270 post.tags = [];
271 }
272
273 renderPage(req, res, 'pages/post-edit', {
274 post,
275 isNew: false,
276 pageTitle: 'Edit: ' + (post.title || 'Untitled'),
277 bodyClass: 'on-special',
278 });
279});
280
281// ==================== SAVE POST ====================
282router.post('/posts/:slug/save', requireAuth, (req, res) => {
283 const site = res.locals.site;
284 if (!site) return res.status(404).send('Site required');
285
286 const post = db.prepare(
287 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
288 ).get(site.id, req.params.slug);
289
290 if (!post) return res.status(404).send('Post not found');
291 if (!PermissionsService.canEditPost(req.session.user, post, site)) {
292 return res.status(403).send('No permission');
293 }
294
295 const { title, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
296 const fanOnly = req.body.fan_only ? 1 : 0;
297 const newSlug = req.body.slug;
298 const action = req.body.action || 'save';
299 const validTypes = new Set(['post', 'foto', 'video', 'audio']);
300 const finalType = validTypes.has(type) ? type : (post.type || 'post');
301
302 // Sanitize before storage — same pipeline as create.
303 const cleanContent = HtmlSanitizerService.sanitize(content || '');
304
305 let finalSlug = post.slug;
306 if (newSlug && newSlug !== post.slug) {
307 const cleaned = newSlug.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
308 const safe = RESERVED_SLUGS.has(cleaned) ? `${cleaned}-post` : cleaned;
309 // Duplicate slug? Make it unique automatically instead of rejecting (own post may keep its slug).
310 finalSlug = uniqueSlug(site.id, safe, post.id);
311 }
312
313 const now = new Date().toISOString();
314 let finalStatus = status || post.status;
315 let publishedAt = post.published_at;
316
317 if (action === 'publish') {
318 finalStatus = 'published';
319 if (!publishedAt) publishedAt = now;
320 }
321
322 // Release planning: published + future publish_at -> 'scheduled'.
323 let publishAt = null;
324 const pa = Date.parse(req.body.publish_at || '');
325 if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
326 finalStatus = 'scheduled';
327 publishAt = new Date(pa).toISOString();
328 publishedAt = null;
329 }
330
331 db.prepare(`
332 UPDATE posts SET
333 title = ?, content = ?, excerpt = ?, status = ?,
334 cover_image_url = ?, pinned = ?, tags = ?,
335 type = ?, noindex = ?, fan_only = ?, publish_at = ?,
336 slug = ?, published_at = ?, updated_at = ?
337 WHERE id = ?
338 `).run(
339 title, cleanContent, excerpt, finalStatus,
340 cover_image_url || null, parsePinnedRank(pinned),
341 JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
342 finalType, noindex ? 1 : 0, fanOnly, publishAt,
343 finalSlug, publishedAt, now, post.id
344 );
345
346 // Update FTS
347 try {
348 db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id);
349 if (finalStatus === 'published') {
350 db.prepare(
351 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
352 ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, post.id);
353 }
354 } catch (e) { /* FTS issues non-fatal */ }
355
356 res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
357});
358
359// ==================== DELETE POST ====================
360router.post('/posts/:slug/delete', requireAuth, (req, res) => {
361 const site = res.locals.site;
362 if (!site) return res.status(404).send('Site required');
363
364 const post = db.prepare(
365 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
366 ).get(site.id, req.params.slug);
367
368 if (!post) return res.status(404).send('Not found');
369 if (!PermissionsService.canDeletePost(req.session.user, post, site)) {
370 return res.status(403).send('No permission');
371 }
372
373 // ActivityPub: tell followers the post is gone (Delete + Tombstone), but only
374 // if it was actually federated (published + not fan-only). Fire before the row
375 // is removed — we still have post.id (= the Note id).
376 if (post.status === 'published' && !post.fan_only) {
377 ActivityPubService.deliverDelete(site, post).catch(() => { /* best-effort */ });
378 }
379
380 // Cascade: comments + FTS row, THEN the post itself.
381 // FK constraints are ON (config/database.js), so a bare DELETE on posts
382 // fails when comments still reference it.
383 const cascade = db.transaction(() => {
384 db.prepare('DELETE FROM comments WHERE post_id = ?').run(post.id);
385 try { db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id); } catch {}
386 db.prepare('DELETE FROM posts WHERE id = ?').run(post.id);
387 });
388 cascade();
389
390 if (req.headers['hx-request']) {
391 res.setHeader('HX-Redirect', res.locals.siteUrlBase || '/');
392 return res.send('OK');
393 }
394 res.redirect(res.locals.siteUrlBase || '/');
395});
396
397// ==================== ARCHIVE ====================
398router.get('/archive', (req, res) => {
399 const site = res.locals.site;
400 if (!site) return res.status(404).send('No site');
401
402 const posts = db.prepare(`
403 SELECT p.*, u.username as author_username
404 FROM posts p JOIN users u ON p.author_id = u.id
405 WHERE p.site_id = ? AND p.status = 'published'
406 ORDER BY p.published_at DESC
407 `).all(site.id);
408
409 // Group by year/month
410 const grouped = {};
411 for (const post of posts) {
412 if (!post.published_at) continue;
413 const d = new Date(post.published_at);
414 const year = d.getFullYear();
415 const month = d.getMonth();
416 const monthName = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'][month];
417
418 if (!grouped[year]) grouped[year] = {};
419 if (!grouped[year][monthName]) grouped[year][monthName] = [];
420 grouped[year][monthName].push(post);
421 }
422
423 renderPage(req, res, 'pages/archive', {
424 grouped,
425 totalPosts: posts.length,
426 pageTitle: 'Archive - ' + site.title,
427 bodyClass: 'on-archive',
428 });
429});
430
431// Path to the like button partial (for the htmx toggle re-render).
432const LIKE_PARTIAL = path.join(__dirname, '..', 'views', 'partials', 'like-button.ejs');
433
434// ==================== LIKE / FAVOURITE ====================
435// A logged-in user (not a viewer — the global guard blocks non-GET for viewers)
436// toggles a like on a published post. Returns the re-rendered button (htmx outerHTML swap).
437router.post('/posts/:id/like', requireAuth, (req, res) => {
438 const userId = req.session.user.id;
439 const post = db.prepare('SELECT id, status, slug, title, author_id FROM posts WHERE id = ?').get(req.params.id);
440 if (!post) return res.status(404).send('Post niet gevonden');
441 if (post.status !== 'published') return res.status(403).send('Niet beschikbaar');
442
443 const exists = db.prepare('SELECT 1 FROM post_likes WHERE post_id = ? AND user_id = ?').get(post.id, userId);
444 if (exists) {
445 db.prepare('DELETE FROM post_likes WHERE post_id = ? AND user_id = ?').run(post.id, userId);
446 } else {
447 db.prepare('INSERT OR IGNORE INTO post_likes (post_id, user_id) VALUES (?, ?)').run(post.id, userId);
448 // Notification for the post author (notify skips self-likes).
449 notify({
450 userId: post.author_id, actorId: userId, actorName: req.session.user.username, type: 'like',
451 postSlug: post.slug, postTitle: post.title, url: (res.locals.siteUrlBase || '') + '/' + post.slug,
452 });
453 }
454 const likeCount = db.prepare('SELECT COUNT(*) AS c FROM post_likes WHERE post_id = ?').get(post.id).c;
455
456 const html = ejs.render(fs.readFileSync(LIKE_PARTIAL, 'utf8'), {
457 post: { id: post.id }, likedByMe: !exists, likeCount, loggedIn: true, loginNext: '/',
458 });
459 res.send(html);
460});
461
462// Favourites = posts the logged-in user has liked. Solo: within the current
463// site. Hub: across all sites (with correct /user/<slug> links).
464router.get('/favorieten', requireAuth, (req, res) => {
465 const userId = req.session.user.id;
466 const isHub = res.locals.tenancy === 'hub';
467 const site = res.locals.site;
468 const rows = isHub
469 ? db.prepare(`
470 SELECT p.id, p.slug, p.title, p.excerpt, p.cover_image_url, p.published_at,
471 p.tags, p.type, p.pinned, p.status, s.slug AS site_slug
472 FROM post_likes pl JOIN posts p ON p.id = pl.post_id JOIN sites s ON s.id = p.site_id
473 WHERE pl.user_id = ? AND p.status = 'published'
474 ORDER BY pl.created_at DESC
475 `).all(userId)
476 : db.prepare(`
477 SELECT p.id, p.slug, p.title, p.excerpt, p.cover_image_url, p.published_at,
478 p.tags, p.type, p.pinned, p.status
479 FROM post_likes pl JOIN posts p ON p.id = pl.post_id
480 WHERE pl.user_id = ? AND p.site_id = ? AND p.status = 'published'
481 ORDER BY pl.created_at DESC
482 `).all(userId, site ? site.id : '');
483 const posts = rows.map((p) => ({ ...p, _urlBase: (isHub && p.site_slug) ? `/user/${p.site_slug}` : '' }));
484 renderPage(req, res, 'pages/favorites', { posts, pageTitle: 'Favorieten', bodyClass: 'on-favorites' });
485});
486
487// Newer/Older neighbours across ALL posts in feed order. Shared by the full
488// post render and the fan gate (premium fan_only) so navigation is consistent
489// everywhere. Solo: within the site (pinned first, then date). Hub: globally by date.
490function postNeighbors(site, post, isHub) {
491 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
492 const ordered = isHub
493 ? db.prepare(`
494 SELECT p.id, p.slug, p.title, p.pinned, s.slug AS site_slug
495 FROM posts p JOIN sites s ON s.id = p.site_id
496 WHERE p.status = 'published'
497 ORDER BY p.published_at DESC
498 `).all()
499 : db.prepare(`
500 SELECT id, slug, title, pinned FROM posts
501 WHERE site_id = ? AND status = 'published'
502 ORDER BY (pinned = 0) ASC, pinned ASC, published_at DESC
503 `).all(site.id);
504 const idx = ordered.findIndex((p) => p.id === post.id);
505 const newerPost = idx > 0 ? ordered[idx - 1] : null;
506 const olderPost = (idx >= 0 && idx < ordered.length - 1) ? ordered[idx + 1] : null;
507 if (newerPost) newerPost._urlBase = urlBaseFor(newerPost);
508 if (olderPost) olderPost._urlBase = urlBaseFor(olderPost);
509 return { newerPost, olderPost };
510}
511
512// ==================== VIEW POST (last route — catches /:slug) ====================
513router.get('/:slug', (req, res, next) => {
514 if (RESERVED_SLUGS.has(req.params.slug)) return next();
515
516 const site = res.locals.site;
517 if (!site) return next(); // -> nette 404 catch-all
518
519 const post = db.prepare(`
520 SELECT p.*, u.username as author_username, u.avatar_url as author_avatar
521 FROM posts p JOIN users u ON p.author_id = u.id
522 WHERE p.site_id = ? AND p.slug = ?
523 `).get(site.id, req.params.slug);
524
525 if (!post) return next(); // unknown slug -> clean 404 catch-all
526
527 // Permission to view: published OR (logged in + can edit)
528 if (post.status !== 'published') {
529 const canEdit = req.session?.user && PermissionsService.canEditPost(req.session.user, post, site);
530 if (!canEdit) return res.status(403).send('Not published');
531 }
532
533 // Fan-only preview (premium #3): full content only for logged-in fans.
534 // Anonymous visitors get a clean login gate instead of the content (the title/
535 // teaser may still appear elsewhere as a teaser).
536 if (post.fan_only && !(req.session && req.session.user)) {
537 // Same Newer/Older navigation as on a normal post, so the visitor doesn't get
538 // stuck on the fan gate but can keep browsing.
539 const { newerPost, olderPost } = postNeighbors(site, post, res.locals.tenancy === 'hub');
540 return renderPage(req, res, 'pages/fan-gate', {
541 pageTitle: post.title || 'Alleen voor fans',
542 bodyClass: 'on-special',
543 fgTitle: post.title || '',
544 fgNext: (res.locals.siteUrlBase || '') + '/' + post.slug,
545 newerPost,
546 olderPost,
547 });
548 }
549
550 // Statistics: count the view (skips admins + unpublished own-preview).
551 if (post.status === 'published') recordPostView(post, req);
552
553 // Render content. Content is now user-authored HTML (already sanitized on
554 // save). The pipeline still adds autoembed iframes and shortcode embeds:
555 // stored HTML → autoembed → [[track]]/[[album]]/[[playlist]] → response
556 let html = post.content || '';
557 if (audioEnabled()) {
558 if (site.enable_audio_player !== 0) {
559 html = AudioEmbedService.autoembed(html);
560 html = AudioEmbedService.embedMediaShortcodes(html);
561 html = AudioEmbedService.embedExternalLinkShortcodes(html);
562
563 // Fetch any tracks referenced by [[track:id]] in this post.
564 // Cheap to do unconditionally — only matches if the post actually has shortcodes.
565 const trackIds = [...html.matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)].map(m => m[1]);
566 if (trackIds.length) {
567 const placeholders = trackIds.map(() => '?').join(',');
568 const rows = db.prepare(`
569 SELECT t.id, t.title, t.artist, t.cover_url, t.credit, t.license,
570 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
571 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
572 WHERE t.site_id = ? AND t.id IN (${placeholders})
573 `).all(site.id, ...trackIds);
574 const byId = new Map(rows.map(r => [r.id, r]));
575 html = AudioEmbedService.embedTrackShortcodes(html, (id) => {
576 const r = byId.get(id);
577 if (!r) return null;
578 return {
579 id: r.id,
580 title: r.title,
581 artist: r.artist,
582 cover: r.cover_url,
583 credit: r.credit || '',
584 license: r.license || '',
585 link_spotify: r.link_spotify || '',
586 link_youtube: r.link_youtube || '',
587 link_soundcloud: r.link_soundcloud || '',
588 url: r.filename ? audioUrl(r.filename) : '', // '' = link-only track
589 };
590 });
591 }
592
593 // Album shortcodes: [[album:Some Album Name]]
594 const albumNames = [...html.matchAll(/\[\[album:([^\]]+)\]\]/g)].map(m => m[1].trim());
595 if (albumNames.length) {
596 const placeholders = albumNames.map(() => '?').join(',');
597 const albumRows = db.prepare(`
598 SELECT t.id, t.title, t.artist, t.album, t.cover_url, t.position,
599 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
600 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
601 WHERE t.site_id = ? AND t.album IN (${placeholders})
602 ORDER BY t.position ASC, t.created_at ASC
603 `).all(site.id, ...albumNames);
604 const byAlbum = new Map();
605 for (const r of albumRows) {
606 // Link-only tracks (no file) remain in the album overview (url '').
607 if (!byAlbum.has(r.album)) byAlbum.set(r.album, []);
608 byAlbum.get(r.album).push({
609 id: r.id,
610 url: r.filename ? audioUrl(r.filename) : '',
611 title: r.title || 'Untitled',
612 artist: r.artist || '',
613 cover: r.cover_url || '',
614 link_spotify: r.link_spotify || '',
615 link_youtube: r.link_youtube || '',
616 link_soundcloud: r.link_soundcloud || '',
617 });
618 }
619 html = AudioEmbedService.embedAlbumShortcodes(html, (name) => {
620 const tracks = byAlbum.get(name);
621 if (!tracks || !tracks.length) return null;
622 return {
623 title: name,
624 artist: tracks[0].artist || '',
625 cover: tracks[0].cover || '',
626 tracks,
627 };
628 });
629 }
630
631 // Playlist shortcodes: [[playlist:some-slug-id]] — first-class entity.
632 // Editing the playlist propagates to every post that embeds it.
633 const playlistIds = [...html.matchAll(/\[\[playlist:([a-z0-9][a-z0-9-]*)\]\]/gi)]
634 .map(m => m[1].toLowerCase());
635 if (playlistIds.length) {
636 const isAdmin = req.session?.user?.role === 'god';
637 html = AudioEmbedService.embedPlaylistShortcodes(html, (id) => {
638 return PlaylistService.get(site.id, id, audioUrl);
639 }, { isAdmin });
640 }
641 }
642 } else {
643 // LITE mode (KLONKT_AUDIO=off): no own audio (no ffmpeg/stream route).
644 // External embeds (YouTube/SoundCloud/Spotify) remain; the own-audio
645 // shortcodes ([[track]]/[[album]]/[[playlist]]) are cleanly stripped.
646 html = AudioEmbedService.autoembed(html);
647 html = AudioEmbedService.embedMediaShortcodes(html);
648 html = AudioEmbedService.embedExternalLinkShortcodes(html);
649 html = html.replace(/\[\[(track|album|playlist):[^\]]+\]\]/gi, '');
650 }
651 post.content_html = html;
652
653 if (post.tags) {
654 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
655 } else {
656 post.tags = [];
657 }
658
659 // Comments: top-level + replies. Two-pass build: fetch all approved
660 // comments for the post, then group replies under their parent.
661 const commentRows = db.prepare(`
662 SELECT c.id, c.parent_comment_id, c.content, c.status, c.created_at,
663 c.author_id, u.username AS author_username, u.avatar_url AS author_avatar
664 FROM comments c JOIN users u ON u.id = c.author_id
665 WHERE c.post_id = ? AND c.status = 'approved'
666 ORDER BY c.created_at ASC
667 `).all(post.id);
668 const topLevel = [];
669 const repliesById = new Map();
670 for (const c of commentRows) {
671 if (c.parent_comment_id) {
672 if (!repliesById.has(c.parent_comment_id)) repliesById.set(c.parent_comment_id, []);
673 repliesById.get(c.parent_comment_id).push(c);
674 } else {
675 topLevel.push(c);
676 }
677 }
678 for (const c of topLevel) c.replies = repliesById.get(c.id) || [];
679 const totalComments = commentRows.length;
680
681 // Prev / next chronological (kept for back-compat — "post-nav" feature
682 // below the article still uses these as a simple linear navigation).
683 // Hub mode: Related posts + Newer/Older pull from ALL users (all sites),
684 // newest first. Solo mode: within the current site (old behaviour).
685 const isHub = res.locals.tenancy === 'hub';
686 // Per-post URL base: in hub a link points to /user/<site-slug>/<post-slug>.
687 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
688
689 // Newer/Older across ALL posts (shared helper — also used by the fan gate).
690 const { newerPost, olderPost } = postNeighbors(site, post, isHub);
691
692 // ── Related posts: same-tag matching with recency fallback ─────
693 // Fetch ~50 candidates, score by tag overlap, take top 3.
694 // Excluding self via `id != ?`.
695 const candidates = isHub
696 ? db.prepare(`
697 SELECT p.id, p.slug, p.title, p.cover_image_url, p.published_at, p.tags, s.slug AS site_slug
698 FROM posts p JOIN sites s ON s.id = p.site_id
699 WHERE p.status = 'published' AND p.id != ?
700 ORDER BY p.published_at DESC LIMIT 50
701 `).all(post.id)
702 : db.prepare(`
703 SELECT id, slug, title, cover_image_url, published_at, tags
704 FROM posts
705 WHERE site_id = ? AND status = 'published' AND id != ?
706 ORDER BY published_at DESC LIMIT 50
707 `).all(site.id, post.id);
708
709 // Parse tags JSON safely; missing/malformed → empty array.
710 const parseTags = (raw) => {
711 if (!raw) return [];
712 try {
713 const v = JSON.parse(raw);
714 return Array.isArray(v) ? v.map(String) : [];
715 } catch { return []; }
716 };
717
718 const myTags = new Set(parseTags(post.tags));
719 let relatedPosts;
720 if (myTags.size > 0) {
721 // Score = number of overlapping tags. Posts with zero overlap are
722 // included only if we don't have 3 with-overlap candidates.
723 const scored = candidates.map(p => {
724 const theirTags = parseTags(p.tags);
725 const overlap = theirTags.reduce((n, t) => n + (myTags.has(t) ? 1 : 0), 0);
726 return { ...p, _overlap: overlap };
727 });
728 const withOverlap = scored.filter(p => p._overlap > 0)
729 .sort((a, b) => b._overlap - a._overlap || new Date(b.published_at) - new Date(a.published_at));
730 if (withOverlap.length >= 3) {
731 relatedPosts = withOverlap.slice(0, 3);
732 } else {
733 // Pad with most-recent non-overlap posts so the section is never empty
734 const overlapIds = new Set(withOverlap.map(p => p.id));
735 const filler = candidates.filter(p => !overlapIds.has(p.id));
736 relatedPosts = [...withOverlap, ...filler].slice(0, 3);
737 }
738 } else {
739 // No tags on current post → just show 3 most-recent
740 relatedPosts = candidates.slice(0, 3);
741 }
742 // Strip the internal _overlap field before sending to view
743 relatedPosts = relatedPosts.map(({ _overlap, tags, ...rest }) => ({ ...rest, _urlBase: urlBaseFor(rest) }));
744
745 // Likes / favourites: count + whether the logged-in user liked this post.
746 const likeCount = db.prepare('SELECT COUNT(*) AS c FROM post_likes WHERE post_id = ?').get(post.id).c;
747 const likedByMe = !!(req.session?.user &&
748 db.prepare('SELECT 1 FROM post_likes WHERE post_id = ? AND user_id = ?').get(post.id, req.session.user.id));
749
750 // Inbound fediverse activity (replies/likes/boosts) for this post.
751 let fediverse = { replies: [], likeCount: 0, announceCount: 0, total: 0 };
752 try { fediverse = ActivityPubService.getInteractions(post.id); } catch { /* non-fatal */ }
753
754 renderPage(req, res, 'pages/post', {
755 post,
756 newerPost,
757 olderPost,
758 relatedPosts,
759 comments: topLevel,
760 totalComments,
761 fediverse,
762 likeCount,
763 likedByMe,
764 pageTitle: post.title + ' - ' + site.title,
765 socialDescr: post.excerpt || '',
766 socialImage: post.cover_image_url || '',
767 bodyClass: 'on-post',
768 });
769});
770
771export default router;
772export { postNeighbors };
Note: See TracBrowser for help on using the repository browser.