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