source: Klonkt/src/routes/posts.js@ 2d6a9c3

main
Last change on this file since 2d6a9c3 was 2d6a9c3, checked in by Robin <roboburr@…>, 8 weeks ago

Spoor A step 1: bake post display HTML at save (ActivityPub source model)

Introduce the source/rendered split: posts.content stays the raw source (what
the editor round-trips), a new content_rendered column holds the baked display
HTML. bakePostContent() runs the linkify pipeline once at create/edit and
caches it; the render route serves content_rendered (falling back to an
on-the-fly bake for not-yet-baked posts) and no longer re-linkifies every view.
Verified: baked and fallback paths render byte-identically and a baked lone URL
still becomes an embed. This is the seam for step 2 (resolve @mentions once at
save instead of per page view) and removes the per-render linkify cost.

Co-Authored-By: Claude Opus 4.8 <noreply@…>

  • Property mode set to 100644
File size: 60.2 KB
Line 
1import express from 'express';
2import { v4 as uuid } from 'uuid';
3import path from 'path';
4import fs from 'fs';
5import { fileURLToPath } from 'url';
6import multer from 'multer';
7import ejs from 'ejs';
8import db from '../config/database.js';
9import { requireAuth, requireSiteManager, isViewer } from '../middleware/auth.js';
10import { renderPage } from '../middleware/render.js';
11import { recordPageview, recordPostView } from '../services/StatsService.js';
12import PermissionsService from '../services/PermissionsService.js';
13import MarkdownService from '../services/MarkdownService.js';
14import HtmlSanitizerService from '../services/HtmlSanitizerService.js';
15import AudioEmbedService from '../services/AudioEmbedService.js';
16import PlaylistService from '../services/PlaylistService.js';
17import { audioEnabled } from '../config/features.js';
18import { audioUrl } from '../services/AudioStreamService.js';
19import { toWebp } from '../services/ImageWebpService.js';
20import VideoCoverService from '../services/VideoCoverService.js';
21import ActivityPubService from '../services/ActivityPubService.js';
22import MusicMeta from '../services/MusicMeta.js';
23
24const __dirname = path.dirname(fileURLToPath(import.meta.url));
25const POST_IMAGES_DIR = path.resolve(
26 process.env.POST_IMAGES_PATH ||
27 path.join(__dirname, '..', '..', 'storage', 'media', 'post-images')
28);
29fs.mkdirSync(POST_IMAGES_DIR, { recursive: true });
30
31const ALLOWED_IMAGE_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
32const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
33
34const imageStorage = multer.diskStorage({
35 destination: (req, file, cb) => cb(null, POST_IMAGES_DIR),
36 filename: (req, file, cb) => {
37 const ext = path.extname(file.originalname).toLowerCase();
38 cb(null, `${uuid()}${ext}`);
39 },
40});
41const imageUpload = multer({
42 storage: imageStorage,
43 limits: { fileSize: MAX_IMAGE_BYTES },
44 fileFilter: (req, file, cb) => {
45 const ext = path.extname(file.originalname).toLowerCase();
46 if (!ALLOWED_IMAGE_EXT.has(ext)) {
47 return cb(new Error('Image must be jpg/png/webp/gif'));
48 }
49 cb(null, true);
50 },
51});
52
53// Generates a unique slug within the site: 'title', 'title-2', 'title-3', …
54// A second post with the same title is NOT rejected ("already exists"),
55// but automatically gets a free suffix. exceptId = the post being updated
56// (allowed to keep its own slug).
57function uniqueSlug(siteId, base, exceptId = null) {
58 let candidate = base;
59 let n = 2;
60 for (;;) {
61 const row = exceptId
62 ? db.prepare('SELECT id FROM posts WHERE site_id = ? AND slug = ? AND id != ?').get(siteId, candidate, exceptId)
63 : db.prepare('SELECT id FROM posts WHERE site_id = ? AND slug = ?').get(siteId, candidate);
64 if (!row) return candidate;
65 candidate = `${base}-${n++}`;
66 }
67}
68
69const router = express.Router();
70
71// ==================== UPLOAD IMAGE (cover or content) ====================
72// Returns JSON {url} so the editor can stick it into the cover field or
73// insert a markdown ![](url) into content.
74router.post('/posts/upload-image', requireAuth, (req, res) => {
75 imageUpload.single('image')(req, res, async (err) => {
76 if (err) return res.status(400).json({ error: err.message });
77 if (!req.file) return res.status(400).json({ error: 'No file' });
78 const name = toWebp(req.file);
79 const url = '/media/post-images/' + name;
80 // An animated WebP cover → also make a muted loop MP4 (Safari plays it smoothly where the
81 // animated WebP is janky on iOS). Best-effort; on failure we just return the still image.
82 // The editor stores `video` in the hidden cover_video_url field for the cover.
83 let video = null;
84 try {
85 const src = path.join(POST_IMAGES_DIR, name);
86 if (VideoCoverService.isAnimatedWebp(src)) {
87 const r = await VideoCoverService.animatedWebpToVideo(src, POST_IMAGES_DIR, path.basename(name, path.extname(name)) + '-v');
88 if (r) video = '/media/post-images/' + path.basename(r.videoPath);
89 }
90 } catch { /* keep the still image */ }
91 res.json({ url, video, size: req.file.size, mime: req.file.mimetype });
92 });
93});
94
95const RESERVED_SLUGS = new Set([
96 'auth', 'admin', 'login', 'register', 'logout',
97 'archive', 'search', 'account', 'sites', 'comments',
98 'posts', 'media', 'audio', 'forum',
99 'tag', 'type', 'user', 'users', 'artiesten', 'leden', 'favorieten', 'feed.xml', 'atom.xml', 'sitemap.xml',
100 'manifest.webmanifest', 'sw.js', 'favicon.ico', 'favicon.svg', 'assets',
101 'authorize_interaction', 'fediverse', 'news', 'following', 'notifications', 'blocking',
102]);
103
104/**
105 * Parse the form's `pinned` field into a non-negative integer rank.
106 * Empty / undefined / NaN / negative → 0 (= not pinned).
107 * Otherwise: integer rank (1 = top of pinned stack, 2 = below, ...).
108 *
109 * Multiple posts CAN share the same rank — UI shows them tiebroken by
110 * published_at DESC. Saying #2 twice doesn't error, it just duplicates.
111 * (We don't enforce uniqueness at this layer because race conditions and
112 * "swap two ranks" workflows are easier without a UNIQUE constraint.)
113 */
114function parsePinnedRank(raw) {
115 const n = parseInt(raw, 10);
116 if (!Number.isFinite(n) || n < 0) return 0;
117 return n;
118}
119
120// Poll durations offered in the editor (seconds) — the Mastodon set (5m … 7d).
121const POLL_DURATIONS = new Set([300, 1800, 3600, 21600, 43200, 86400, 259200, 604800]);
122// Parse the editor's poll fields into the poll_json we store on the post (which
123// buildNote federates as an AS2 Question). Returns null when no valid poll (< 2
124// options or the poll checkbox is off). endTime is set from the chosen duration
125// (default 1 day) so the Scheduler can close it.
126function parsePollForm(body) {
127 if (!body || !body.poll_enabled) return null;
128 const raw = body.poll_option == null ? [] : (Array.isArray(body.poll_option) ? body.poll_option : [body.poll_option]);
129 const options = [];
130 const seen = new Set();
131 for (const o of raw) {
132 const name = String(o == null ? '' : o).trim().slice(0, 100);
133 if (!name) continue;
134 const key = name.toLowerCase();
135 if (seen.has(key)) continue; seen.add(key);
136 options.push({ name });
137 if (options.length >= 8) break;
138 }
139 if (options.length < 2) return null;
140 const dur = parseInt(body.poll_duration, 10);
141 const secs = POLL_DURATIONS.has(dur) ? dur : 86400;
142 return JSON.stringify({ multiple: !!body.poll_multiple, options, endTime: new Date(Date.now() + secs * 1000).toISOString(), closed: false });
143}
144
145// ==================== HOME (Posts list) ====================
146router.get('/', (req, res) => {
147 const site = res.locals.site;
148
149 if (!site) {
150 return renderPage(req, res, 'pages/welcome', {
151 pageTitle: 'Welcome',
152 bodyClass: 'on-special',
153 });
154 }
155
156 // Pinned first — ordered by their rank (1 = top, 2 = below, etc).
157 // pinned column is now an integer rank: 0 = not pinned, 1+ = pinned at
158 // that position. Older boolean usage where pinned was always 1 still
159 // works because integer ranks 1, 2, 3 sort the same as a flat 1.
160 const pinnedPosts = db.prepare(`
161 SELECT p.*, u.username as author_username
162 FROM posts p JOIN users u ON p.author_id = u.id
163 WHERE p.site_id = ? AND p.status = 'published' AND p.pinned > 0
164 ORDER BY p.pinned ASC, p.published_at DESC
165 `).all(site.id);
166
167 // Regular posts: anything with pinned = 0
168 const posts = db.prepare(`
169 SELECT p.*, u.username as author_username
170 FROM posts p JOIN users u ON p.author_id = u.id
171 WHERE p.site_id = ? AND p.status = 'published' AND p.pinned = 0
172 ORDER BY p.published_at DESC
173 LIMIT 30
174 `).all(site.id);
175
176 recordPageview(site.id, req);
177
178 renderPage(req, res, 'pages/home', {
179 pinnedPosts,
180 posts,
181 pageTitle: site.title,
182 socialDescr: site.description || site.tagline || '',
183 bodyClass: 'on-home',
184 });
185});
186
187// ==================== NEW POST FORM ====================
188router.get('/posts/new', requireAuth, (req, res) => {
189 const site = res.locals.site;
190 if (!site) return res.status(404).send('Site required');
191 if (!PermissionsService.canCreatePost(req.session.user, site)) {
192 return res.status(403).send('No permission');
193 }
194
195 renderPage(req, res, 'pages/post-edit', {
196 post: {
197 id: uuid(),
198 title: '', slug: '', content: '', excerpt: '',
199 status: 'draft', pinned: 0, tags: [],
200 cover_image_url: '',
201 },
202 isNew: true,
203 pageTitle: 'New post',
204 bodyClass: 'on-special',
205 });
206});
207
208// ==================== CREATE POST ====================
209// ── Per-post audio federation ──────────────────────────────────────────────
210// "Share audio on the fediverse" is a per-post choice in the editor, but the underlying
211// flag is per track (audio_tracks.fedi_open — it gates the file + drives the AS2 Audio
212// attachment). NB: the file gate is per file, so opening a track in one post makes its file
213// fetchable for every post that reuses it.
214// ONE-WAY: opening is permanent. Once the file has federated it's out there — re-gating
215// would be false security (remote copies keep the URL), so we never write fedi_open back to 0.
216function setAudioFediOpen(siteId, content, open) {
217 if (!open) return; // never close — see one-way note above
218 const c = content || '';
219 try {
220 for (const m of c.matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)) db.prepare('UPDATE audio_tracks SET fedi_open = 1 WHERE id = ? AND site_id = ?').run(m[1], siteId);
221 for (const m of c.matchAll(/\[\[album:([^\]]+)\]\]/g)) db.prepare('UPDATE audio_tracks SET fedi_open = 1 WHERE site_id = ? AND album = ?').run(siteId, m[1].trim());
222 for (const m of c.matchAll(/\[\[playlist:([A-Za-z0-9_-]+)\]\]/g)) db.prepare('UPDATE audio_tracks SET fedi_open = 1 WHERE id IN (SELECT track_id FROM playlist_tracks WHERE playlist_id = ?)').run(m[1]);
223 } catch { /* non-fatal */ }
224}
225// True when the post references hosted audio AND all of it is currently fedi_open (drives the
226// editor checkbox's initial state).
227function postAudioFediOpen(siteId, content) {
228 const c = content || '';
229 if (!/\[\[(track|album|playlist):/i.test(c)) return false;
230 let total = 0, open = 0;
231 const tally = (r) => { if (r && r.media_id) { total++; if (r.fedi_open) open++; } };
232 try {
233 for (const m of c.matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)) tally(db.prepare('SELECT fedi_open, media_id FROM audio_tracks WHERE id = ? AND site_id = ?').get(m[1], siteId));
234 for (const m of c.matchAll(/\[\[album:([^\]]+)\]\]/g)) for (const r of db.prepare('SELECT fedi_open, media_id FROM audio_tracks WHERE site_id = ? AND album = ? AND media_id IS NOT NULL').all(siteId, m[1].trim())) tally(r);
235 for (const m of c.matchAll(/\[\[playlist:([A-Za-z0-9_-]+)\]\]/g)) for (const r of db.prepare('SELECT t.fedi_open, t.media_id FROM playlist_tracks pt JOIN audio_tracks t ON t.id = pt.track_id WHERE pt.playlist_id = ? AND t.media_id IS NOT NULL').all(m[1])) tally(r);
236 } catch { /* non-fatal */ }
237 return total > 0 && open === total;
238}
239
240// Bake + cache a post's display HTML (ActivityPub `source` model): `content` stays the raw
241// source (used by the editor + re-rendering), content_rendered holds the linkified render the
242// page serves. Called after every create/edit. Non-fatal: the render route falls back to
243// baking on the fly if this ever fails.
244function cacheRenderedContent(postId, rawContent) {
245 try {
246 db.prepare('UPDATE posts SET content_rendered = ? WHERE id = ?')
247 .run(ActivityPubService.bakePostContent(rawContent || ''), postId);
248 } catch (e) { /* fallback bake in the render route keeps display correct */ }
249}
250
251router.post('/posts/create', requireAuth, (req, res) => {
252 const site = res.locals.site;
253 if (!site || !PermissionsService.canCreatePost(req.session.user, site)) {
254 return res.status(403).send('No permission');
255 }
256
257 const { title, slug, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
258 const fanOnly = req.body.fan_only ? 1 : 0;
259 const nsfw = req.body.nsfw ? 1 : 0;
260 const cw = (req.body.content_warning || '').trim().slice(0, 200);
261 const coverAlt = (req.body.cover_alt || '').trim().slice(0, 1500) || null; // cover alt text (a11y)
262 const language = /^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(req.body.language || '') ? req.body.language : (res.locals.lang || null); // BCP-47 content language
263
264 // Content arrives as user-authored HTML from the WYSIWYG editor — sanitize
265 // before storage. Shortcode text tokens like [[track:UUID]] live in text
266 // nodes and pass through untouched.
267 const cleanContent = HtmlSanitizerService.sanitize(content || '');
268
269 // Generate slug from title if empty
270 let finalSlug = (slug || title || '')
271 .toLowerCase()
272 .replace(/[^a-z0-9]+/g, '-')
273 .replace(/^-|-$/g, '');
274
275 if (!finalSlug) return res.status(400).send('Title or slug required');
276 if (RESERVED_SLUGS.has(finalSlug)) finalSlug = `${finalSlug}-post`;
277
278 // Duplicate title/slug? Make it unique automatically (title-2, title-3, …) instead of rejecting.
279 finalSlug = uniqueSlug(site.id, finalSlug);
280
281 const validTypes = new Set(['post', 'foto', 'video', 'audio']);
282 const finalType = validTypes.has(type) ? type : 'post';
283 const pollJson = parsePollForm(req.body); // AS2 Question definition, or null
284 const postId = uuid();
285 const now = new Date().toISOString();
286 let finalStatus = status || 'draft';
287 let publishedAt = finalStatus === 'published' ? now : null;
288 // Release planning: published + a future publish_at -> 'scheduled'
289 // (the Scheduler makes it live at that moment). Past/empty -> live immediately.
290 let publishAt = null;
291 const pa = Date.parse(req.body.publish_at || '');
292 if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
293 finalStatus = 'scheduled';
294 publishAt = new Date(pa).toISOString();
295 publishedAt = null;
296 }
297
298 db.prepare(`
299 INSERT INTO posts (
300 id, site_id, slug, author_id, title, content, excerpt,
301 status, cover_image_url, cover_video_url, cover_alt, language, pinned, tags, type, noindex, fan_only, nsfw, content_warning, poll_json, publish_at,
302 created_at, updated_at, published_at
303 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
304 `).run(
305 postId, site.id, finalSlug, req.session.user.id,
306 title || finalSlug, cleanContent, excerpt || '',
307 finalStatus, cover_image_url || null, (req.body.cover_video_url || null), coverAlt, language, parsePinnedRank(pinned),
308 JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
309 finalType, noindex ? 1 : 0, fanOnly, nsfw, cw, pollJson, publishAt,
310 now, now, publishedAt
311 );
312 cacheRenderedContent(postId, cleanContent); // bake display HTML (ActivityPub `source` model)
313
314 // Per-post "share audio on the fediverse" → set fedi_open on this post's hosted tracks
315 // BEFORE federating, so the Create note carries the right Audio attachments.
316 setAudioFediOpen(site.id, cleanContent, req.body.fedi_open_audio);
317
318 if (finalStatus === 'published') {
319 try {
320 db.prepare(
321 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
322 ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, postId);
323 } catch (e) { /* FTS index issues are non-fatal */ }
324
325 // ActivityPub: federate a freshly published post to followers. fan_only → delivered
326 // to followers but addressed followers-only (option A: "fans" = your fedi followers).
327 if (status === 'published') {
328 ActivityPubService.deliverCreate(site, {
329 id: postId, slug: finalSlug, title: title || finalSlug,
330 content: cleanContent, cover_image_url: cover_image_url || null, cover_video_url: req.body.cover_video_url || null, cover_alt: coverAlt, language,
331 published_at: publishedAt, created_at: now, fan_only: fanOnly, nsfw, content_warning: cw, poll_json: pollJson,
332 }).catch(() => { /* best-effort */ });
333 }
334 }
335
336 // HTMX request -> return redirect header
337 if (req.headers['hx-request']) {
338 res.setHeader('HX-Redirect', `${res.locals.siteUrlBase || ''}/${finalSlug}`);
339 return res.send('OK');
340 }
341
342 res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
343});
344
345// ==================== EDIT POST FORM ====================
346router.get('/posts/:slug/edit', requireAuth, (req, res) => {
347 const site = res.locals.site;
348 if (!site) return res.status(404).send('Site required');
349
350 const post = db.prepare(
351 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
352 ).get(site.id, req.params.slug);
353
354 if (!post) return res.status(404).send('Post not found');
355 if (!PermissionsService.canEditPost(req.session.user, post, site)) {
356 return res.status(403).send('No permission');
357 }
358
359 if (post.tags) {
360 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
361 } else {
362 post.tags = [];
363 }
364
365 // A poll with votes is frozen (options can't change) — flag it so the editor disables the poll fields.
366 let pollLocked = false;
367 try { pollLocked = !!(post.poll_json && db.prepare('SELECT 1 FROM poll_votes WHERE post_id = ? LIMIT 1').get(post.id)); } catch { /* ignore */ }
368
369 renderPage(req, res, 'pages/post-edit', {
370 post,
371 isNew: false,
372 pollLocked,
373 fediOpenAudio: postAudioFediOpen(site.id, post.content),
374 pageTitle: 'Edit: ' + (post.title || 'Untitled'),
375 bodyClass: 'on-special',
376 });
377});
378
379// ==================== SAVE POST ====================
380router.post('/posts/:slug/save', requireAuth, (req, res) => {
381 const site = res.locals.site;
382 if (!site) return res.status(404).send('Site required');
383
384 const post = db.prepare(
385 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
386 ).get(site.id, req.params.slug);
387
388 if (!post) return res.status(404).send('Post not found');
389 if (!PermissionsService.canEditPost(req.session.user, post, site)) {
390 return res.status(403).send('No permission');
391 }
392
393 const { title, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
394 const fanOnly = req.body.fan_only ? 1 : 0;
395 const nsfw = req.body.nsfw ? 1 : 0;
396 const cw = (req.body.content_warning || '').trim().slice(0, 200);
397 const coverAlt = (req.body.cover_alt || '').trim().slice(0, 1500) || null; // cover alt text (a11y)
398 const language = /^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(req.body.language || '') ? req.body.language : (res.locals.lang || null); // BCP-47 content language
399 const newSlug = req.body.slug;
400 const action = req.body.action || 'save';
401 const validTypes = new Set(['post', 'foto', 'video', 'audio']);
402 const finalType = validTypes.has(type) ? type : (post.type || 'post');
403
404 // A poll that has already received votes is frozen (you can still edit the surrounding
405 // post, but not the options) — changing options after votes would scramble the tally and
406 // is disallowed on the fediverse too. Otherwise re-parse the poll form (add/remove/disable).
407 const hasVotes = !!(post.poll_json && (() => { try { return db.prepare('SELECT 1 FROM poll_votes WHERE post_id = ? LIMIT 1').get(post.id); } catch { return false; } })());
408 const pollJson = hasVotes ? post.poll_json : parsePollForm(req.body);
409
410 // Sanitize before storage — same pipeline as create.
411 const cleanContent = HtmlSanitizerService.sanitize(content || '');
412
413 let finalSlug = post.slug;
414 if (newSlug && newSlug !== post.slug) {
415 const cleaned = newSlug.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
416 const safe = RESERVED_SLUGS.has(cleaned) ? `${cleaned}-post` : cleaned;
417 // Duplicate slug? Make it unique automatically instead of rejecting (own post may keep its slug).
418 finalSlug = uniqueSlug(site.id, safe, post.id);
419 }
420
421 const now = new Date().toISOString();
422 let finalStatus = status || post.status;
423 let publishedAt = post.published_at;
424
425 if (action === 'publish') {
426 finalStatus = 'published';
427 if (!publishedAt) publishedAt = now;
428 }
429
430 // Release planning: published + future publish_at -> 'scheduled'.
431 let publishAt = null;
432 const pa = Date.parse(req.body.publish_at || '');
433 if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
434 finalStatus = 'scheduled';
435 publishAt = new Date(pa).toISOString();
436 publishedAt = null;
437 }
438
439 db.prepare(`
440 UPDATE posts SET
441 title = ?, content = ?, excerpt = ?, status = ?,
442 cover_image_url = ?, cover_video_url = ?, cover_alt = ?, language = ?, pinned = ?, tags = ?,
443 type = ?, noindex = ?, fan_only = ?, nsfw = ?, content_warning = ?, poll_json = ?, publish_at = ?,
444 slug = ?, published_at = ?, updated_at = ?
445 WHERE id = ?
446 `).run(
447 title, cleanContent, excerpt, finalStatus,
448 cover_image_url || null, (req.body.cover_video_url || null), coverAlt, language, parsePinnedRank(pinned),
449 JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
450 finalType, noindex ? 1 : 0, fanOnly, nsfw, cw, pollJson, publishAt,
451 finalSlug, publishedAt, now, post.id
452 );
453 cacheRenderedContent(post.id, cleanContent); // re-bake display HTML on edit (ActivityPub `source` model)
454
455 // Per-post "share audio on the fediverse" → set fedi_open on this post's hosted tracks
456 // BEFORE federating, so the Update/Create note carries the right Audio attachments.
457 setAudioFediOpen(site.id, cleanContent, req.body.fedi_open_audio);
458
459 // Update FTS
460 try {
461 db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id);
462 if (finalStatus === 'published') {
463 db.prepare(
464 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
465 ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, post.id);
466 }
467 } catch (e) { /* FTS issues non-fatal */ }
468
469 // ActivityPub: federate edits to followers. A post that BECOMES published →
470 // Create (new post); an already-published post that's edited → Update (so
471 // Mastodon refreshes its cached copy). fan_only → followers-only (option A).
472 if (finalStatus === 'published') {
473 const apPost = {
474 id: post.id, slug: finalSlug, title: title || finalSlug,
475 content: cleanContent, cover_image_url: cover_image_url || null, cover_video_url: req.body.cover_video_url || null, cover_alt: coverAlt, language,
476 published_at: publishedAt, created_at: post.created_at, fan_only: fanOnly, nsfw, content_warning: cw, poll_json: pollJson,
477 };
478 if (post.status !== 'published') ActivityPubService.deliverCreate(site, apPost).catch(() => { /* best-effort */ });
479 else ActivityPubService.deliverUpdate(site, apPost).catch(() => { /* best-effort */ });
480 }
481
482 // Pin/unpin/reorder → push Add/Remove activities so followers' instances update the
483 // pinned order immediately (reliable, unlike re-fetching the cached featured collection).
484 if ((post.pinned || 0) !== parsePinnedRank(pinned)) {
485 const unpinned = (post.pinned || 0) > 0 && parsePinnedRank(pinned) === 0 ? [post.id] : [];
486 ActivityPubService.resyncFeaturedPins(site, unpinned).catch(() => { /* best-effort */ });
487 }
488
489 res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
490});
491
492// ==================== DELETE POST ====================
493router.post('/posts/:slug/delete', requireAuth, (req, res) => {
494 const site = res.locals.site;
495 if (!site) return res.status(404).send('Site required');
496
497 const post = db.prepare(
498 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
499 ).get(site.id, req.params.slug);
500
501 if (!post) return res.status(404).send('Not found');
502 if (!PermissionsService.canDeletePost(req.session.user, post, site)) {
503 return res.status(403).send('No permission');
504 }
505
506 // ActivityPub: tell followers the post is gone (Delete + Tombstone) if it was
507 // federated (any published post now federates — fan_only goes followers-only).
508 // Fire before the row is removed — we still have post.id (= the Note id).
509 if (post.status === 'published') {
510 ActivityPubService.deliverDelete(site, post).catch(() => { /* best-effort */ });
511 }
512
513 // Cascade: comments + FTS row, THEN the post itself.
514 // FK constraints are ON (config/database.js), so a bare DELETE on posts
515 // fails when comments still reference it.
516 const cascade = db.transaction(() => {
517 db.prepare('DELETE FROM comments WHERE post_id = ?').run(post.id);
518 try { db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id); } catch {}
519 db.prepare('DELETE FROM posts WHERE id = ?').run(post.id);
520 });
521 cascade();
522
523 if (req.headers['hx-request']) {
524 res.setHeader('HX-Redirect', res.locals.siteUrlBase || '/');
525 return res.send('OK');
526 }
527 res.redirect(res.locals.siteUrlBase || '/');
528});
529
530// ==================== ARCHIVE ====================
531router.get('/archive', (req, res) => {
532 const site = res.locals.site;
533 if (!site) return res.status(404).send('No site');
534
535 const posts = db.prepare(`
536 SELECT p.*, u.username as author_username
537 FROM posts p JOIN users u ON p.author_id = u.id
538 WHERE p.site_id = ? AND p.status = 'published'
539 ORDER BY p.published_at DESC
540 `).all(site.id);
541
542 // Group by year/month
543 const grouped = {};
544 for (const post of posts) {
545 if (!post.published_at) continue;
546 const d = new Date(post.published_at);
547 const year = d.getFullYear();
548 const month = d.getMonth();
549 const monthName = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'][month];
550
551 if (!grouped[year]) grouped[year] = {};
552 if (!grouped[year][monthName]) grouped[year][monthName] = [];
553 grouped[year][monthName].push(post);
554 }
555
556 renderPage(req, res, 'pages/archive', {
557 grouped,
558 totalPosts: posts.length,
559 pageTitle: 'Archive - ' + site.title,
560 bodyClass: 'on-archive',
561 });
562});
563
564// Local likes/favourites are removed — engagement is fediverse-only now
565// (the ⭐ on a post likes via the fediverse). No post_likes, no /favorieten.
566
567// Newer/Older neighbours across ALL posts in feed order. Shared by the full
568// post render and the fan gate (premium fan_only) so navigation is consistent
569// everywhere. Solo: within the site (pinned first, then date). Hub: globally by date.
570function postNeighbors(site, post, isHub) {
571 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
572 const ordered = isHub
573 ? db.prepare(`
574 SELECT p.id, p.slug, p.title, p.pinned, s.slug AS site_slug
575 FROM posts p JOIN sites s ON s.id = p.site_id
576 WHERE p.status = 'published'
577 ORDER BY p.published_at DESC
578 `).all()
579 : db.prepare(`
580 SELECT id, slug, title, pinned FROM posts
581 WHERE site_id = ? AND status = 'published'
582 ORDER BY (pinned = 0) ASC, pinned ASC, published_at DESC
583 `).all(site.id);
584 const idx = ordered.findIndex((p) => p.id === post.id);
585 const newerPost = idx > 0 ? ordered[idx - 1] : null;
586 const olderPost = (idx >= 0 && idx < ordered.length - 1) ? ordered[idx + 1] : null;
587 if (newerPost) newerPost._urlBase = urlBaseFor(newerPost);
588 if (olderPost) olderPost._urlBase = urlBaseFor(olderPost);
589 return { newerPost, olderPost };
590}
591
592// ==================== REMOTE INTERACTION (reply to a fediverse post as your site) ====================
593// Standard fediverse "reply from your own server" landing endpoint. A post page
594// elsewhere bounces the visitor here with ?uri=<remote post>; the site owner
595// composes a reply that federates back to that post.
596router.get('/authorize_interaction', requireSiteManager, async (req, res) => {
597 const site = res.locals.site;
598 const uri = (req.query.uri || '').toString();
599 const sent = !!req.query.sent;
600 const followed = !!req.query.followed;
601 const voted = !!req.query.voted;
602 const reported = !!req.query.reported;
603 let target = null, followTarget = null;
604 if (!sent && !followed && !voted && !reported && uri) {
605 try { target = await ActivityPubService.resolveRemoteNote(uri); } catch { /* ignore */ }
606 // Not a post? Maybe the URI is a profile/actor → offer Follow, not reply.
607 if (!target) { try { followTarget = await ActivityPubService.resolveRemoteActor(uri); } catch { /* ignore */ } }
608 }
609 renderPage(req, res, 'pages/authorize-interaction', {
610 pageTitle: 'Interacteer via de fediverse',
611 bodyClass: 'on-special',
612 uri,
613 target,
614 followTarget,
615 sent,
616 followed,
617 voted: !!req.query.voted,
618 reported: !!req.query.reported,
619 liked: !!req.query.liked,
620 boosted: !!req.query.boosted,
621 reacted: (site && uri) ? ActivityPubService.getMyReactions(site.slug, uri) : { liked: false, boosted: false },
622 siteTitle: site ? site.title : '',
623 });
624});
625
626// 📊 Vote on a remote fediverse poll from the interact page (any poll by URL, not just
627// followed ones). Casts the Mastodon-standard ballot straight to the poll's author.
628router.post('/authorize_interaction/vote', requireSiteManager, async (req, res) => {
629 const site = res.locals.site;
630 const uri = (req.body.uri || '').toString();
631 let choice = req.body.choice;
632 if (choice == null) choice = [];
633 if (!Array.isArray(choice)) choice = [choice];
634 if (site && uri && choice.length) { try { await ActivityPubService.voteOnRemotePoll(site, uri, choice.map(String)); } catch { /* ignore */ } }
635 res.redirect('/authorize_interaction?voted=1&uri=' + encodeURIComponent(uri));
636});
637
638// 🚩 Report a remote post/account to its home instance (sends an AS2 Flag).
639router.post('/authorize_interaction/report', requireSiteManager, async (req, res) => {
640 const site = res.locals.site;
641 const uri = (req.body.uri || '').toString();
642 const actorUri = (req.body.actor_uri || '').toString();
643 const reason = (req.body.reason || '').toString();
644 if (site && (uri || actorUri)) { try { await ActivityPubService.sendReport(site, { objectUri: uri, actorUri, reason }); } catch { /* ignore */ } }
645 res.redirect('/authorize_interaction?reported=1&uri=' + encodeURIComponent(uri || actorUri));
646});
647
648// ⭐ Like / unlike a remote post from your own site (toggle on the interact page).
649router.post('/authorize_interaction/like', requireSiteManager, (req, res) => {
650 const site = res.locals.site;
651 const uri = (req.body.uri || '').toString();
652 let on = false;
653 if (site && uri) {
654 on = !ActivityPubService.getMyReactions(site.slug, uri).liked;
655 ActivityPubService.resolveRemoteNote(uri)
656 .then((note) => note && ActivityPubService.sendInteraction(site, on ? 'like' : 'unlike', note.object_uri || uri, note.actor_uri))
657 .catch((e) => console.warn('[AP] remote like failed:', e.message));
658 ActivityPubService.setMyReaction(site.slug, uri, 'like', on);
659 }
660 if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
661 res.redirect('/authorize_interaction?uri=' + encodeURIComponent(uri));
662});
663
664// 🔁 Boost / unboost a remote post from your own site (toggle on the interact page).
665// Also flags it for the Cirkel (markBoosted is a no-op if the post isn't in your timeline).
666router.post('/authorize_interaction/boost', requireSiteManager, (req, res) => {
667 const site = res.locals.site;
668 const uri = (req.body.uri || '').toString();
669 let on = false;
670 if (site && uri) {
671 on = !ActivityPubService.getMyReactions(site.slug, uri).boosted;
672 ActivityPubService.resolveRemoteNote(uri)
673 .then((note) => {
674 if (!note) return;
675 const id = note.object_uri || uri;
676 return Promise.resolve(ActivityPubService.sendInteraction(site, on ? 'boost' : 'unboost', id, note.actor_uri))
677 // Boost → store the post in the timeline (even if you don't follow the author) so it
678 // surfaces in the Cirkel; unboost → just clear the flag.
679 .then(() => on ? ActivityPubService.upsertBoostedNote(site.slug, note) : ActivityPubService.unmarkBoosted(site.slug, id));
680 })
681 .catch((e) => console.warn('[AP] remote boost failed:', e.message));
682 ActivityPubService.setMyReaction(site.slug, uri, 'boost', on);
683 }
684 if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
685 res.redirect('/authorize_interaction?uri=' + encodeURIComponent(uri));
686});
687
688// Follow a remote actor from your own site (when the target is a profile, not a post).
689router.post('/authorize_interaction/follow', requireSiteManager, (req, res) => {
690 const site = res.locals.site;
691 const uri = (req.body.uri || '').toString();
692 if (site && uri) {
693 ActivityPubService.followActor(site, uri)
694 .catch((e) => console.warn('[AP] remote follow failed:', e.message));
695 }
696 res.redirect('/authorize_interaction?followed=1&uri=' + encodeURIComponent(uri));
697});
698
699router.post('/authorize_interaction', requireSiteManager, (req, res) => {
700 const site = res.locals.site;
701 const uri = (req.body.uri || '').toString();
702 const text = (req.body.text || '').toString();
703 if (site && uri && text.trim()) {
704 // Resolve + deliver in the background so Send responds instantly.
705 ActivityPubService.resolveRemoteNote(uri)
706 .then((parent) => parent && ActivityPubService.deliverReply(site, { postId: parent.localPostId || '', postSlug: null, parent, text }))
707 .catch((e) => console.warn('[AP] remote reply failed:', e.message));
708 }
709 res.redirect('/authorize_interaction?sent=1&uri=' + encodeURIComponent(uri));
710});
711
712// Manage / delete your own outbound fediverse replies (site owner only).
713router.get('/fediverse', requireSiteManager, (req, res) => {
714 const site = res.locals.site;
715 const items = site ? ActivityPubService.listOutbox(site.slug) : [];
716 renderPage(req, res, 'pages/authorize-interaction', {
717 pageTitle: 'Mijn fediverse-reacties', bodyClass: 'on-special',
718 manage: items, uri: '', target: null, sent: false, siteTitle: site ? site.title : '',
719 });
720});
721
722router.post('/fediverse/:id/delete', requireSiteManager, async (req, res) => {
723 const site = res.locals.site;
724 if (site) {
725 try { await ActivityPubService.deliverOutboxDelete(site, req.params.id); }
726 catch (e) { console.warn('[AP] outbox delete failed:', e.message); }
727 }
728 res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/fediverse`);
729});
730
731// Edit one of your own outbound fediverse replies (owner only) → sends an Update(Note).
732router.post('/fediverse/:id/edit', requireSiteManager, async (req, res) => {
733 const site = res.locals.site;
734 if (site && String(req.body.text || '').trim()) {
735 try { await ActivityPubService.deliverOutboxUpdate(site, req.params.id, req.body.text); }
736 catch (e) { console.warn('[AP] outbox edit failed:', e.message); }
737 }
738 res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/fediverse`);
739});
740
741// ==================== FEDIVERSE CLIENT: home timeline + following ====================
742// Build a direct embed iframe for the first embeddable link (YouTube/Spotify/
743// SoundCloud/Vimeo) in a remote post's content, so others' media plays inline.
744function timelineEmbedHtml(html) {
745 if (!html) return null;
746 const re = /href=["']([^"']+)["']/gi; let m; const seen = new Set();
747 while ((m = re.exec(html))) {
748 const u = m[1]; if (seen.has(u)) continue; seen.add(u);
749 let p; try { p = AudioEmbedService.detectProvider(u); } catch { p = null; }
750 if (!p) {
751 // PeerTube is decentralised (any instance), so it's not in detectProvider — match its watch URL
752 // (/w/<id> or /videos/watch/<id>) and embed the player. Host is validated (safe chars only), so
753 // it's safe to inline into the iframe src; a non-PeerTube /w/ URL just yields an empty iframe.
754 const pt = u.match(/^https?:\/\/([\w.-]+(?::\d+)?)\/(?:w|videos\/watch)\/([\w-]{6,})/i);
755 if (pt) return `<iframe class="tl-embed-frame" src="https://${pt[1]}/videos/embed/${pt[2]}" title="PeerTube" loading="lazy" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>`;
756 continue;
757 }
758 if (p.provider === 'youtube') return `<iframe class="tl-embed-frame" src="https://www.youtube-nocookie.com/embed/${p.id}" title="YouTube" loading="lazy" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
759 if (p.provider === 'spotify') return `<iframe class="tl-embed-frame tl-embed-spotify" src="https://open.spotify.com/embed/${p.type}/${p.id}" title="Spotify" loading="lazy" frameborder="0" allow="encrypted-media"></iframe>`;
760 if (p.provider === 'soundcloud') return `<iframe class="tl-embed-frame tl-embed-sc" src="https://w.soundcloud.com/player/?url=${encodeURIComponent(p.url)}&color=%23ff5500&visual=false" title="SoundCloud" loading="lazy" frameborder="0" allow="autoplay" scrolling="no"></iframe>`;
761 if (p.provider === 'vimeo') return `<iframe class="tl-embed-frame" src="https://player.vimeo.com/video/${p.id}" title="Vimeo" loading="lazy" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>`;
762 if (p.provider === 'bandcamp') return `<iframe class="tl-embed-frame tl-embed-bandcamp" src="https://bandcamp.com/EmbeddedPlayer/url=${encodeURIComponent(u)}/size=large/bgcol=faf8f3/linkcol=c2410c/tracklist=false/transparent=true/" title="Bandcamp" loading="lazy" frameborder="0" allow="encrypted-media"></iframe>`;
763 if (p.provider === 'applemusic') { const am = u.match(/music\.apple\.com\/([a-z]{2}\/(?:album|playlist|song)\/[^/?#]+\/[0-9]+)/i); if (am) return `<iframe class="tl-embed-frame tl-embed-apple" src="https://embed.music.apple.com/${am[1]}" title="Apple Music" loading="lazy" frameborder="0" allow="autoplay; encrypted-media"></iframe>`; }
764 }
765 return null;
766}
767
768// A federated Klonkt audio post renders as "🎵 … listen on <link>". Embed the remote
769// Klonkt player (its /embed?post=<slug>). A single-segment path = a Klonkt post slug
770// (skips Mastodon /@user/123). The origin is whitelisted in the response CSP frame-src.
771function klonktAudioEmbed(html, url) {
772 if (!html || !url || html.indexOf('🎵') < 0) return null;
773 let u; try { u = new URL(url); } catch { return null; }
774 if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;
775 const slug = u.pathname.replace(/^\/+|\/+$/g, '');
776 if (!slug || slug.indexOf('/') >= 0) return null; // single segment only
777 const src = u.origin + '/embed?post=' + encodeURIComponent(slug);
778 // Drop the now-redundant "🎵 … listen on <site>" line — the embedded player below shows it.
779 const content = html.replace(/<p>🎵[\s\S]*?<\/p>\s*/i, '');
780 return { origin: u.origin, embedUrl: src, content, html: `<iframe class="tl-embed-frame tl-embed-klonkt" src="${src}" title="Audio" loading="lazy" frameborder="0" allow="autoplay; encrypted-media"></iframe>` };
781}
782
783router.get('/news', requireSiteManager, (req, res) => {
784 const site = res.locals.site;
785 const cspOrigins = new Set();
786 const timeline = (site ? ActivityPubService.getTimeline(site.slug, 60) : []).map((p) => {
787 let embedHtml = timelineEmbedHtml(p.content);
788 let content = p.content;
789 let embedUrl = null;
790 if (!embedHtml) {
791 const k = klonktAudioEmbed(p.content, p.url);
792 if (k) { embedHtml = k.html; content = k.content; embedUrl = k.embedUrl; cspOrigins.add(k.origin); }
793 }
794 // embedUrl = the player's direct /embed?post=… URL. Surfaced so the view can offer a
795 // top-level "open the player" link that works even when a browser shield/CSP blocks
796 // the cross-site iframe (a full-page navigation is not a cross-site frame).
797 let poll = null;
798 if (p.poll_json) { try { poll = JSON.parse(p.poll_json); } catch { /* ignore */ } }
799 return { ...p, content, embedHtml, embedUrl, poll };
800 });
801 // Option A: allow the followed Klonkt sites' player iframes (you follow them) by
802 // extending ONLY this response's CSP frame-src. The global policy stays locked down.
803 if (cspOrigins.size) {
804 const csp = res.getHeader('Content-Security-Policy');
805 if (csp) {
806 const extra = [...cspOrigins].join(' ');
807 res.setHeader('Content-Security-Policy', String(csp).replace(/frame-src ([^;]*)/i, (m, g) => `frame-src ${g} ${extra}`));
808 }
809 }
810 renderPage(req, res, 'pages/news', {
811 pageTitle: 'News', bodyClass: 'on-special',
812 timeline,
813 success: req.query.success || null, error: req.query.error || null,
814 });
815});
816
817// Volgend — manage the accounts you follow (+ per-account auto-boost toggles).
818router.get('/following', requireSiteManager, (req, res) => {
819 const site = res.locals.site;
820 const following = site ? ActivityPubService.listFollowing(site.slug) : [];
821 renderPage(req, res, 'pages/following', {
822 pageTitle: 'Volgend', bodyClass: 'on-special',
823 following,
824 success: req.query.success || null, error: req.query.error || null,
825 });
826});
827
828// Followers (remote AP actors following us) + per-account delivery health, so dead
829// accounts (never/last-delivered long ago) can be pruned after a manual check.
830router.get('/followers', requireSiteManager, (req, res) => {
831 const site = res.locals.site;
832 const followers = site ? ActivityPubService.listFollowers(site.slug) : [];
833 renderPage(req, res, 'pages/followers', {
834 pageTitle: 'Volgers', bodyClass: 'on-special',
835 followers,
836 success: req.query.success || null, error: req.query.error || null,
837 });
838});
839
840router.post('/followers/:id/remove', requireSiteManager, (req, res) => {
841 const site = res.locals.site;
842 const base = res.locals.siteUrlBase || '';
843 if (!site) return res.redirect(`${base}/followers`);
844 const ok = ActivityPubService.removeFollower(site.slug, parseInt(req.params.id, 10) || 0);
845 return res.redirect(`${base}/followers?` + (ok
846 ? 'success=' + encodeURIComponent('Volger verwijderd')
847 : 'error=' + encodeURIComponent('Volger niet gevonden')));
848});
849
850router.post('/news/follow', requireSiteManager, async (req, res) => {
851 const site = res.locals.site;
852 const handle = (req.body.handle || '').toString();
853 let q = 'success=' + encodeURIComponent('Volgverzoek verstuurd');
854 if (site && handle.trim()) {
855 try {
856 const r = await ActivityPubService.followActor(site, handle, !!req.body.auto_boost);
857 if (r && r.error) q = 'error=' + encodeURIComponent(r.error === 'not_found' ? 'Account niet gevonden' : (r.error === 'unreachable' ? 'Server onbereikbaar' : 'Volgen mislukt'));
858 else {
859 q = 'success=' + encodeURIComponent('Je volgt nu ' + ((r && r.name) || handle));
860 }
861 } catch (e) { q = 'error=' + encodeURIComponent('Volgen mislukt'); }
862 }
863 res.redirect('/following?' + q);
864});
865
866router.post('/news/unfollow', requireSiteManager, async (req, res) => {
867 const site = res.locals.site;
868 const actorUri = (req.body.actor_uri || '').toString();
869 if (site && actorUri) { try { await ActivityPubService.unfollowActor(site, actorUri); } catch (e) { /* ignore */ } }
870 res.redirect('/following?success=' + encodeURIComponent('Ontvolgd'));
871});
872
873// Toggle "Featured" (show this account's posts in your Cirkel) on an account you follow.
874router.post('/news/autoboost', requireSiteManager, (req, res) => {
875 const site = res.locals.site;
876 const actorUri = (req.body.actor_uri || '').toString();
877 if (site && actorUri) ActivityPubService.setAutoBoost(site.slug, actorUri, !!req.body.auto_boost);
878 res.redirect('/following?success=' + encodeURIComponent(req.body.auto_boost ? 'Uitgelicht ✨' : 'Niet meer uitgelicht'));
879});
880
881// Like / unlike a feed post — a toggle. Fetch request → JSON {on} (stay on the page,
882// no banner); no-JS → redirect back.
883router.post('/news/like', requireSiteManager, async (req, res) => {
884 const site = res.locals.site;
885 const note = (req.body.note || '').toString();
886 let on = false;
887 if (site && note) {
888 on = !ActivityPubService.getTimelineReaction(site.slug, note).liked;
889 try { await ActivityPubService.sendInteraction(site, on ? 'like' : 'unlike', note, (req.body.author || '').toString()); } catch (e) { /* ignore */ }
890 if (on) ActivityPubService.markLiked(site.slug, note); else ActivityPubService.unmarkLiked(site.slug, note);
891 }
892 if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
893 res.redirect('/news');
894});
895
896// Boost / unboost a feed post — a toggle. markBoosted also surfaces it in the Cirkel.
897router.post('/news/boost', requireSiteManager, async (req, res) => {
898 const site = res.locals.site;
899 const note = (req.body.note || '').toString();
900 let on = false;
901 if (site && note) {
902 on = !ActivityPubService.getTimelineReaction(site.slug, note).boosted;
903 try { await ActivityPubService.sendInteraction(site, on ? 'boost' : 'unboost', note, (req.body.author || '').toString()); } catch (e) { /* ignore */ }
904 if (on) {
905 ActivityPubService.markBoosted(site.slug, note); // instant UI state
906 // Fire-and-forget: re-resolve the note so the cached row is refreshed
907 // (cover/content) — boosting again heals a stale copy from EVERY boost
908 // path, not just the interact page.
909 ActivityPubService.resolveRemoteNote(note)
910 .then((n) => { if (n) ActivityPubService.upsertBoostedNote(site.slug, n); })
911 .catch(() => { /* best-effort */ });
912 } else {
913 ActivityPubService.unmarkBoosted(site.slug, note);
914 }
915 }
916 if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
917 res.redirect('/news');
918});
919
920// Vote on a fediverse poll (a Question in the feed). Owner-only, like the other interactions.
921router.post('/news/vote', requireSiteManager, async (req, res) => {
922 const site = res.locals.site;
923 const note = (req.body.note || '').toString();
924 let choice = req.body.choice;
925 if (choice == null) choice = [];
926 if (!Array.isArray(choice)) choice = [choice];
927 if (site && note && choice.length) { try { await ActivityPubService.voteOnPoll(site, note, choice.map(String)); } catch (e) { /* ignore */ } }
928 res.redirect('/news');
929});
930
931// Notifications inbox (new followers + replies/likes/boosts on your posts).
932router.get('/notifications', requireSiteManager, (req, res) => {
933 const site = res.locals.site;
934 const items = site ? ActivityPubService.getNotifications(site.slug, 80) : [];
935 // viewing = seen → clears the bell badge. A viewer (kijker) may look but must not
936 // mutate state (the global write-guard only catches non-GET, not this GET-side effect).
937 if (site && !isViewer(req.session.user)) ActivityPubService.markNotificationsSeen(site.slug);
938 renderPage(req, res, 'pages/fedi-notifications', { pageTitle: 'Meldingen', bodyClass: 'on-special', items });
939});
940
941// Blocking / defederation (owner-only).
942router.get('/blocking', requireSiteManager, (req, res) => {
943 const site = res.locals.site;
944 const blocks = site ? ActivityPubService.listBlocks(site.slug) : [];
945 renderPage(req, res, 'pages/blocks', { pageTitle: 'Blokkeren', bodyClass: 'on-special', blocks, success: req.query.success || null, error: req.query.error || null });
946});
947
948router.post('/blocking/add', requireSiteManager, async (req, res) => {
949 const site = res.locals.site;
950 let q = 'success=' + encodeURIComponent('Geblokkeerd');
951 if (site) {
952 try {
953 const r = await ActivityPubService.blockTarget(site, (req.body.target || '').toString());
954 if (r && r.error) q = 'error=' + encodeURIComponent(r.error === 'not_found' ? 'Account niet gevonden' : 'Voer een @handle of domein in');
955 else q = 'success=' + encodeURIComponent(((r && r.label) || '') + ' geblokkeerd');
956 } catch (e) { q = 'error=' + encodeURIComponent('Blokkeren mislukt'); }
957 }
958 const ref = req.get('Referer') || '';
959 res.redirect((ref.includes('/news') ? '/news?' : '/blocking?') + q);
960});
961
962router.post('/blocking/remove', requireSiteManager, (req, res) => {
963 const site = res.locals.site;
964 if (site) { try { ActivityPubService.unblock(site, (req.body.target || '').toString()); } catch (e) { /* ignore */ } }
965 res.redirect('/blocking?success=' + encodeURIComponent('Deblokkeerd'));
966});
967
968// ==================== VIEW POST (last route — catches /:slug) ====================
969router.get('/:slug', (req, res, next) => {
970 if (RESERVED_SLUGS.has(req.params.slug)) return next();
971
972 const site = res.locals.site;
973 if (!site) return next(); // -> nette 404 catch-all
974
975 const post = db.prepare(`
976 SELECT p.*, u.username as author_username, u.avatar_url as author_avatar
977 FROM posts p JOIN users u ON p.author_id = u.id
978 WHERE p.site_id = ? AND p.slug = ?
979 `).get(site.id, req.params.slug);
980
981 if (!post) return next(); // unknown slug -> clean 404 catch-all
982
983 // Permission to view: published OR (logged in + can edit)
984 if (post.status !== 'published') {
985 const canEdit = req.session?.user && PermissionsService.canEditPost(req.session.user, post, site);
986 if (!canEdit) return res.status(403).send('Not published');
987 }
988
989 // Fan-only preview (premium #3): full content only for logged-in fans.
990 // Anonymous visitors get a clean login gate instead of the content (the title/
991 // teaser may still appear elsewhere as a teaser).
992 if (post.fan_only && !(req.session && req.session.user)) {
993 // Same Newer/Older navigation as on a normal post, so the visitor doesn't get
994 // stuck on the fan gate but can keep browsing.
995 const { newerPost, olderPost } = postNeighbors(site, post, res.locals.tenancy === 'hub');
996 return renderPage(req, res, 'pages/fan-gate', {
997 pageTitle: post.title || 'Alleen voor fans',
998 bodyClass: 'on-special',
999 fgTitle: post.title || '',
1000 fgNext: (res.locals.siteUrlBase || '') + '/' + post.slug,
1001 newerPost,
1002 olderPost,
1003 });
1004 }
1005
1006 // Statistics: count the view (skips admins + unpublished own-preview).
1007 if (post.status === 'published') recordPostView(post, req);
1008
1009 // Render content. Base = the pre-rendered ("baked") display HTML: #hashtags/URLs (and, later,
1010 // @mentions) linkified once at SAVE and cached in content_rendered — the ActivityPub `source`
1011 // model (content = raw source, kept for editing). Old posts with no baked copy fall back to
1012 // baking on the fly (cheap, no network). The dynamic layer (autoembed + [[track/album/
1013 // playlist]] + signed audio URLs) stays per-render on top, since it can't be cached.
1014 let html = (post.content_rendered != null && post.content_rendered !== '')
1015 ? post.content_rendered
1016 : ActivityPubService.bakePostContent(post.content || '');
1017 if (audioEnabled()) {
1018 if (site.enable_audio_player !== 0) {
1019 html = AudioEmbedService.autoembed(html);
1020 html = AudioEmbedService.embedMediaShortcodes(html);
1021 html = AudioEmbedService.embedExternalLinkShortcodes(html);
1022
1023 // Fetch any tracks referenced by [[track:id]] in this post.
1024 // Cheap to do unconditionally — only matches if the post actually has shortcodes.
1025 const trackIds = [...html.matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)].map(m => m[1]);
1026 if (trackIds.length) {
1027 const placeholders = trackIds.map(() => '?').join(',');
1028 const rows = db.prepare(`
1029 SELECT t.id, t.title, t.artist, t.cover_url, t.credit, t.license,
1030 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
1031 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
1032 WHERE t.site_id = ? AND t.id IN (${placeholders})
1033 `).all(site.id, ...trackIds);
1034 const byId = new Map(rows.map(r => [r.id, r]));
1035 html = AudioEmbedService.embedTrackShortcodes(html, (id) => {
1036 const r = byId.get(id);
1037 if (!r) return null;
1038 return {
1039 id: r.id,
1040 title: r.title,
1041 artist: r.artist,
1042 cover: r.cover_url,
1043 credit: r.credit || '',
1044 license: r.license || '',
1045 link_spotify: r.link_spotify || '',
1046 link_youtube: r.link_youtube || '',
1047 link_soundcloud: r.link_soundcloud || '',
1048 url: r.filename ? audioUrl(r.filename) : '', // '' = link-only track
1049 };
1050 });
1051 }
1052
1053 // Album shortcodes: [[album:Some Album Name]]
1054 const albumNames = [...html.matchAll(/\[\[album:([^\]]+)\]\]/g)].map(m => m[1].trim());
1055 if (albumNames.length) {
1056 const placeholders = albumNames.map(() => '?').join(',');
1057 const albumRows = db.prepare(`
1058 SELECT t.id, t.title, t.artist, t.album, t.cover_url, t.position,
1059 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
1060 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
1061 WHERE t.site_id = ? AND t.album IN (${placeholders})
1062 ORDER BY t.position ASC, t.created_at ASC
1063 `).all(site.id, ...albumNames);
1064 const byAlbum = new Map();
1065 for (const r of albumRows) {
1066 // Link-only tracks (no file) remain in the album overview (url '').
1067 if (!byAlbum.has(r.album)) byAlbum.set(r.album, []);
1068 byAlbum.get(r.album).push({
1069 id: r.id,
1070 url: r.filename ? audioUrl(r.filename) : '',
1071 title: r.title || 'Untitled',
1072 artist: r.artist || '',
1073 cover: r.cover_url || '',
1074 link_spotify: r.link_spotify || '',
1075 link_youtube: r.link_youtube || '',
1076 link_soundcloud: r.link_soundcloud || '',
1077 });
1078 }
1079 html = AudioEmbedService.embedAlbumShortcodes(html, (name) => {
1080 const tracks = byAlbum.get(name);
1081 if (!tracks || !tracks.length) return null;
1082 return {
1083 title: name,
1084 artist: tracks[0].artist || '',
1085 cover: tracks[0].cover || '',
1086 tracks,
1087 };
1088 });
1089 }
1090
1091 // Playlist shortcodes: [[playlist:some-slug-id]] — first-class entity.
1092 // Editing the playlist propagates to every post that embeds it.
1093 const playlistIds = [...html.matchAll(/\[\[playlist:([a-z0-9][a-z0-9-]*)\]\]/gi)]
1094 .map(m => m[1].toLowerCase());
1095 if (playlistIds.length) {
1096 const isAdmin = req.session?.user?.role === 'god';
1097 html = AudioEmbedService.embedPlaylistShortcodes(html, (id) => {
1098 return PlaylistService.get(site.id, id, audioUrl);
1099 }, { isAdmin });
1100 }
1101 }
1102 } else {
1103 // LITE mode (KLONKT_AUDIO=off): no own audio (no ffmpeg/stream route).
1104 // External embeds (YouTube/SoundCloud/Spotify) remain; the own-audio
1105 // shortcodes ([[track]]/[[album]]/[[playlist]]) are cleanly stripped.
1106 html = AudioEmbedService.autoembed(html);
1107 html = AudioEmbedService.embedMediaShortcodes(html);
1108 html = AudioEmbedService.embedExternalLinkShortcodes(html);
1109 html = html.replace(/\[\[(track|album|playlist):[^\]]+\]\]/gi, '');
1110 }
1111 // (linkify is baked into content_rendered at save now, not re-run here.)
1112 post.content_html = html;
1113
1114 if (post.tags) {
1115 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
1116 } else {
1117 post.tags = [];
1118 }
1119
1120 // Native comments removed: social interaction is fediverse-only (see the
1121 // "From the fediverse" section below).
1122
1123 // Prev / next chronological (kept for back-compat — "post-nav" feature
1124 // below the article still uses these as a simple linear navigation).
1125 // Hub mode: Related posts + Newer/Older pull from ALL users (all sites),
1126 // newest first. Solo mode: within the current site (old behaviour).
1127 const isHub = res.locals.tenancy === 'hub';
1128 // Per-post URL base: in hub a link points to /user/<site-slug>/<post-slug>.
1129 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
1130
1131 // Newer/Older across ALL posts (shared helper — also used by the fan gate).
1132 const { newerPost, olderPost } = postNeighbors(site, post, isHub);
1133
1134 // ── Related posts: same-tag matching with recency fallback ─────
1135 // Fetch ~50 candidates, score by tag overlap, take top 3.
1136 // Excluding self via `id != ?`.
1137 const candidates = isHub
1138 ? db.prepare(`
1139 SELECT p.id, p.slug, p.title, p.cover_image_url, p.cover_video_url, p.published_at, p.tags, p.nsfw, p.content_warning, s.slug AS site_slug
1140 FROM posts p JOIN sites s ON s.id = p.site_id
1141 WHERE p.status = 'published' AND p.id != ?
1142 ORDER BY p.published_at DESC LIMIT 50
1143 `).all(post.id)
1144 : db.prepare(`
1145 SELECT id, slug, title, cover_image_url, cover_video_url, published_at, tags, nsfw, content_warning
1146 FROM posts
1147 WHERE site_id = ? AND status = 'published' AND id != ?
1148 ORDER BY published_at DESC LIMIT 50
1149 `).all(site.id, post.id);
1150
1151 // Parse tags JSON safely; missing/malformed → empty array.
1152 const parseTags = (raw) => {
1153 if (!raw) return [];
1154 try {
1155 const v = JSON.parse(raw);
1156 return Array.isArray(v) ? v.map(String) : [];
1157 } catch { return []; }
1158 };
1159
1160 const myTags = new Set(parseTags(post.tags));
1161 let relatedPosts;
1162 if (myTags.size > 0) {
1163 // Score = number of overlapping tags. Posts with zero overlap are
1164 // included only if we don't have 3 with-overlap candidates.
1165 const scored = candidates.map(p => {
1166 const theirTags = parseTags(p.tags);
1167 const overlap = theirTags.reduce((n, t) => n + (myTags.has(t) ? 1 : 0), 0);
1168 return { ...p, _overlap: overlap };
1169 });
1170 const withOverlap = scored.filter(p => p._overlap > 0)
1171 .sort((a, b) => b._overlap - a._overlap || new Date(b.published_at) - new Date(a.published_at));
1172 if (withOverlap.length >= 3) {
1173 relatedPosts = withOverlap.slice(0, 3);
1174 } else {
1175 // Pad with most-recent non-overlap posts so the section is never empty
1176 const overlapIds = new Set(withOverlap.map(p => p.id));
1177 const filler = candidates.filter(p => !overlapIds.has(p.id));
1178 relatedPosts = [...withOverlap, ...filler].slice(0, 3);
1179 }
1180 } else {
1181 // No tags on current post → just show 3 most-recent
1182 relatedPosts = candidates.slice(0, 3);
1183 }
1184 // Strip the internal _overlap field before sending to view
1185 relatedPosts = relatedPosts.map(({ _overlap, tags, ...rest }) => ({ ...rest, _urlBase: urlBaseFor(rest) }));
1186
1187 // Inbound fediverse activity (threaded) for this post.
1188 let fediverse = { thread: [], likeCount: 0, announceCount: 0, total: 0 };
1189 try {
1190 const _apBase = (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
1191 fediverse = ActivityPubService.getInteractions(post.id, _apBase, site);
1192 // Stale-while-revalidate: render from cache now; refresh the remote thread in the
1193 // background (TTL-gated, non-blocking) so undelivered replies-to-replies fill in next view.
1194 if (res.locals.apEnabled !== false) ActivityPubService.maybeCrawlThread(post.id);
1195 } catch { /* non-fatal */ }
1196 // Owner/admin of this site may reply back to a fediverse interaction.
1197 const canManageSite = !!(req.session?.user && PermissionsService.canAdminSite(req.session.user, site));
1198 // Avatar for our own (outbound) fediverse replies = the site's profile photo.
1199 const siteAvatar = (site && site.profile_photo) ? site.profile_photo : null;
1200
1201 renderPage(req, res, 'pages/post', {
1202 post,
1203 poll: ActivityPubService.ownPollView(post),
1204 newerPost,
1205 olderPost,
1206 relatedPosts,
1207 fediverse,
1208 canManageSite,
1209 siteAvatar,
1210 postHasPlayableAudio: ActivityPubService.hasPlayableAudio(post.content || '', site.id),
1211 musicLd: MusicMeta.build((process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, ''), site, post),
1212 pageTitle: post.title + ' - ' + site.title,
1213 socialDescr: post.excerpt || '',
1214 socialImage: post.cover_image_url || '',
1215 bodyClass: 'on-post',
1216 });
1217});
1218
1219// ── Reply back to a fediverse interaction (site owner/admin only) ──
1220router.post('/posts/:slug/fedi-reply', requireSiteManager, async (req, res) => {
1221 const site = res.locals.site;
1222 if (!site) return res.status(404).send('Site required');
1223 const post = db.prepare('SELECT id, slug FROM posts WHERE site_id = ? AND slug = ?').get(site.id, req.params.slug);
1224 if (!post) return res.status(404).send('Not found');
1225 const parent = ActivityPubService.getInteractionById(req.body.interaction_id);
1226 const text = (req.body.text || '').toString();
1227 if (parent && parent.post_id === post.id && text.trim()) {
1228 try {
1229 await ActivityPubService.deliverReply(site, { postId: post.id, postSlug: post.slug, parent, text });
1230 } catch (e) { console.warn('[AP] reply send failed:', e.message); }
1231 }
1232 res.redirect(`${res.locals.siteUrlBase || ''}/${post.slug}#fediverse`);
1233});
1234
1235// Owner likes/boosts a fediverse comment on their own post — directly as the
1236// site, no "your server" detour (mirrors /fedi-reply).
1237router.post('/posts/:slug/fedi-react', requireSiteManager, async (req, res) => {
1238 const site = res.locals.site;
1239 if (!site) return res.status(404).send('Site required');
1240 const post = db.prepare('SELECT id, slug FROM posts WHERE site_id = ? AND slug = ?').get(site.id, req.params.slug);
1241 if (!post) return res.status(404).send('Not found');
1242 const parent = ActivityPubService.getInteractionById(req.body.interaction_id);
1243 const kind = req.body.kind === 'boost' ? 'boost' : 'like';
1244 if (parent && parent.post_id === post.id && parent.object_uri) {
1245 if (kind === 'boost') {
1246 // Toggle: boost an unboosted comment, or retract it (Undo Announce) if already boosted.
1247 const on = !parent.acted_boost;
1248 ActivityPubService.sendInteraction(site, on ? 'boost' : 'unboost', parent.object_uri, parent.actor_uri)
1249 .catch((e) => console.warn('[AP] reaction failed:', e.message));
1250 ActivityPubService.setInteractionBoosted(parent.id, on);
1251 } else {
1252 // Toggle: like an unliked comment, or un-favourite (Undo Like) if already liked.
1253 const on = !parent.acted_like;
1254 ActivityPubService.sendInteraction(site, on ? 'like' : 'unlike', parent.object_uri, parent.actor_uri)
1255 .catch((e) => console.warn('[AP] reaction failed:', e.message));
1256 ActivityPubService.setInteractionLiked(parent.id, on);
1257 }
1258 }
1259 res.redirect(`${res.locals.siteUrlBase || ''}/${post.slug}#fediverse`);
1260});
1261
1262export default router;
1263export { postNeighbors };
Note: See TracBrowser for help on using the repository browser.