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

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

feat(activitypub): federate images as attachments

Cover image + inline <img> are emitted as AP attachment (Document) with absolute
URLs + mediaType; <img> stripped from content (Mastodon strips it anyway). Outbox
+ post-create delivery now include cover_image_url.

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

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