| [7bc636b] | 1 | import express from 'express';
|
|---|
| 2 | import { v4 as uuid } from 'uuid';
|
|---|
| 3 | import path from 'path';
|
|---|
| 4 | import fs from 'fs';
|
|---|
| 5 | import { fileURLToPath } from 'url';
|
|---|
| 6 | import multer from 'multer';
|
|---|
| [535f955] | 7 | import ejs from 'ejs';
|
|---|
| [7bc636b] | 8 | import db from '../config/database.js';
|
|---|
| [55bc7f9] | 9 | import { requireAuth, requireSiteManager } from '../middleware/auth.js';
|
|---|
| [7bc636b] | 10 | import { renderPage } from '../middleware/render.js';
|
|---|
| [d549549] | 11 | import { recordPageview, recordPostView } from '../services/StatsService.js';
|
|---|
| [c9c6a2d] | 12 | import { notify } from '../services/NotificationService.js';
|
|---|
| [7bc636b] | 13 | import PermissionsService from '../services/PermissionsService.js';
|
|---|
| 14 | import MarkdownService from '../services/MarkdownService.js';
|
|---|
| 15 | import HtmlSanitizerService from '../services/HtmlSanitizerService.js';
|
|---|
| 16 | import AudioEmbedService from '../services/AudioEmbedService.js';
|
|---|
| 17 | import PlaylistService from '../services/PlaylistService.js';
|
|---|
| [cb01666] | 18 | import { audioEnabled } from '../config/features.js';
|
|---|
| [21522ae] | 19 | import { audioUrl } from '../services/AudioStreamService.js';
|
|---|
| [8f6225c] | 20 | import { toWebp } from '../services/ImageWebpService.js';
|
|---|
| [5bf63b7] | 21 | import ActivityPubService from '../services/ActivityPubService.js';
|
|---|
| [7bc636b] | 22 |
|
|---|
| 23 | const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|---|
| 24 | const POST_IMAGES_DIR = path.resolve(
|
|---|
| 25 | process.env.POST_IMAGES_PATH ||
|
|---|
| 26 | path.join(__dirname, '..', '..', 'storage', 'media', 'post-images')
|
|---|
| 27 | );
|
|---|
| 28 | fs.mkdirSync(POST_IMAGES_DIR, { recursive: true });
|
|---|
| 29 |
|
|---|
| 30 | const ALLOWED_IMAGE_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
|
|---|
| 31 | const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|---|
| 32 |
|
|---|
| 33 | const imageStorage = multer.diskStorage({
|
|---|
| 34 | destination: (req, file, cb) => cb(null, POST_IMAGES_DIR),
|
|---|
| 35 | filename: (req, file, cb) => {
|
|---|
| 36 | const ext = path.extname(file.originalname).toLowerCase();
|
|---|
| 37 | cb(null, `${uuid()}${ext}`);
|
|---|
| 38 | },
|
|---|
| 39 | });
|
|---|
| 40 | const imageUpload = multer({
|
|---|
| 41 | storage: imageStorage,
|
|---|
| 42 | limits: { fileSize: MAX_IMAGE_BYTES },
|
|---|
| 43 | fileFilter: (req, file, cb) => {
|
|---|
| 44 | const ext = path.extname(file.originalname).toLowerCase();
|
|---|
| 45 | if (!ALLOWED_IMAGE_EXT.has(ext)) {
|
|---|
| 46 | return cb(new Error('Image must be jpg/png/webp/gif'));
|
|---|
| 47 | }
|
|---|
| 48 | cb(null, true);
|
|---|
| 49 | },
|
|---|
| 50 | });
|
|---|
| 51 |
|
|---|
| [834bcc3] | 52 | // Generates a unique slug within the site: 'title', 'title-2', 'title-3', …
|
|---|
| 53 | // A second post with the same title is NOT rejected ("already exists"),
|
|---|
| 54 | // but automatically gets a free suffix. exceptId = the post being updated
|
|---|
| 55 | // (allowed to keep its own slug).
|
|---|
| [b27cde6] | 56 | function uniqueSlug(siteId, base, exceptId = null) {
|
|---|
| 57 | let candidate = base;
|
|---|
| 58 | let n = 2;
|
|---|
| 59 | for (;;) {
|
|---|
| 60 | const row = exceptId
|
|---|
| 61 | ? db.prepare('SELECT id FROM posts WHERE site_id = ? AND slug = ? AND id != ?').get(siteId, candidate, exceptId)
|
|---|
| 62 | : db.prepare('SELECT id FROM posts WHERE site_id = ? AND slug = ?').get(siteId, candidate);
|
|---|
| 63 | if (!row) return candidate;
|
|---|
| 64 | candidate = `${base}-${n++}`;
|
|---|
| 65 | }
|
|---|
| 66 | }
|
|---|
| 67 |
|
|---|
| [7bc636b] | 68 | const router = express.Router();
|
|---|
| 69 |
|
|---|
| 70 | // ==================== UPLOAD IMAGE (cover or content) ====================
|
|---|
| 71 | // Returns JSON {url} so the editor can stick it into the cover field or
|
|---|
| 72 | // insert a markdown  into content.
|
|---|
| 73 | router.post('/posts/upload-image', requireAuth, (req, res) => {
|
|---|
| 74 | imageUpload.single('image')(req, res, (err) => {
|
|---|
| 75 | if (err) return res.status(400).json({ error: err.message });
|
|---|
| 76 | if (!req.file) return res.status(400).json({ error: 'No file' });
|
|---|
| [8f6225c] | 77 | const url = '/media/post-images/' + toWebp(req.file);
|
|---|
| [7bc636b] | 78 | res.json({ url, size: req.file.size, mime: req.file.mimetype });
|
|---|
| 79 | });
|
|---|
| 80 | });
|
|---|
| 81 |
|
|---|
| 82 | const RESERVED_SLUGS = new Set([
|
|---|
| 83 | 'auth', 'admin', 'login', 'register', 'logout',
|
|---|
| 84 | 'archive', 'search', 'account', 'sites', 'comments',
|
|---|
| [8f2f97c] | 85 | 'posts', 'media', 'audio', 'forum',
|
|---|
| [535f955] | 86 | 'tag', 'type', 'user', 'users', 'artiesten', 'leden', 'favorieten', 'feed.xml', 'atom.xml', 'sitemap.xml',
|
|---|
| [7bc636b] | 87 | 'manifest.webmanifest', 'sw.js', 'favicon.ico', 'favicon.svg', 'assets',
|
|---|
| [7d932ce] | 88 | 'authorize_interaction', 'fediverse',
|
|---|
| [7bc636b] | 89 | ]);
|
|---|
| 90 |
|
|---|
| 91 | /**
|
|---|
| 92 | * Parse the form's `pinned` field into a non-negative integer rank.
|
|---|
| 93 | * Empty / undefined / NaN / negative → 0 (= not pinned).
|
|---|
| 94 | * Otherwise: integer rank (1 = top of pinned stack, 2 = below, ...).
|
|---|
| 95 | *
|
|---|
| 96 | * Multiple posts CAN share the same rank — UI shows them tiebroken by
|
|---|
| 97 | * published_at DESC. Saying #2 twice doesn't error, it just duplicates.
|
|---|
| 98 | * (We don't enforce uniqueness at this layer because race conditions and
|
|---|
| 99 | * "swap two ranks" workflows are easier without a UNIQUE constraint.)
|
|---|
| 100 | */
|
|---|
| 101 | function parsePinnedRank(raw) {
|
|---|
| 102 | const n = parseInt(raw, 10);
|
|---|
| 103 | if (!Number.isFinite(n) || n < 0) return 0;
|
|---|
| 104 | return n;
|
|---|
| 105 | }
|
|---|
| 106 |
|
|---|
| 107 | // ==================== HOME (Posts list) ====================
|
|---|
| 108 | router.get('/', (req, res) => {
|
|---|
| 109 | const site = res.locals.site;
|
|---|
| 110 |
|
|---|
| 111 | if (!site) {
|
|---|
| 112 | return renderPage(req, res, 'pages/welcome', {
|
|---|
| 113 | pageTitle: 'Welcome',
|
|---|
| 114 | bodyClass: 'on-special',
|
|---|
| 115 | });
|
|---|
| 116 | }
|
|---|
| 117 |
|
|---|
| 118 | // Pinned first — ordered by their rank (1 = top, 2 = below, etc).
|
|---|
| 119 | // pinned column is now an integer rank: 0 = not pinned, 1+ = pinned at
|
|---|
| 120 | // that position. Older boolean usage where pinned was always 1 still
|
|---|
| 121 | // works because integer ranks 1, 2, 3 sort the same as a flat 1.
|
|---|
| 122 | const pinnedPosts = db.prepare(`
|
|---|
| 123 | SELECT p.*, u.username as author_username
|
|---|
| 124 | FROM posts p JOIN users u ON p.author_id = u.id
|
|---|
| 125 | WHERE p.site_id = ? AND p.status = 'published' AND p.pinned > 0
|
|---|
| 126 | ORDER BY p.pinned ASC, p.published_at DESC
|
|---|
| 127 | `).all(site.id);
|
|---|
| 128 |
|
|---|
| 129 | // Regular posts: anything with pinned = 0
|
|---|
| 130 | const posts = db.prepare(`
|
|---|
| 131 | SELECT p.*, u.username as author_username
|
|---|
| 132 | FROM posts p JOIN users u ON p.author_id = u.id
|
|---|
| 133 | WHERE p.site_id = ? AND p.status = 'published' AND p.pinned = 0
|
|---|
| 134 | ORDER BY p.published_at DESC
|
|---|
| 135 | LIMIT 30
|
|---|
| 136 | `).all(site.id);
|
|---|
| 137 |
|
|---|
| [d549549] | 138 | recordPageview(site.id, req);
|
|---|
| 139 |
|
|---|
| [7bc636b] | 140 | renderPage(req, res, 'pages/home', {
|
|---|
| 141 | pinnedPosts,
|
|---|
| 142 | posts,
|
|---|
| 143 | pageTitle: site.title,
|
|---|
| 144 | socialDescr: site.description || site.tagline || '',
|
|---|
| 145 | bodyClass: 'on-home',
|
|---|
| 146 | });
|
|---|
| 147 | });
|
|---|
| 148 |
|
|---|
| 149 | // ==================== NEW POST FORM ====================
|
|---|
| 150 | router.get('/posts/new', requireAuth, (req, res) => {
|
|---|
| 151 | const site = res.locals.site;
|
|---|
| 152 | if (!site) return res.status(404).send('Site required');
|
|---|
| 153 | if (!PermissionsService.canCreatePost(req.session.user, site)) {
|
|---|
| 154 | return res.status(403).send('No permission');
|
|---|
| 155 | }
|
|---|
| 156 |
|
|---|
| 157 | renderPage(req, res, 'pages/post-edit', {
|
|---|
| 158 | post: {
|
|---|
| 159 | id: uuid(),
|
|---|
| 160 | title: '', slug: '', content: '', excerpt: '',
|
|---|
| 161 | status: 'draft', pinned: 0, tags: [],
|
|---|
| 162 | cover_image_url: '',
|
|---|
| 163 | },
|
|---|
| 164 | isNew: true,
|
|---|
| 165 | pageTitle: 'New post',
|
|---|
| 166 | bodyClass: 'on-special',
|
|---|
| 167 | });
|
|---|
| 168 | });
|
|---|
| 169 |
|
|---|
| 170 | // ==================== CREATE POST ====================
|
|---|
| 171 | router.post('/posts/create', requireAuth, (req, res) => {
|
|---|
| 172 | const site = res.locals.site;
|
|---|
| 173 | if (!site || !PermissionsService.canCreatePost(req.session.user, site)) {
|
|---|
| 174 | return res.status(403).send('No permission');
|
|---|
| 175 | }
|
|---|
| 176 |
|
|---|
| 177 | const { title, slug, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
|
|---|
| [b9dc94c] | 178 | const fanOnly = req.body.fan_only ? 1 : 0;
|
|---|
| [7bc636b] | 179 |
|
|---|
| 180 | // Content arrives as user-authored HTML from the WYSIWYG editor — sanitize
|
|---|
| 181 | // before storage. Shortcode text tokens like [[track:UUID]] live in text
|
|---|
| 182 | // nodes and pass through untouched.
|
|---|
| 183 | const cleanContent = HtmlSanitizerService.sanitize(content || '');
|
|---|
| 184 |
|
|---|
| 185 | // Generate slug from title if empty
|
|---|
| [b27cde6] | 186 | let finalSlug = (slug || title || '')
|
|---|
| [7bc636b] | 187 | .toLowerCase()
|
|---|
| 188 | .replace(/[^a-z0-9]+/g, '-')
|
|---|
| 189 | .replace(/^-|-$/g, '');
|
|---|
| 190 |
|
|---|
| 191 | if (!finalSlug) return res.status(400).send('Title or slug required');
|
|---|
| [b27cde6] | 192 | if (RESERVED_SLUGS.has(finalSlug)) finalSlug = `${finalSlug}-post`;
|
|---|
| [7bc636b] | 193 |
|
|---|
| [834bcc3] | 194 | // Duplicate title/slug? Make it unique automatically (title-2, title-3, …) instead of rejecting.
|
|---|
| [b27cde6] | 195 | finalSlug = uniqueSlug(site.id, finalSlug);
|
|---|
| [7bc636b] | 196 |
|
|---|
| 197 | const validTypes = new Set(['post', 'foto', 'video', 'audio']);
|
|---|
| 198 | const finalType = validTypes.has(type) ? type : 'post';
|
|---|
| 199 | const postId = uuid();
|
|---|
| 200 | const now = new Date().toISOString();
|
|---|
| [b9dc94c] | 201 | let finalStatus = status || 'draft';
|
|---|
| 202 | let publishedAt = finalStatus === 'published' ? now : null;
|
|---|
| [834bcc3] | 203 | // Release planning: published + a future publish_at -> 'scheduled'
|
|---|
| 204 | // (the Scheduler makes it live at that moment). Past/empty -> live immediately.
|
|---|
| [b9dc94c] | 205 | let publishAt = null;
|
|---|
| 206 | const pa = Date.parse(req.body.publish_at || '');
|
|---|
| [11b3ba5] | 207 | if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
|
|---|
| [b9dc94c] | 208 | finalStatus = 'scheduled';
|
|---|
| 209 | publishAt = new Date(pa).toISOString();
|
|---|
| 210 | publishedAt = null;
|
|---|
| 211 | }
|
|---|
| [7bc636b] | 212 |
|
|---|
| 213 | db.prepare(`
|
|---|
| 214 | INSERT INTO posts (
|
|---|
| 215 | id, site_id, slug, author_id, title, content, excerpt,
|
|---|
| [b9dc94c] | 216 | status, cover_image_url, pinned, tags, type, noindex, fan_only, publish_at,
|
|---|
| [7bc636b] | 217 | created_at, updated_at, published_at
|
|---|
| [b9dc94c] | 218 | ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|---|
| [7bc636b] | 219 | `).run(
|
|---|
| 220 | postId, site.id, finalSlug, req.session.user.id,
|
|---|
| 221 | title || finalSlug, cleanContent, excerpt || '',
|
|---|
| 222 | finalStatus, cover_image_url || null, parsePinnedRank(pinned),
|
|---|
| 223 | JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
|
|---|
| [b9dc94c] | 224 | finalType, noindex ? 1 : 0, fanOnly, publishAt,
|
|---|
| [7bc636b] | 225 | now, now, publishedAt
|
|---|
| 226 | );
|
|---|
| 227 |
|
|---|
| 228 | if (finalStatus === 'published') {
|
|---|
| 229 | try {
|
|---|
| 230 | db.prepare(
|
|---|
| 231 | 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
|
|---|
| 232 | ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, postId);
|
|---|
| 233 | } catch (e) { /* FTS index issues are non-fatal */ }
|
|---|
| [5bf63b7] | 234 |
|
|---|
| 235 | // ActivityPub: federate a freshly published public post to followers.
|
|---|
| 236 | if (!fanOnly) {
|
|---|
| 237 | ActivityPubService.deliverCreate(site, {
|
|---|
| 238 | id: postId, slug: finalSlug, title: title || finalSlug,
|
|---|
| [5a93ac0] | 239 | content: cleanContent, cover_image_url: cover_image_url || null,
|
|---|
| 240 | published_at: publishedAt, created_at: now,
|
|---|
| [5bf63b7] | 241 | }).catch(() => { /* best-effort */ });
|
|---|
| 242 | }
|
|---|
| [7bc636b] | 243 | }
|
|---|
| 244 |
|
|---|
| 245 | // HTMX request -> return redirect header
|
|---|
| 246 | if (req.headers['hx-request']) {
|
|---|
| 247 | res.setHeader('HX-Redirect', `${res.locals.siteUrlBase || ''}/${finalSlug}`);
|
|---|
| 248 | return res.send('OK');
|
|---|
| 249 | }
|
|---|
| 250 |
|
|---|
| 251 | res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
|
|---|
| 252 | });
|
|---|
| 253 |
|
|---|
| 254 | // ==================== EDIT POST FORM ====================
|
|---|
| 255 | router.get('/posts/:slug/edit', 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 | if (post.tags) {
|
|---|
| 269 | try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
|
|---|
| 270 | } else {
|
|---|
| 271 | post.tags = [];
|
|---|
| 272 | }
|
|---|
| 273 |
|
|---|
| 274 | renderPage(req, res, 'pages/post-edit', {
|
|---|
| 275 | post,
|
|---|
| 276 | isNew: false,
|
|---|
| 277 | pageTitle: 'Edit: ' + (post.title || 'Untitled'),
|
|---|
| 278 | bodyClass: 'on-special',
|
|---|
| 279 | });
|
|---|
| 280 | });
|
|---|
| 281 |
|
|---|
| 282 | // ==================== SAVE POST ====================
|
|---|
| 283 | router.post('/posts/:slug/save', requireAuth, (req, res) => {
|
|---|
| 284 | const site = res.locals.site;
|
|---|
| 285 | if (!site) return res.status(404).send('Site required');
|
|---|
| 286 |
|
|---|
| 287 | const post = db.prepare(
|
|---|
| 288 | 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
|
|---|
| 289 | ).get(site.id, req.params.slug);
|
|---|
| 290 |
|
|---|
| 291 | if (!post) return res.status(404).send('Post not found');
|
|---|
| 292 | if (!PermissionsService.canEditPost(req.session.user, post, site)) {
|
|---|
| 293 | return res.status(403).send('No permission');
|
|---|
| 294 | }
|
|---|
| 295 |
|
|---|
| 296 | const { title, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
|
|---|
| [b9dc94c] | 297 | const fanOnly = req.body.fan_only ? 1 : 0;
|
|---|
| [7bc636b] | 298 | const newSlug = req.body.slug;
|
|---|
| 299 | const action = req.body.action || 'save';
|
|---|
| 300 | const validTypes = new Set(['post', 'foto', 'video', 'audio']);
|
|---|
| 301 | const finalType = validTypes.has(type) ? type : (post.type || 'post');
|
|---|
| 302 |
|
|---|
| 303 | // Sanitize before storage — same pipeline as create.
|
|---|
| 304 | const cleanContent = HtmlSanitizerService.sanitize(content || '');
|
|---|
| 305 |
|
|---|
| 306 | let finalSlug = post.slug;
|
|---|
| 307 | if (newSlug && newSlug !== post.slug) {
|
|---|
| 308 | const cleaned = newSlug.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
|---|
| [b27cde6] | 309 | const safe = RESERVED_SLUGS.has(cleaned) ? `${cleaned}-post` : cleaned;
|
|---|
| [834bcc3] | 310 | // Duplicate slug? Make it unique automatically instead of rejecting (own post may keep its slug).
|
|---|
| [b27cde6] | 311 | finalSlug = uniqueSlug(site.id, safe, post.id);
|
|---|
| [7bc636b] | 312 | }
|
|---|
| 313 |
|
|---|
| 314 | const now = new Date().toISOString();
|
|---|
| 315 | let finalStatus = status || post.status;
|
|---|
| 316 | let publishedAt = post.published_at;
|
|---|
| 317 |
|
|---|
| 318 | if (action === 'publish') {
|
|---|
| 319 | finalStatus = 'published';
|
|---|
| 320 | if (!publishedAt) publishedAt = now;
|
|---|
| 321 | }
|
|---|
| 322 |
|
|---|
| [834bcc3] | 323 | // Release planning: published + future publish_at -> 'scheduled'.
|
|---|
| [b9dc94c] | 324 | let publishAt = null;
|
|---|
| 325 | const pa = Date.parse(req.body.publish_at || '');
|
|---|
| [11b3ba5] | 326 | if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
|
|---|
| [b9dc94c] | 327 | finalStatus = 'scheduled';
|
|---|
| 328 | publishAt = new Date(pa).toISOString();
|
|---|
| 329 | publishedAt = null;
|
|---|
| 330 | }
|
|---|
| 331 |
|
|---|
| [7bc636b] | 332 | db.prepare(`
|
|---|
| 333 | UPDATE posts SET
|
|---|
| 334 | title = ?, content = ?, excerpt = ?, status = ?,
|
|---|
| 335 | cover_image_url = ?, pinned = ?, tags = ?,
|
|---|
| [b9dc94c] | 336 | type = ?, noindex = ?, fan_only = ?, publish_at = ?,
|
|---|
| [7bc636b] | 337 | slug = ?, published_at = ?, updated_at = ?
|
|---|
| 338 | WHERE id = ?
|
|---|
| 339 | `).run(
|
|---|
| 340 | title, cleanContent, excerpt, finalStatus,
|
|---|
| 341 | cover_image_url || null, parsePinnedRank(pinned),
|
|---|
| 342 | JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
|
|---|
| [b9dc94c] | 343 | finalType, noindex ? 1 : 0, fanOnly, publishAt,
|
|---|
| [7bc636b] | 344 | finalSlug, publishedAt, now, post.id
|
|---|
| 345 | );
|
|---|
| 346 |
|
|---|
| 347 | // Update FTS
|
|---|
| 348 | try {
|
|---|
| 349 | db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id);
|
|---|
| 350 | if (finalStatus === 'published') {
|
|---|
| 351 | db.prepare(
|
|---|
| 352 | 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
|
|---|
| 353 | ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, post.id);
|
|---|
| 354 | }
|
|---|
| 355 | } catch (e) { /* FTS issues non-fatal */ }
|
|---|
| 356 |
|
|---|
| 357 | res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
|
|---|
| 358 | });
|
|---|
| 359 |
|
|---|
| 360 | // ==================== DELETE POST ====================
|
|---|
| 361 | router.post('/posts/:slug/delete', requireAuth, (req, res) => {
|
|---|
| 362 | const site = res.locals.site;
|
|---|
| 363 | if (!site) return res.status(404).send('Site required');
|
|---|
| 364 |
|
|---|
| 365 | const post = db.prepare(
|
|---|
| 366 | 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
|
|---|
| 367 | ).get(site.id, req.params.slug);
|
|---|
| 368 |
|
|---|
| 369 | if (!post) return res.status(404).send('Not found');
|
|---|
| 370 | if (!PermissionsService.canDeletePost(req.session.user, post, site)) {
|
|---|
| 371 | return res.status(403).send('No permission');
|
|---|
| 372 | }
|
|---|
| 373 |
|
|---|
| [eb852c5] | 374 | // ActivityPub: tell followers the post is gone (Delete + Tombstone), but only
|
|---|
| 375 | // if it was actually federated (published + not fan-only). Fire before the row
|
|---|
| 376 | // is removed — we still have post.id (= the Note id).
|
|---|
| 377 | if (post.status === 'published' && !post.fan_only) {
|
|---|
| 378 | ActivityPubService.deliverDelete(site, post).catch(() => { /* best-effort */ });
|
|---|
| 379 | }
|
|---|
| 380 |
|
|---|
| [7bc636b] | 381 | // Cascade: comments + FTS row, THEN the post itself.
|
|---|
| 382 | // FK constraints are ON (config/database.js), so a bare DELETE on posts
|
|---|
| 383 | // fails when comments still reference it.
|
|---|
| 384 | const cascade = db.transaction(() => {
|
|---|
| 385 | db.prepare('DELETE FROM comments WHERE post_id = ?').run(post.id);
|
|---|
| 386 | try { db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id); } catch {}
|
|---|
| 387 | db.prepare('DELETE FROM posts WHERE id = ?').run(post.id);
|
|---|
| 388 | });
|
|---|
| 389 | cascade();
|
|---|
| 390 |
|
|---|
| 391 | if (req.headers['hx-request']) {
|
|---|
| 392 | res.setHeader('HX-Redirect', res.locals.siteUrlBase || '/');
|
|---|
| 393 | return res.send('OK');
|
|---|
| 394 | }
|
|---|
| 395 | res.redirect(res.locals.siteUrlBase || '/');
|
|---|
| 396 | });
|
|---|
| 397 |
|
|---|
| 398 | // ==================== ARCHIVE ====================
|
|---|
| 399 | router.get('/archive', (req, res) => {
|
|---|
| 400 | const site = res.locals.site;
|
|---|
| 401 | if (!site) return res.status(404).send('No site');
|
|---|
| 402 |
|
|---|
| 403 | const posts = db.prepare(`
|
|---|
| 404 | SELECT p.*, u.username as author_username
|
|---|
| 405 | FROM posts p JOIN users u ON p.author_id = u.id
|
|---|
| 406 | WHERE p.site_id = ? AND p.status = 'published'
|
|---|
| 407 | ORDER BY p.published_at DESC
|
|---|
| 408 | `).all(site.id);
|
|---|
| 409 |
|
|---|
| 410 | // Group by year/month
|
|---|
| 411 | const grouped = {};
|
|---|
| 412 | for (const post of posts) {
|
|---|
| 413 | if (!post.published_at) continue;
|
|---|
| 414 | const d = new Date(post.published_at);
|
|---|
| 415 | const year = d.getFullYear();
|
|---|
| 416 | const month = d.getMonth();
|
|---|
| 417 | const monthName = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'][month];
|
|---|
| 418 |
|
|---|
| 419 | if (!grouped[year]) grouped[year] = {};
|
|---|
| 420 | if (!grouped[year][monthName]) grouped[year][monthName] = [];
|
|---|
| 421 | grouped[year][monthName].push(post);
|
|---|
| 422 | }
|
|---|
| 423 |
|
|---|
| 424 | renderPage(req, res, 'pages/archive', {
|
|---|
| 425 | grouped,
|
|---|
| 426 | totalPosts: posts.length,
|
|---|
| 427 | pageTitle: 'Archive - ' + site.title,
|
|---|
| 428 | bodyClass: 'on-archive',
|
|---|
| 429 | });
|
|---|
| 430 | });
|
|---|
| 431 |
|
|---|
| [834bcc3] | 432 | // Path to the like button partial (for the htmx toggle re-render).
|
|---|
| [535f955] | 433 | const LIKE_PARTIAL = path.join(__dirname, '..', 'views', 'partials', 'like-button.ejs');
|
|---|
| 434 |
|
|---|
| [834bcc3] | 435 | // ==================== LIKE / FAVOURITE ====================
|
|---|
| 436 | // A logged-in user (not a viewer — the global guard blocks non-GET for viewers)
|
|---|
| 437 | // toggles a like on a published post. Returns the re-rendered button (htmx outerHTML swap).
|
|---|
| [535f955] | 438 | router.post('/posts/:id/like', requireAuth, (req, res) => {
|
|---|
| 439 | const userId = req.session.user.id;
|
|---|
| [c9c6a2d] | 440 | const post = db.prepare('SELECT id, status, slug, title, author_id FROM posts WHERE id = ?').get(req.params.id);
|
|---|
| [535f955] | 441 | if (!post) return res.status(404).send('Post niet gevonden');
|
|---|
| 442 | if (post.status !== 'published') return res.status(403).send('Niet beschikbaar');
|
|---|
| 443 |
|
|---|
| 444 | const exists = db.prepare('SELECT 1 FROM post_likes WHERE post_id = ? AND user_id = ?').get(post.id, userId);
|
|---|
| 445 | if (exists) {
|
|---|
| 446 | db.prepare('DELETE FROM post_likes WHERE post_id = ? AND user_id = ?').run(post.id, userId);
|
|---|
| 447 | } else {
|
|---|
| 448 | db.prepare('INSERT OR IGNORE INTO post_likes (post_id, user_id) VALUES (?, ?)').run(post.id, userId);
|
|---|
| [834bcc3] | 449 | // Notification for the post author (notify skips self-likes).
|
|---|
| [c9c6a2d] | 450 | notify({
|
|---|
| 451 | userId: post.author_id, actorId: userId, actorName: req.session.user.username, type: 'like',
|
|---|
| 452 | postSlug: post.slug, postTitle: post.title, url: (res.locals.siteUrlBase || '') + '/' + post.slug,
|
|---|
| 453 | });
|
|---|
| [535f955] | 454 | }
|
|---|
| 455 | const likeCount = db.prepare('SELECT COUNT(*) AS c FROM post_likes WHERE post_id = ?').get(post.id).c;
|
|---|
| 456 |
|
|---|
| 457 | const html = ejs.render(fs.readFileSync(LIKE_PARTIAL, 'utf8'), {
|
|---|
| 458 | post: { id: post.id }, likedByMe: !exists, likeCount, loggedIn: true, loginNext: '/',
|
|---|
| 459 | });
|
|---|
| 460 | res.send(html);
|
|---|
| 461 | });
|
|---|
| 462 |
|
|---|
| [834bcc3] | 463 | // Favourites = posts the logged-in user has liked. Solo: within the current
|
|---|
| 464 | // site. Hub: across all sites (with correct /user/<slug> links).
|
|---|
| [535f955] | 465 | router.get('/favorieten', requireAuth, (req, res) => {
|
|---|
| 466 | const userId = req.session.user.id;
|
|---|
| 467 | const isHub = res.locals.tenancy === 'hub';
|
|---|
| 468 | const site = res.locals.site;
|
|---|
| 469 | const rows = isHub
|
|---|
| 470 | ? db.prepare(`
|
|---|
| 471 | SELECT p.id, p.slug, p.title, p.excerpt, p.cover_image_url, p.published_at,
|
|---|
| 472 | p.tags, p.type, p.pinned, p.status, s.slug AS site_slug
|
|---|
| 473 | FROM post_likes pl JOIN posts p ON p.id = pl.post_id JOIN sites s ON s.id = p.site_id
|
|---|
| 474 | WHERE pl.user_id = ? AND p.status = 'published'
|
|---|
| 475 | ORDER BY pl.created_at DESC
|
|---|
| 476 | `).all(userId)
|
|---|
| 477 | : db.prepare(`
|
|---|
| 478 | SELECT p.id, p.slug, p.title, p.excerpt, p.cover_image_url, p.published_at,
|
|---|
| 479 | p.tags, p.type, p.pinned, p.status
|
|---|
| 480 | FROM post_likes pl JOIN posts p ON p.id = pl.post_id
|
|---|
| 481 | WHERE pl.user_id = ? AND p.site_id = ? AND p.status = 'published'
|
|---|
| 482 | ORDER BY pl.created_at DESC
|
|---|
| 483 | `).all(userId, site ? site.id : '');
|
|---|
| 484 | const posts = rows.map((p) => ({ ...p, _urlBase: (isHub && p.site_slug) ? `/user/${p.site_slug}` : '' }));
|
|---|
| 485 | renderPage(req, res, 'pages/favorites', { posts, pageTitle: 'Favorieten', bodyClass: 'on-favorites' });
|
|---|
| 486 | });
|
|---|
| 487 |
|
|---|
| [834bcc3] | 488 | // Newer/Older neighbours across ALL posts in feed order. Shared by the full
|
|---|
| 489 | // post render and the fan gate (premium fan_only) so navigation is consistent
|
|---|
| 490 | // everywhere. Solo: within the site (pinned first, then date). Hub: globally by date.
|
|---|
| [1e2e9e7] | 491 | function postNeighbors(site, post, isHub) {
|
|---|
| 492 | const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
|
|---|
| 493 | const ordered = isHub
|
|---|
| 494 | ? db.prepare(`
|
|---|
| [8cdb377] | 495 | SELECT p.id, p.slug, p.title, p.pinned, s.slug AS site_slug
|
|---|
| [1e2e9e7] | 496 | FROM posts p JOIN sites s ON s.id = p.site_id
|
|---|
| 497 | WHERE p.status = 'published'
|
|---|
| 498 | ORDER BY p.published_at DESC
|
|---|
| 499 | `).all()
|
|---|
| 500 | : db.prepare(`
|
|---|
| [8cdb377] | 501 | SELECT id, slug, title, pinned FROM posts
|
|---|
| [1e2e9e7] | 502 | WHERE site_id = ? AND status = 'published'
|
|---|
| 503 | ORDER BY (pinned = 0) ASC, pinned ASC, published_at DESC
|
|---|
| 504 | `).all(site.id);
|
|---|
| 505 | const idx = ordered.findIndex((p) => p.id === post.id);
|
|---|
| 506 | const newerPost = idx > 0 ? ordered[idx - 1] : null;
|
|---|
| 507 | const olderPost = (idx >= 0 && idx < ordered.length - 1) ? ordered[idx + 1] : null;
|
|---|
| 508 | if (newerPost) newerPost._urlBase = urlBaseFor(newerPost);
|
|---|
| 509 | if (olderPost) olderPost._urlBase = urlBaseFor(olderPost);
|
|---|
| 510 | return { newerPost, olderPost };
|
|---|
| 511 | }
|
|---|
| 512 |
|
|---|
| [3d7312a] | 513 | // ==================== REMOTE INTERACTION (reply to a fediverse post as your site) ====================
|
|---|
| 514 | // Standard fediverse "reply from your own server" landing endpoint. A post page
|
|---|
| 515 | // elsewhere bounces the visitor here with ?uri=<remote post>; the site owner
|
|---|
| 516 | // composes a reply that federates back to that post.
|
|---|
| 517 | router.get('/authorize_interaction', requireSiteManager, async (req, res) => {
|
|---|
| 518 | const site = res.locals.site;
|
|---|
| 519 | const uri = (req.query.uri || '').toString();
|
|---|
| [41a7637] | 520 | const sent = !!req.query.sent;
|
|---|
| [3d7312a] | 521 | let target = null;
|
|---|
| [41a7637] | 522 | if (!sent) { try { target = await ActivityPubService.resolveRemoteNote(uri); } catch { /* ignore */ } }
|
|---|
| [3d7312a] | 523 | renderPage(req, res, 'pages/authorize-interaction', {
|
|---|
| 524 | pageTitle: 'Reageer via de fediverse',
|
|---|
| 525 | bodyClass: 'on-special',
|
|---|
| 526 | uri,
|
|---|
| 527 | target,
|
|---|
| [41a7637] | 528 | sent,
|
|---|
| [3d7312a] | 529 | siteTitle: site ? site.title : '',
|
|---|
| 530 | });
|
|---|
| 531 | });
|
|---|
| 532 |
|
|---|
| [41a7637] | 533 | router.post('/authorize_interaction', requireSiteManager, (req, res) => {
|
|---|
| [3d7312a] | 534 | const site = res.locals.site;
|
|---|
| 535 | const uri = (req.body.uri || '').toString();
|
|---|
| 536 | const text = (req.body.text || '').toString();
|
|---|
| 537 | if (site && uri && text.trim()) {
|
|---|
| [41a7637] | 538 | // Resolve + deliver in the background so Send responds instantly.
|
|---|
| 539 | ActivityPubService.resolveRemoteNote(uri)
|
|---|
| [de3d24b] | 540 | .then((parent) => parent && ActivityPubService.deliverReply(site, { postId: parent.localPostId || '', postSlug: null, parent, text }))
|
|---|
| [41a7637] | 541 | .catch((e) => console.warn('[AP] remote reply failed:', e.message));
|
|---|
| [3d7312a] | 542 | }
|
|---|
| [41a7637] | 543 | res.redirect('/authorize_interaction?sent=1&uri=' + encodeURIComponent(uri));
|
|---|
| [3d7312a] | 544 | });
|
|---|
| 545 |
|
|---|
| [7d932ce] | 546 | // Manage / delete your own outbound fediverse replies (site owner only).
|
|---|
| 547 | router.get('/fediverse', requireSiteManager, (req, res) => {
|
|---|
| 548 | const site = res.locals.site;
|
|---|
| 549 | const items = site ? ActivityPubService.listOutbox(site.slug) : [];
|
|---|
| 550 | renderPage(req, res, 'pages/authorize-interaction', {
|
|---|
| 551 | pageTitle: 'Mijn fediverse-reacties', bodyClass: 'on-special',
|
|---|
| 552 | manage: items, uri: '', target: null, sent: false, siteTitle: site ? site.title : '',
|
|---|
| 553 | });
|
|---|
| 554 | });
|
|---|
| 555 |
|
|---|
| 556 | router.post('/fediverse/:id/delete', requireSiteManager, async (req, res) => {
|
|---|
| 557 | const site = res.locals.site;
|
|---|
| 558 | if (site) {
|
|---|
| 559 | try { await ActivityPubService.deliverOutboxDelete(site, req.params.id); }
|
|---|
| 560 | catch (e) { console.warn('[AP] outbox delete failed:', e.message); }
|
|---|
| 561 | }
|
|---|
| 562 | res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/fediverse`);
|
|---|
| 563 | });
|
|---|
| 564 |
|
|---|
| [7bc636b] | 565 | // ==================== VIEW POST (last route — catches /:slug) ====================
|
|---|
| 566 | router.get('/:slug', (req, res, next) => {
|
|---|
| 567 | if (RESERVED_SLUGS.has(req.params.slug)) return next();
|
|---|
| 568 |
|
|---|
| 569 | const site = res.locals.site;
|
|---|
| [59e522f] | 570 | if (!site) return next(); // -> nette 404 catch-all
|
|---|
| [7bc636b] | 571 |
|
|---|
| 572 | const post = db.prepare(`
|
|---|
| 573 | SELECT p.*, u.username as author_username, u.avatar_url as author_avatar
|
|---|
| 574 | FROM posts p JOIN users u ON p.author_id = u.id
|
|---|
| 575 | WHERE p.site_id = ? AND p.slug = ?
|
|---|
| 576 | `).get(site.id, req.params.slug);
|
|---|
| 577 |
|
|---|
| [834bcc3] | 578 | if (!post) return next(); // unknown slug -> clean 404 catch-all
|
|---|
| [7bc636b] | 579 |
|
|---|
| 580 | // Permission to view: published OR (logged in + can edit)
|
|---|
| 581 | if (post.status !== 'published') {
|
|---|
| 582 | const canEdit = req.session?.user && PermissionsService.canEditPost(req.session.user, post, site);
|
|---|
| 583 | if (!canEdit) return res.status(403).send('Not published');
|
|---|
| 584 | }
|
|---|
| 585 |
|
|---|
| [834bcc3] | 586 | // Fan-only preview (premium #3): full content only for logged-in fans.
|
|---|
| 587 | // Anonymous visitors get a clean login gate instead of the content (the title/
|
|---|
| 588 | // teaser may still appear elsewhere as a teaser).
|
|---|
| [b9dc94c] | 589 | if (post.fan_only && !(req.session && req.session.user)) {
|
|---|
| [834bcc3] | 590 | // Same Newer/Older navigation as on a normal post, so the visitor doesn't get
|
|---|
| 591 | // stuck on the fan gate but can keep browsing.
|
|---|
| [1e2e9e7] | 592 | const { newerPost, olderPost } = postNeighbors(site, post, res.locals.tenancy === 'hub');
|
|---|
| [b9dc94c] | 593 | return renderPage(req, res, 'pages/fan-gate', {
|
|---|
| 594 | pageTitle: post.title || 'Alleen voor fans',
|
|---|
| 595 | bodyClass: 'on-special',
|
|---|
| 596 | fgTitle: post.title || '',
|
|---|
| 597 | fgNext: (res.locals.siteUrlBase || '') + '/' + post.slug,
|
|---|
| [1e2e9e7] | 598 | newerPost,
|
|---|
| 599 | olderPost,
|
|---|
| [b9dc94c] | 600 | });
|
|---|
| 601 | }
|
|---|
| 602 |
|
|---|
| [834bcc3] | 603 | // Statistics: count the view (skips admins + unpublished own-preview).
|
|---|
| [d549549] | 604 | if (post.status === 'published') recordPostView(post, req);
|
|---|
| 605 |
|
|---|
| [7bc636b] | 606 | // Render content. Content is now user-authored HTML (already sanitized on
|
|---|
| 607 | // save). The pipeline still adds autoembed iframes and shortcode embeds:
|
|---|
| 608 | // stored HTML → autoembed → [[track]]/[[album]]/[[playlist]] → response
|
|---|
| 609 | let html = post.content || '';
|
|---|
| [cb01666] | 610 | if (audioEnabled()) {
|
|---|
| [7bc636b] | 611 | if (site.enable_audio_player !== 0) {
|
|---|
| 612 | html = AudioEmbedService.autoembed(html);
|
|---|
| [1907a18] | 613 | html = AudioEmbedService.embedMediaShortcodes(html);
|
|---|
| [7bc636b] | 614 | html = AudioEmbedService.embedExternalLinkShortcodes(html);
|
|---|
| 615 |
|
|---|
| 616 | // Fetch any tracks referenced by [[track:id]] in this post.
|
|---|
| 617 | // Cheap to do unconditionally — only matches if the post actually has shortcodes.
|
|---|
| 618 | const trackIds = [...html.matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)].map(m => m[1]);
|
|---|
| 619 | if (trackIds.length) {
|
|---|
| 620 | const placeholders = trackIds.map(() => '?').join(',');
|
|---|
| 621 | const rows = db.prepare(`
|
|---|
| [183875b] | 622 | SELECT t.id, t.title, t.artist, t.cover_url, t.credit, t.license,
|
|---|
| 623 | t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
|
|---|
| [7bc636b] | 624 | FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
|
|---|
| 625 | WHERE t.site_id = ? AND t.id IN (${placeholders})
|
|---|
| 626 | `).all(site.id, ...trackIds);
|
|---|
| 627 | const byId = new Map(rows.map(r => [r.id, r]));
|
|---|
| 628 | html = AudioEmbedService.embedTrackShortcodes(html, (id) => {
|
|---|
| 629 | const r = byId.get(id);
|
|---|
| [d727e92] | 630 | if (!r) return null;
|
|---|
| [7bc636b] | 631 | return {
|
|---|
| 632 | id: r.id,
|
|---|
| 633 | title: r.title,
|
|---|
| 634 | artist: r.artist,
|
|---|
| 635 | cover: r.cover_url,
|
|---|
| [0d7acdf] | 636 | credit: r.credit || '',
|
|---|
| 637 | license: r.license || '',
|
|---|
| [183875b] | 638 | link_spotify: r.link_spotify || '',
|
|---|
| 639 | link_youtube: r.link_youtube || '',
|
|---|
| 640 | link_soundcloud: r.link_soundcloud || '',
|
|---|
| [d727e92] | 641 | url: r.filename ? audioUrl(r.filename) : '', // '' = link-only track
|
|---|
| [7bc636b] | 642 | };
|
|---|
| 643 | });
|
|---|
| 644 | }
|
|---|
| 645 |
|
|---|
| 646 | // Album shortcodes: [[album:Some Album Name]]
|
|---|
| 647 | const albumNames = [...html.matchAll(/\[\[album:([^\]]+)\]\]/g)].map(m => m[1].trim());
|
|---|
| 648 | if (albumNames.length) {
|
|---|
| 649 | const placeholders = albumNames.map(() => '?').join(',');
|
|---|
| 650 | const albumRows = db.prepare(`
|
|---|
| [183875b] | 651 | SELECT t.id, t.title, t.artist, t.album, t.cover_url, t.position,
|
|---|
| 652 | t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
|
|---|
| [7bc636b] | 653 | FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
|
|---|
| 654 | WHERE t.site_id = ? AND t.album IN (${placeholders})
|
|---|
| 655 | ORDER BY t.position ASC, t.created_at ASC
|
|---|
| 656 | `).all(site.id, ...albumNames);
|
|---|
| 657 | const byAlbum = new Map();
|
|---|
| 658 | for (const r of albumRows) {
|
|---|
| [834bcc3] | 659 | // Link-only tracks (no file) remain in the album overview (url '').
|
|---|
| [7bc636b] | 660 | if (!byAlbum.has(r.album)) byAlbum.set(r.album, []);
|
|---|
| 661 | byAlbum.get(r.album).push({
|
|---|
| [359b9ae] | 662 | id: r.id,
|
|---|
| [d727e92] | 663 | url: r.filename ? audioUrl(r.filename) : '',
|
|---|
| [7bc636b] | 664 | title: r.title || 'Untitled',
|
|---|
| 665 | artist: r.artist || '',
|
|---|
| 666 | cover: r.cover_url || '',
|
|---|
| [183875b] | 667 | link_spotify: r.link_spotify || '',
|
|---|
| 668 | link_youtube: r.link_youtube || '',
|
|---|
| 669 | link_soundcloud: r.link_soundcloud || '',
|
|---|
| [7bc636b] | 670 | });
|
|---|
| 671 | }
|
|---|
| 672 | html = AudioEmbedService.embedAlbumShortcodes(html, (name) => {
|
|---|
| 673 | const tracks = byAlbum.get(name);
|
|---|
| 674 | if (!tracks || !tracks.length) return null;
|
|---|
| 675 | return {
|
|---|
| 676 | title: name,
|
|---|
| 677 | artist: tracks[0].artist || '',
|
|---|
| 678 | cover: tracks[0].cover || '',
|
|---|
| 679 | tracks,
|
|---|
| 680 | };
|
|---|
| 681 | });
|
|---|
| 682 | }
|
|---|
| 683 |
|
|---|
| 684 | // Playlist shortcodes: [[playlist:some-slug-id]] — first-class entity.
|
|---|
| 685 | // Editing the playlist propagates to every post that embeds it.
|
|---|
| 686 | const playlistIds = [...html.matchAll(/\[\[playlist:([a-z0-9][a-z0-9-]*)\]\]/gi)]
|
|---|
| 687 | .map(m => m[1].toLowerCase());
|
|---|
| 688 | if (playlistIds.length) {
|
|---|
| 689 | const isAdmin = req.session?.user?.role === 'god';
|
|---|
| 690 | html = AudioEmbedService.embedPlaylistShortcodes(html, (id) => {
|
|---|
| [21522ae] | 691 | return PlaylistService.get(site.id, id, audioUrl);
|
|---|
| [7bc636b] | 692 | }, { isAdmin });
|
|---|
| 693 | }
|
|---|
| 694 | }
|
|---|
| [cb01666] | 695 | } else {
|
|---|
| [834bcc3] | 696 | // LITE mode (KLONKT_AUDIO=off): no own audio (no ffmpeg/stream route).
|
|---|
| 697 | // External embeds (YouTube/SoundCloud/Spotify) remain; the own-audio
|
|---|
| 698 | // shortcodes ([[track]]/[[album]]/[[playlist]]) are cleanly stripped.
|
|---|
| [cb01666] | 699 | html = AudioEmbedService.autoembed(html);
|
|---|
| 700 | html = AudioEmbedService.embedMediaShortcodes(html);
|
|---|
| 701 | html = AudioEmbedService.embedExternalLinkShortcodes(html);
|
|---|
| 702 | html = html.replace(/\[\[(track|album|playlist):[^\]]+\]\]/gi, '');
|
|---|
| 703 | }
|
|---|
| [7bc636b] | 704 | post.content_html = html;
|
|---|
| 705 |
|
|---|
| 706 | if (post.tags) {
|
|---|
| 707 | try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
|
|---|
| 708 | } else {
|
|---|
| 709 | post.tags = [];
|
|---|
| 710 | }
|
|---|
| 711 |
|
|---|
| [59f0170] | 712 | // Native comments removed: social interaction is fediverse-only (see the
|
|---|
| 713 | // "From the fediverse" section below).
|
|---|
| [7bc636b] | 714 |
|
|---|
| 715 | // Prev / next chronological (kept for back-compat — "post-nav" feature
|
|---|
| 716 | // below the article still uses these as a simple linear navigation).
|
|---|
| [834bcc3] | 717 | // Hub mode: Related posts + Newer/Older pull from ALL users (all sites),
|
|---|
| 718 | // newest first. Solo mode: within the current site (old behaviour).
|
|---|
| [d54dade] | 719 | const isHub = res.locals.tenancy === 'hub';
|
|---|
| [834bcc3] | 720 | // Per-post URL base: in hub a link points to /user/<site-slug>/<post-slug>.
|
|---|
| [d54dade] | 721 | const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
|
|---|
| 722 |
|
|---|
| [834bcc3] | 723 | // Newer/Older across ALL posts (shared helper — also used by the fan gate).
|
|---|
| [1e2e9e7] | 724 | const { newerPost, olderPost } = postNeighbors(site, post, isHub);
|
|---|
| [7bc636b] | 725 |
|
|---|
| 726 | // ── Related posts: same-tag matching with recency fallback ─────
|
|---|
| 727 | // Fetch ~50 candidates, score by tag overlap, take top 3.
|
|---|
| 728 | // Excluding self via `id != ?`.
|
|---|
| [d54dade] | 729 | const candidates = isHub
|
|---|
| 730 | ? db.prepare(`
|
|---|
| 731 | SELECT p.id, p.slug, p.title, p.cover_image_url, p.published_at, p.tags, s.slug AS site_slug
|
|---|
| 732 | FROM posts p JOIN sites s ON s.id = p.site_id
|
|---|
| 733 | WHERE p.status = 'published' AND p.id != ?
|
|---|
| 734 | ORDER BY p.published_at DESC LIMIT 50
|
|---|
| 735 | `).all(post.id)
|
|---|
| 736 | : db.prepare(`
|
|---|
| 737 | SELECT id, slug, title, cover_image_url, published_at, tags
|
|---|
| 738 | FROM posts
|
|---|
| 739 | WHERE site_id = ? AND status = 'published' AND id != ?
|
|---|
| 740 | ORDER BY published_at DESC LIMIT 50
|
|---|
| 741 | `).all(site.id, post.id);
|
|---|
| [7bc636b] | 742 |
|
|---|
| 743 | // Parse tags JSON safely; missing/malformed → empty array.
|
|---|
| 744 | const parseTags = (raw) => {
|
|---|
| 745 | if (!raw) return [];
|
|---|
| 746 | try {
|
|---|
| 747 | const v = JSON.parse(raw);
|
|---|
| 748 | return Array.isArray(v) ? v.map(String) : [];
|
|---|
| 749 | } catch { return []; }
|
|---|
| 750 | };
|
|---|
| 751 |
|
|---|
| 752 | const myTags = new Set(parseTags(post.tags));
|
|---|
| 753 | let relatedPosts;
|
|---|
| 754 | if (myTags.size > 0) {
|
|---|
| 755 | // Score = number of overlapping tags. Posts with zero overlap are
|
|---|
| 756 | // included only if we don't have 3 with-overlap candidates.
|
|---|
| 757 | const scored = candidates.map(p => {
|
|---|
| 758 | const theirTags = parseTags(p.tags);
|
|---|
| 759 | const overlap = theirTags.reduce((n, t) => n + (myTags.has(t) ? 1 : 0), 0);
|
|---|
| 760 | return { ...p, _overlap: overlap };
|
|---|
| 761 | });
|
|---|
| 762 | const withOverlap = scored.filter(p => p._overlap > 0)
|
|---|
| 763 | .sort((a, b) => b._overlap - a._overlap || new Date(b.published_at) - new Date(a.published_at));
|
|---|
| 764 | if (withOverlap.length >= 3) {
|
|---|
| 765 | relatedPosts = withOverlap.slice(0, 3);
|
|---|
| 766 | } else {
|
|---|
| 767 | // Pad with most-recent non-overlap posts so the section is never empty
|
|---|
| 768 | const overlapIds = new Set(withOverlap.map(p => p.id));
|
|---|
| 769 | const filler = candidates.filter(p => !overlapIds.has(p.id));
|
|---|
| 770 | relatedPosts = [...withOverlap, ...filler].slice(0, 3);
|
|---|
| 771 | }
|
|---|
| 772 | } else {
|
|---|
| 773 | // No tags on current post → just show 3 most-recent
|
|---|
| 774 | relatedPosts = candidates.slice(0, 3);
|
|---|
| 775 | }
|
|---|
| 776 | // Strip the internal _overlap field before sending to view
|
|---|
| [d54dade] | 777 | relatedPosts = relatedPosts.map(({ _overlap, tags, ...rest }) => ({ ...rest, _urlBase: urlBaseFor(rest) }));
|
|---|
| [7bc636b] | 778 |
|
|---|
| [834bcc3] | 779 | // Likes / favourites: count + whether the logged-in user liked this post.
|
|---|
| [535f955] | 780 | const likeCount = db.prepare('SELECT COUNT(*) AS c FROM post_likes WHERE post_id = ?').get(post.id).c;
|
|---|
| 781 | const likedByMe = !!(req.session?.user &&
|
|---|
| 782 | db.prepare('SELECT 1 FROM post_likes WHERE post_id = ? AND user_id = ?').get(post.id, req.session.user.id));
|
|---|
| 783 |
|
|---|
| [7d932ce] | 784 | // Inbound fediverse activity (threaded) for this post.
|
|---|
| 785 | let fediverse = { thread: [], likeCount: 0, announceCount: 0, total: 0 };
|
|---|
| 786 | try {
|
|---|
| 787 | const _apBase = (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
|
|---|
| [c73ac64] | 788 | fediverse = ActivityPubService.getInteractions(post.id, _apBase, site);
|
|---|
| [7d932ce] | 789 | } catch { /* non-fatal */ }
|
|---|
| [55bc7f9] | 790 | // Owner/admin of this site may reply back to a fediverse interaction.
|
|---|
| 791 | const canManageSite = !!(req.session?.user && PermissionsService.canAdminSite(req.session.user, site));
|
|---|
| [52ea6df] | 792 | // Avatar for our own (outbound) fediverse replies = the site's profile photo.
|
|---|
| 793 | const siteAvatar = (site && site.profile_photo) ? site.profile_photo : null;
|
|---|
| [c16e0a5] | 794 |
|
|---|
| [7bc636b] | 795 | renderPage(req, res, 'pages/post', {
|
|---|
| 796 | post,
|
|---|
| [6117035] | 797 | newerPost,
|
|---|
| 798 | olderPost,
|
|---|
| [7bc636b] | 799 | relatedPosts,
|
|---|
| [c16e0a5] | 800 | fediverse,
|
|---|
| [55bc7f9] | 801 | canManageSite,
|
|---|
| [52ea6df] | 802 | siteAvatar,
|
|---|
| [535f955] | 803 | likeCount,
|
|---|
| 804 | likedByMe,
|
|---|
| [7bc636b] | 805 | pageTitle: post.title + ' - ' + site.title,
|
|---|
| 806 | socialDescr: post.excerpt || '',
|
|---|
| 807 | socialImage: post.cover_image_url || '',
|
|---|
| 808 | bodyClass: 'on-post',
|
|---|
| 809 | });
|
|---|
| 810 | });
|
|---|
| 811 |
|
|---|
| [55bc7f9] | 812 | // ── Reply back to a fediverse interaction (site owner/admin only) ──
|
|---|
| 813 | router.post('/posts/:slug/fedi-reply', requireSiteManager, async (req, res) => {
|
|---|
| 814 | const site = res.locals.site;
|
|---|
| 815 | if (!site) return res.status(404).send('Site required');
|
|---|
| 816 | const post = db.prepare('SELECT id, slug FROM posts WHERE site_id = ? AND slug = ?').get(site.id, req.params.slug);
|
|---|
| 817 | if (!post) return res.status(404).send('Not found');
|
|---|
| 818 | const parent = ActivityPubService.getInteractionById(req.body.interaction_id);
|
|---|
| 819 | const text = (req.body.text || '').toString();
|
|---|
| 820 | if (parent && parent.post_id === post.id && text.trim()) {
|
|---|
| 821 | try {
|
|---|
| 822 | await ActivityPubService.deliverReply(site, { postId: post.id, postSlug: post.slug, parent, text });
|
|---|
| 823 | } catch (e) { console.warn('[AP] reply send failed:', e.message); }
|
|---|
| 824 | }
|
|---|
| 825 | res.redirect(`${res.locals.siteUrlBase || ''}/${post.slug}#fediverse`);
|
|---|
| 826 | });
|
|---|
| 827 |
|
|---|
| [7bc636b] | 828 | export default router;
|
|---|
| [d8c6a83] | 829 | export { postNeighbors };
|
|---|