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