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