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