source: Klonkt/src/routes/posts.js@ 4424af7

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

Fix: linkify #hashtags and bare URLs in post bodies for on-site display

The website showed raw '#tag' and URL text in post bodies; only the
federated (Mastodon) copy got links, via buildNote. Add a shared
linkifyBody() that reuses the exact same linkHashtags()/linkUrls() rules and
apply it in the post render pipeline, so the site and the federated copy
agree. Idempotent (splits out existing <a>), so editor links and autoembeds
are never double-wrapped; hashtags point at the site's own /tag/<slug>.
@mention display-linking is deferred (needs a per-render webfinger lookup).

This is the first step of the compose/display pipeline unification; buildNote
should later call linkifyBody too so there is a single content pipeline.

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

  • Property mode set to 100644
File size: 58.3 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
240router.post('/posts/create', requireAuth, (req, res) => {
241 const site = res.locals.site;
242 if (!site || !PermissionsService.canCreatePost(req.session.user, site)) {
243 return res.status(403).send('No permission');
244 }
245
246 const { title, slug, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
247 const fanOnly = req.body.fan_only ? 1 : 0;
248 const nsfw = req.body.nsfw ? 1 : 0;
249 const cw = (req.body.content_warning || '').trim().slice(0, 200);
250 const coverAlt = (req.body.cover_alt || '').trim().slice(0, 1500) || null; // cover alt text (a11y)
251 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
252
253 // Content arrives as user-authored HTML from the WYSIWYG editor — sanitize
254 // before storage. Shortcode text tokens like [[track:UUID]] live in text
255 // nodes and pass through untouched.
256 const cleanContent = HtmlSanitizerService.sanitize(content || '');
257
258 // Generate slug from title if empty
259 let finalSlug = (slug || title || '')
260 .toLowerCase()
261 .replace(/[^a-z0-9]+/g, '-')
262 .replace(/^-|-$/g, '');
263
264 if (!finalSlug) return res.status(400).send('Title or slug required');
265 if (RESERVED_SLUGS.has(finalSlug)) finalSlug = `${finalSlug}-post`;
266
267 // Duplicate title/slug? Make it unique automatically (title-2, title-3, …) instead of rejecting.
268 finalSlug = uniqueSlug(site.id, finalSlug);
269
270 const validTypes = new Set(['post', 'foto', 'video', 'audio']);
271 const finalType = validTypes.has(type) ? type : 'post';
272 const pollJson = parsePollForm(req.body); // AS2 Question definition, or null
273 const postId = uuid();
274 const now = new Date().toISOString();
275 let finalStatus = status || 'draft';
276 let publishedAt = finalStatus === 'published' ? now : null;
277 // Release planning: published + a future publish_at -> 'scheduled'
278 // (the Scheduler makes it live at that moment). Past/empty -> live immediately.
279 let publishAt = null;
280 const pa = Date.parse(req.body.publish_at || '');
281 if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
282 finalStatus = 'scheduled';
283 publishAt = new Date(pa).toISOString();
284 publishedAt = null;
285 }
286
287 db.prepare(`
288 INSERT INTO posts (
289 id, site_id, slug, author_id, title, content, excerpt,
290 status, cover_image_url, cover_video_url, cover_alt, language, pinned, tags, type, noindex, fan_only, nsfw, content_warning, poll_json, publish_at,
291 created_at, updated_at, published_at
292 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
293 `).run(
294 postId, site.id, finalSlug, req.session.user.id,
295 title || finalSlug, cleanContent, excerpt || '',
296 finalStatus, cover_image_url || null, (req.body.cover_video_url || null), coverAlt, language, parsePinnedRank(pinned),
297 JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
298 finalType, noindex ? 1 : 0, fanOnly, nsfw, cw, pollJson, publishAt,
299 now, now, publishedAt
300 );
301
302 // Per-post "share audio on the fediverse" → set fedi_open on this post's hosted tracks
303 // BEFORE federating, so the Create note carries the right Audio attachments.
304 setAudioFediOpen(site.id, cleanContent, req.body.fedi_open_audio);
305
306 if (finalStatus === 'published') {
307 try {
308 db.prepare(
309 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
310 ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, postId);
311 } catch (e) { /* FTS index issues are non-fatal */ }
312
313 // ActivityPub: federate a freshly published post to followers. fan_only → delivered
314 // to followers but addressed followers-only (option A: "fans" = your fedi followers).
315 if (status === 'published') {
316 ActivityPubService.deliverCreate(site, {
317 id: postId, slug: finalSlug, title: title || finalSlug,
318 content: cleanContent, cover_image_url: cover_image_url || null, cover_video_url: req.body.cover_video_url || null, cover_alt: coverAlt, language,
319 published_at: publishedAt, created_at: now, fan_only: fanOnly, nsfw, content_warning: cw, poll_json: pollJson,
320 }).catch(() => { /* best-effort */ });
321 }
322 }
323
324 // HTMX request -> return redirect header
325 if (req.headers['hx-request']) {
326 res.setHeader('HX-Redirect', `${res.locals.siteUrlBase || ''}/${finalSlug}`);
327 return res.send('OK');
328 }
329
330 res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
331});
332
333// ==================== EDIT POST FORM ====================
334router.get('/posts/:slug/edit', requireAuth, (req, res) => {
335 const site = res.locals.site;
336 if (!site) return res.status(404).send('Site required');
337
338 const post = db.prepare(
339 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
340 ).get(site.id, req.params.slug);
341
342 if (!post) return res.status(404).send('Post not found');
343 if (!PermissionsService.canEditPost(req.session.user, post, site)) {
344 return res.status(403).send('No permission');
345 }
346
347 if (post.tags) {
348 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
349 } else {
350 post.tags = [];
351 }
352
353 // A poll with votes is frozen (options can't change) — flag it so the editor disables the poll fields.
354 let pollLocked = false;
355 try { pollLocked = !!(post.poll_json && db.prepare('SELECT 1 FROM poll_votes WHERE post_id = ? LIMIT 1').get(post.id)); } catch { /* ignore */ }
356
357 renderPage(req, res, 'pages/post-edit', {
358 post,
359 isNew: false,
360 pollLocked,
361 fediOpenAudio: postAudioFediOpen(site.id, post.content),
362 pageTitle: 'Edit: ' + (post.title || 'Untitled'),
363 bodyClass: 'on-special',
364 });
365});
366
367// ==================== SAVE POST ====================
368router.post('/posts/:slug/save', requireAuth, (req, res) => {
369 const site = res.locals.site;
370 if (!site) return res.status(404).send('Site required');
371
372 const post = db.prepare(
373 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
374 ).get(site.id, req.params.slug);
375
376 if (!post) return res.status(404).send('Post not found');
377 if (!PermissionsService.canEditPost(req.session.user, post, site)) {
378 return res.status(403).send('No permission');
379 }
380
381 const { title, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
382 const fanOnly = req.body.fan_only ? 1 : 0;
383 const nsfw = req.body.nsfw ? 1 : 0;
384 const cw = (req.body.content_warning || '').trim().slice(0, 200);
385 const coverAlt = (req.body.cover_alt || '').trim().slice(0, 1500) || null; // cover alt text (a11y)
386 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
387 const newSlug = req.body.slug;
388 const action = req.body.action || 'save';
389 const validTypes = new Set(['post', 'foto', 'video', 'audio']);
390 const finalType = validTypes.has(type) ? type : (post.type || 'post');
391
392 // A poll that has already received votes is frozen (you can still edit the surrounding
393 // post, but not the options) — changing options after votes would scramble the tally and
394 // is disallowed on the fediverse too. Otherwise re-parse the poll form (add/remove/disable).
395 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; } })());
396 const pollJson = hasVotes ? post.poll_json : parsePollForm(req.body);
397
398 // Sanitize before storage — same pipeline as create.
399 const cleanContent = HtmlSanitizerService.sanitize(content || '');
400
401 let finalSlug = post.slug;
402 if (newSlug && newSlug !== post.slug) {
403 const cleaned = newSlug.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
404 const safe = RESERVED_SLUGS.has(cleaned) ? `${cleaned}-post` : cleaned;
405 // Duplicate slug? Make it unique automatically instead of rejecting (own post may keep its slug).
406 finalSlug = uniqueSlug(site.id, safe, post.id);
407 }
408
409 const now = new Date().toISOString();
410 let finalStatus = status || post.status;
411 let publishedAt = post.published_at;
412
413 if (action === 'publish') {
414 finalStatus = 'published';
415 if (!publishedAt) publishedAt = now;
416 }
417
418 // Release planning: published + future publish_at -> 'scheduled'.
419 let publishAt = null;
420 const pa = Date.parse(req.body.publish_at || '');
421 if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
422 finalStatus = 'scheduled';
423 publishAt = new Date(pa).toISOString();
424 publishedAt = null;
425 }
426
427 db.prepare(`
428 UPDATE posts SET
429 title = ?, content = ?, excerpt = ?, status = ?,
430 cover_image_url = ?, cover_video_url = ?, cover_alt = ?, language = ?, pinned = ?, tags = ?,
431 type = ?, noindex = ?, fan_only = ?, nsfw = ?, content_warning = ?, poll_json = ?, publish_at = ?,
432 slug = ?, published_at = ?, updated_at = ?
433 WHERE id = ?
434 `).run(
435 title, cleanContent, excerpt, finalStatus,
436 cover_image_url || null, (req.body.cover_video_url || null), coverAlt, language, parsePinnedRank(pinned),
437 JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
438 finalType, noindex ? 1 : 0, fanOnly, nsfw, cw, pollJson, publishAt,
439 finalSlug, publishedAt, now, post.id
440 );
441
442 // Per-post "share audio on the fediverse" → set fedi_open on this post's hosted tracks
443 // BEFORE federating, so the Update/Create note carries the right Audio attachments.
444 setAudioFediOpen(site.id, cleanContent, req.body.fedi_open_audio);
445
446 // Update FTS
447 try {
448 db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id);
449 if (finalStatus === 'published') {
450 db.prepare(
451 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
452 ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, post.id);
453 }
454 } catch (e) { /* FTS issues non-fatal */ }
455
456 // ActivityPub: federate edits to followers. A post that BECOMES published →
457 // Create (new post); an already-published post that's edited → Update (so
458 // Mastodon refreshes its cached copy). fan_only → followers-only (option A).
459 if (finalStatus === 'published') {
460 const apPost = {
461 id: post.id, slug: finalSlug, title: title || finalSlug,
462 content: cleanContent, cover_image_url: cover_image_url || null, cover_video_url: req.body.cover_video_url || null, cover_alt: coverAlt, language,
463 published_at: publishedAt, created_at: post.created_at, fan_only: fanOnly, nsfw, content_warning: cw, poll_json: pollJson,
464 };
465 if (post.status !== 'published') ActivityPubService.deliverCreate(site, apPost).catch(() => { /* best-effort */ });
466 else ActivityPubService.deliverUpdate(site, apPost).catch(() => { /* best-effort */ });
467 }
468
469 // Pin/unpin/reorder → push Add/Remove activities so followers' instances update the
470 // pinned order immediately (reliable, unlike re-fetching the cached featured collection).
471 if ((post.pinned || 0) !== parsePinnedRank(pinned)) {
472 const unpinned = (post.pinned || 0) > 0 && parsePinnedRank(pinned) === 0 ? [post.id] : [];
473 ActivityPubService.resyncFeaturedPins(site, unpinned).catch(() => { /* best-effort */ });
474 }
475
476 res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
477});
478
479// ==================== DELETE POST ====================
480router.post('/posts/:slug/delete', requireAuth, (req, res) => {
481 const site = res.locals.site;
482 if (!site) return res.status(404).send('Site required');
483
484 const post = db.prepare(
485 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
486 ).get(site.id, req.params.slug);
487
488 if (!post) return res.status(404).send('Not found');
489 if (!PermissionsService.canDeletePost(req.session.user, post, site)) {
490 return res.status(403).send('No permission');
491 }
492
493 // ActivityPub: tell followers the post is gone (Delete + Tombstone) if it was
494 // federated (any published post now federates — fan_only goes followers-only).
495 // Fire before the row is removed — we still have post.id (= the Note id).
496 if (post.status === 'published') {
497 ActivityPubService.deliverDelete(site, post).catch(() => { /* best-effort */ });
498 }
499
500 // Cascade: comments + FTS row, THEN the post itself.
501 // FK constraints are ON (config/database.js), so a bare DELETE on posts
502 // fails when comments still reference it.
503 const cascade = db.transaction(() => {
504 db.prepare('DELETE FROM comments WHERE post_id = ?').run(post.id);
505 try { db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id); } catch {}
506 db.prepare('DELETE FROM posts WHERE id = ?').run(post.id);
507 });
508 cascade();
509
510 if (req.headers['hx-request']) {
511 res.setHeader('HX-Redirect', res.locals.siteUrlBase || '/');
512 return res.send('OK');
513 }
514 res.redirect(res.locals.siteUrlBase || '/');
515});
516
517// ==================== ARCHIVE ====================
518router.get('/archive', (req, res) => {
519 const site = res.locals.site;
520 if (!site) return res.status(404).send('No site');
521
522 const posts = db.prepare(`
523 SELECT p.*, u.username as author_username
524 FROM posts p JOIN users u ON p.author_id = u.id
525 WHERE p.site_id = ? AND p.status = 'published'
526 ORDER BY p.published_at DESC
527 `).all(site.id);
528
529 // Group by year/month
530 const grouped = {};
531 for (const post of posts) {
532 if (!post.published_at) continue;
533 const d = new Date(post.published_at);
534 const year = d.getFullYear();
535 const month = d.getMonth();
536 const monthName = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'][month];
537
538 if (!grouped[year]) grouped[year] = {};
539 if (!grouped[year][monthName]) grouped[year][monthName] = [];
540 grouped[year][monthName].push(post);
541 }
542
543 renderPage(req, res, 'pages/archive', {
544 grouped,
545 totalPosts: posts.length,
546 pageTitle: 'Archive - ' + site.title,
547 bodyClass: 'on-archive',
548 });
549});
550
551// Local likes/favourites are removed — engagement is fediverse-only now
552// (the ⭐ on a post likes via the fediverse). No post_likes, no /favorieten.
553
554// Newer/Older neighbours across ALL posts in feed order. Shared by the full
555// post render and the fan gate (premium fan_only) so navigation is consistent
556// everywhere. Solo: within the site (pinned first, then date). Hub: globally by date.
557function postNeighbors(site, post, isHub) {
558 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
559 const ordered = isHub
560 ? db.prepare(`
561 SELECT p.id, p.slug, p.title, p.pinned, s.slug AS site_slug
562 FROM posts p JOIN sites s ON s.id = p.site_id
563 WHERE p.status = 'published'
564 ORDER BY p.published_at DESC
565 `).all()
566 : db.prepare(`
567 SELECT id, slug, title, pinned FROM posts
568 WHERE site_id = ? AND status = 'published'
569 ORDER BY (pinned = 0) ASC, pinned ASC, published_at DESC
570 `).all(site.id);
571 const idx = ordered.findIndex((p) => p.id === post.id);
572 const newerPost = idx > 0 ? ordered[idx - 1] : null;
573 const olderPost = (idx >= 0 && idx < ordered.length - 1) ? ordered[idx + 1] : null;
574 if (newerPost) newerPost._urlBase = urlBaseFor(newerPost);
575 if (olderPost) olderPost._urlBase = urlBaseFor(olderPost);
576 return { newerPost, olderPost };
577}
578
579// ==================== REMOTE INTERACTION (reply to a fediverse post as your site) ====================
580// Standard fediverse "reply from your own server" landing endpoint. A post page
581// elsewhere bounces the visitor here with ?uri=<remote post>; the site owner
582// composes a reply that federates back to that post.
583router.get('/authorize_interaction', requireSiteManager, async (req, res) => {
584 const site = res.locals.site;
585 const uri = (req.query.uri || '').toString();
586 const sent = !!req.query.sent;
587 const followed = !!req.query.followed;
588 const voted = !!req.query.voted;
589 const reported = !!req.query.reported;
590 let target = null, followTarget = null;
591 if (!sent && !followed && !voted && !reported && uri) {
592 try { target = await ActivityPubService.resolveRemoteNote(uri); } catch { /* ignore */ }
593 // Not a post? Maybe the URI is a profile/actor → offer Follow, not reply.
594 if (!target) { try { followTarget = await ActivityPubService.resolveRemoteActor(uri); } catch { /* ignore */ } }
595 }
596 renderPage(req, res, 'pages/authorize-interaction', {
597 pageTitle: 'Interacteer via de fediverse',
598 bodyClass: 'on-special',
599 uri,
600 target,
601 followTarget,
602 sent,
603 followed,
604 voted: !!req.query.voted,
605 reported: !!req.query.reported,
606 liked: !!req.query.liked,
607 boosted: !!req.query.boosted,
608 reacted: (site && uri) ? ActivityPubService.getMyReactions(site.slug, uri) : { liked: false, boosted: false },
609 siteTitle: site ? site.title : '',
610 });
611});
612
613// 📊 Vote on a remote fediverse poll from the interact page (any poll by URL, not just
614// followed ones). Casts the Mastodon-standard ballot straight to the poll's author.
615router.post('/authorize_interaction/vote', requireSiteManager, async (req, res) => {
616 const site = res.locals.site;
617 const uri = (req.body.uri || '').toString();
618 let choice = req.body.choice;
619 if (choice == null) choice = [];
620 if (!Array.isArray(choice)) choice = [choice];
621 if (site && uri && choice.length) { try { await ActivityPubService.voteOnRemotePoll(site, uri, choice.map(String)); } catch { /* ignore */ } }
622 res.redirect('/authorize_interaction?voted=1&uri=' + encodeURIComponent(uri));
623});
624
625// 🚩 Report a remote post/account to its home instance (sends an AS2 Flag).
626router.post('/authorize_interaction/report', requireSiteManager, async (req, res) => {
627 const site = res.locals.site;
628 const uri = (req.body.uri || '').toString();
629 const actorUri = (req.body.actor_uri || '').toString();
630 const reason = (req.body.reason || '').toString();
631 if (site && (uri || actorUri)) { try { await ActivityPubService.sendReport(site, { objectUri: uri, actorUri, reason }); } catch { /* ignore */ } }
632 res.redirect('/authorize_interaction?reported=1&uri=' + encodeURIComponent(uri || actorUri));
633});
634
635// ⭐ Like / unlike a remote post from your own site (toggle on the interact page).
636router.post('/authorize_interaction/like', requireSiteManager, (req, res) => {
637 const site = res.locals.site;
638 const uri = (req.body.uri || '').toString();
639 let on = false;
640 if (site && uri) {
641 on = !ActivityPubService.getMyReactions(site.slug, uri).liked;
642 ActivityPubService.resolveRemoteNote(uri)
643 .then((note) => note && ActivityPubService.sendInteraction(site, on ? 'like' : 'unlike', note.object_uri || uri, note.actor_uri))
644 .catch((e) => console.warn('[AP] remote like failed:', e.message));
645 ActivityPubService.setMyReaction(site.slug, uri, 'like', on);
646 }
647 if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
648 res.redirect('/authorize_interaction?uri=' + encodeURIComponent(uri));
649});
650
651// 🔁 Boost / unboost a remote post from your own site (toggle on the interact page).
652// Also flags it for the Cirkel (markBoosted is a no-op if the post isn't in your timeline).
653router.post('/authorize_interaction/boost', requireSiteManager, (req, res) => {
654 const site = res.locals.site;
655 const uri = (req.body.uri || '').toString();
656 let on = false;
657 if (site && uri) {
658 on = !ActivityPubService.getMyReactions(site.slug, uri).boosted;
659 ActivityPubService.resolveRemoteNote(uri)
660 .then((note) => {
661 if (!note) return;
662 const id = note.object_uri || uri;
663 return Promise.resolve(ActivityPubService.sendInteraction(site, on ? 'boost' : 'unboost', id, note.actor_uri))
664 // Boost → store the post in the timeline (even if you don't follow the author) so it
665 // surfaces in the Cirkel; unboost → just clear the flag.
666 .then(() => on ? ActivityPubService.upsertBoostedNote(site.slug, note) : ActivityPubService.unmarkBoosted(site.slug, id));
667 })
668 .catch((e) => console.warn('[AP] remote boost failed:', e.message));
669 ActivityPubService.setMyReaction(site.slug, uri, 'boost', on);
670 }
671 if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
672 res.redirect('/authorize_interaction?uri=' + encodeURIComponent(uri));
673});
674
675// Follow a remote actor from your own site (when the target is a profile, not a post).
676router.post('/authorize_interaction/follow', requireSiteManager, (req, res) => {
677 const site = res.locals.site;
678 const uri = (req.body.uri || '').toString();
679 if (site && uri) {
680 ActivityPubService.followActor(site, uri)
681 .catch((e) => console.warn('[AP] remote follow failed:', e.message));
682 }
683 res.redirect('/authorize_interaction?followed=1&uri=' + encodeURIComponent(uri));
684});
685
686router.post('/authorize_interaction', requireSiteManager, (req, res) => {
687 const site = res.locals.site;
688 const uri = (req.body.uri || '').toString();
689 const text = (req.body.text || '').toString();
690 if (site && uri && text.trim()) {
691 // Resolve + deliver in the background so Send responds instantly.
692 ActivityPubService.resolveRemoteNote(uri)
693 .then((parent) => parent && ActivityPubService.deliverReply(site, { postId: parent.localPostId || '', postSlug: null, parent, text }))
694 .catch((e) => console.warn('[AP] remote reply failed:', e.message));
695 }
696 res.redirect('/authorize_interaction?sent=1&uri=' + encodeURIComponent(uri));
697});
698
699// Manage / delete your own outbound fediverse replies (site owner only).
700router.get('/fediverse', requireSiteManager, (req, res) => {
701 const site = res.locals.site;
702 const items = site ? ActivityPubService.listOutbox(site.slug) : [];
703 renderPage(req, res, 'pages/authorize-interaction', {
704 pageTitle: 'Mijn fediverse-reacties', bodyClass: 'on-special',
705 manage: items, uri: '', target: null, sent: false, siteTitle: site ? site.title : '',
706 });
707});
708
709router.post('/fediverse/:id/delete', requireSiteManager, async (req, res) => {
710 const site = res.locals.site;
711 if (site) {
712 try { await ActivityPubService.deliverOutboxDelete(site, req.params.id); }
713 catch (e) { console.warn('[AP] outbox delete failed:', e.message); }
714 }
715 res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/fediverse`);
716});
717
718// Edit one of your own outbound fediverse replies (owner only) → sends an Update(Note).
719router.post('/fediverse/:id/edit', requireSiteManager, async (req, res) => {
720 const site = res.locals.site;
721 if (site && String(req.body.text || '').trim()) {
722 try { await ActivityPubService.deliverOutboxUpdate(site, req.params.id, req.body.text); }
723 catch (e) { console.warn('[AP] outbox edit failed:', e.message); }
724 }
725 res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/fediverse`);
726});
727
728// ==================== FEDIVERSE CLIENT: home timeline + following ====================
729// Build a direct embed iframe for the first embeddable link (YouTube/Spotify/
730// SoundCloud/Vimeo) in a remote post's content, so others' media plays inline.
731function timelineEmbedHtml(html) {
732 if (!html) return null;
733 const re = /href=["']([^"']+)["']/gi; let m; const seen = new Set();
734 while ((m = re.exec(html))) {
735 const u = m[1]; if (seen.has(u)) continue; seen.add(u);
736 let p; try { p = AudioEmbedService.detectProvider(u); } catch { p = null; }
737 if (!p) {
738 // PeerTube is decentralised (any instance), so it's not in detectProvider — match its watch URL
739 // (/w/<id> or /videos/watch/<id>) and embed the player. Host is validated (safe chars only), so
740 // it's safe to inline into the iframe src; a non-PeerTube /w/ URL just yields an empty iframe.
741 const pt = u.match(/^https?:\/\/([\w.-]+(?::\d+)?)\/(?:w|videos\/watch)\/([\w-]{6,})/i);
742 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>`;
743 continue;
744 }
745 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>`;
746 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>`;
747 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>`;
748 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>`;
749 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>`;
750 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>`; }
751 }
752 return null;
753}
754
755// A federated Klonkt audio post renders as "🎵 … listen on <link>". Embed the remote
756// Klonkt player (its /embed?post=<slug>). A single-segment path = a Klonkt post slug
757// (skips Mastodon /@user/123). The origin is whitelisted in the response CSP frame-src.
758function klonktAudioEmbed(html, url) {
759 if (!html || !url || html.indexOf('🎵') < 0) return null;
760 let u; try { u = new URL(url); } catch { return null; }
761 if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;
762 const slug = u.pathname.replace(/^\/+|\/+$/g, '');
763 if (!slug || slug.indexOf('/') >= 0) return null; // single segment only
764 const src = u.origin + '/embed?post=' + encodeURIComponent(slug);
765 // Drop the now-redundant "🎵 … listen on <site>" line — the embedded player below shows it.
766 const content = html.replace(/<p>🎵[\s\S]*?<\/p>\s*/i, '');
767 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>` };
768}
769
770router.get('/news', requireSiteManager, (req, res) => {
771 const site = res.locals.site;
772 const cspOrigins = new Set();
773 const timeline = (site ? ActivityPubService.getTimeline(site.slug, 60) : []).map((p) => {
774 let embedHtml = timelineEmbedHtml(p.content);
775 let content = p.content;
776 let embedUrl = null;
777 if (!embedHtml) {
778 const k = klonktAudioEmbed(p.content, p.url);
779 if (k) { embedHtml = k.html; content = k.content; embedUrl = k.embedUrl; cspOrigins.add(k.origin); }
780 }
781 // embedUrl = the player's direct /embed?post=… URL. Surfaced so the view can offer a
782 // top-level "open the player" link that works even when a browser shield/CSP blocks
783 // the cross-site iframe (a full-page navigation is not a cross-site frame).
784 let poll = null;
785 if (p.poll_json) { try { poll = JSON.parse(p.poll_json); } catch { /* ignore */ } }
786 return { ...p, content, embedHtml, embedUrl, poll };
787 });
788 // Option A: allow the followed Klonkt sites' player iframes (you follow them) by
789 // extending ONLY this response's CSP frame-src. The global policy stays locked down.
790 if (cspOrigins.size) {
791 const csp = res.getHeader('Content-Security-Policy');
792 if (csp) {
793 const extra = [...cspOrigins].join(' ');
794 res.setHeader('Content-Security-Policy', String(csp).replace(/frame-src ([^;]*)/i, (m, g) => `frame-src ${g} ${extra}`));
795 }
796 }
797 renderPage(req, res, 'pages/news', {
798 pageTitle: 'News', bodyClass: 'on-special',
799 timeline,
800 success: req.query.success || null, error: req.query.error || null,
801 });
802});
803
804// Volgend — manage the accounts you follow (+ per-account auto-boost toggles).
805router.get('/following', requireSiteManager, (req, res) => {
806 const site = res.locals.site;
807 const following = site ? ActivityPubService.listFollowing(site.slug) : [];
808 renderPage(req, res, 'pages/following', {
809 pageTitle: 'Volgend', bodyClass: 'on-special',
810 following,
811 success: req.query.success || null, error: req.query.error || null,
812 });
813});
814
815router.post('/news/follow', requireSiteManager, async (req, res) => {
816 const site = res.locals.site;
817 const handle = (req.body.handle || '').toString();
818 let q = 'success=' + encodeURIComponent('Volgverzoek verstuurd');
819 if (site && handle.trim()) {
820 try {
821 const r = await ActivityPubService.followActor(site, handle, !!req.body.auto_boost);
822 if (r && r.error) q = 'error=' + encodeURIComponent(r.error === 'not_found' ? 'Account niet gevonden' : (r.error === 'unreachable' ? 'Server onbereikbaar' : 'Volgen mislukt'));
823 else {
824 q = 'success=' + encodeURIComponent('Je volgt nu ' + ((r && r.name) || handle));
825 }
826 } catch (e) { q = 'error=' + encodeURIComponent('Volgen mislukt'); }
827 }
828 res.redirect('/following?' + q);
829});
830
831router.post('/news/unfollow', requireSiteManager, async (req, res) => {
832 const site = res.locals.site;
833 const actorUri = (req.body.actor_uri || '').toString();
834 if (site && actorUri) { try { await ActivityPubService.unfollowActor(site, actorUri); } catch (e) { /* ignore */ } }
835 res.redirect('/following?success=' + encodeURIComponent('Ontvolgd'));
836});
837
838// Toggle "Featured" (show this account's posts in your Cirkel) on an account you follow.
839router.post('/news/autoboost', requireSiteManager, (req, res) => {
840 const site = res.locals.site;
841 const actorUri = (req.body.actor_uri || '').toString();
842 if (site && actorUri) ActivityPubService.setAutoBoost(site.slug, actorUri, !!req.body.auto_boost);
843 res.redirect('/following?success=' + encodeURIComponent(req.body.auto_boost ? 'Uitgelicht ✨' : 'Niet meer uitgelicht'));
844});
845
846// Like / unlike a feed post — a toggle. Fetch request → JSON {on} (stay on the page,
847// no banner); no-JS → redirect back.
848router.post('/news/like', requireSiteManager, async (req, res) => {
849 const site = res.locals.site;
850 const note = (req.body.note || '').toString();
851 let on = false;
852 if (site && note) {
853 on = !ActivityPubService.getTimelineReaction(site.slug, note).liked;
854 try { await ActivityPubService.sendInteraction(site, on ? 'like' : 'unlike', note, (req.body.author || '').toString()); } catch (e) { /* ignore */ }
855 if (on) ActivityPubService.markLiked(site.slug, note); else ActivityPubService.unmarkLiked(site.slug, note);
856 }
857 if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
858 res.redirect('/news');
859});
860
861// Boost / unboost a feed post — a toggle. markBoosted also surfaces it in the Cirkel.
862router.post('/news/boost', requireSiteManager, async (req, res) => {
863 const site = res.locals.site;
864 const note = (req.body.note || '').toString();
865 let on = false;
866 if (site && note) {
867 on = !ActivityPubService.getTimelineReaction(site.slug, note).boosted;
868 try { await ActivityPubService.sendInteraction(site, on ? 'boost' : 'unboost', note, (req.body.author || '').toString()); } catch (e) { /* ignore */ }
869 if (on) {
870 ActivityPubService.markBoosted(site.slug, note); // instant UI state
871 // Fire-and-forget: re-resolve the note so the cached row is refreshed
872 // (cover/content) — boosting again heals a stale copy from EVERY boost
873 // path, not just the interact page.
874 ActivityPubService.resolveRemoteNote(note)
875 .then((n) => { if (n) ActivityPubService.upsertBoostedNote(site.slug, n); })
876 .catch(() => { /* best-effort */ });
877 } else {
878 ActivityPubService.unmarkBoosted(site.slug, note);
879 }
880 }
881 if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
882 res.redirect('/news');
883});
884
885// Vote on a fediverse poll (a Question in the feed). Owner-only, like the other interactions.
886router.post('/news/vote', requireSiteManager, async (req, res) => {
887 const site = res.locals.site;
888 const note = (req.body.note || '').toString();
889 let choice = req.body.choice;
890 if (choice == null) choice = [];
891 if (!Array.isArray(choice)) choice = [choice];
892 if (site && note && choice.length) { try { await ActivityPubService.voteOnPoll(site, note, choice.map(String)); } catch (e) { /* ignore */ } }
893 res.redirect('/news');
894});
895
896// Notifications inbox (new followers + replies/likes/boosts on your posts).
897router.get('/notifications', requireSiteManager, (req, res) => {
898 const site = res.locals.site;
899 const items = site ? ActivityPubService.getNotifications(site.slug, 80) : [];
900 // viewing = seen → clears the bell badge. A viewer (kijker) may look but must not
901 // mutate state (the global write-guard only catches non-GET, not this GET-side effect).
902 if (site && !isViewer(req.session.user)) ActivityPubService.markNotificationsSeen(site.slug);
903 renderPage(req, res, 'pages/fedi-notifications', { pageTitle: 'Meldingen', bodyClass: 'on-special', items });
904});
905
906// Blocking / defederation (owner-only).
907router.get('/blocking', requireSiteManager, (req, res) => {
908 const site = res.locals.site;
909 const blocks = site ? ActivityPubService.listBlocks(site.slug) : [];
910 renderPage(req, res, 'pages/blocks', { pageTitle: 'Blokkeren', bodyClass: 'on-special', blocks, success: req.query.success || null, error: req.query.error || null });
911});
912
913router.post('/blocking/add', requireSiteManager, async (req, res) => {
914 const site = res.locals.site;
915 let q = 'success=' + encodeURIComponent('Geblokkeerd');
916 if (site) {
917 try {
918 const r = await ActivityPubService.blockTarget(site, (req.body.target || '').toString());
919 if (r && r.error) q = 'error=' + encodeURIComponent(r.error === 'not_found' ? 'Account niet gevonden' : 'Voer een @handle of domein in');
920 else q = 'success=' + encodeURIComponent(((r && r.label) || '') + ' geblokkeerd');
921 } catch (e) { q = 'error=' + encodeURIComponent('Blokkeren mislukt'); }
922 }
923 const ref = req.get('Referer') || '';
924 res.redirect((ref.includes('/news') ? '/news?' : '/blocking?') + q);
925});
926
927router.post('/blocking/remove', requireSiteManager, (req, res) => {
928 const site = res.locals.site;
929 if (site) { try { ActivityPubService.unblock(site, (req.body.target || '').toString()); } catch (e) { /* ignore */ } }
930 res.redirect('/blocking?success=' + encodeURIComponent('Deblokkeerd'));
931});
932
933// ==================== VIEW POST (last route — catches /:slug) ====================
934router.get('/:slug', (req, res, next) => {
935 if (RESERVED_SLUGS.has(req.params.slug)) return next();
936
937 const site = res.locals.site;
938 if (!site) return next(); // -> nette 404 catch-all
939
940 const post = db.prepare(`
941 SELECT p.*, u.username as author_username, u.avatar_url as author_avatar
942 FROM posts p JOIN users u ON p.author_id = u.id
943 WHERE p.site_id = ? AND p.slug = ?
944 `).get(site.id, req.params.slug);
945
946 if (!post) return next(); // unknown slug -> clean 404 catch-all
947
948 // Permission to view: published OR (logged in + can edit)
949 if (post.status !== 'published') {
950 const canEdit = req.session?.user && PermissionsService.canEditPost(req.session.user, post, site);
951 if (!canEdit) return res.status(403).send('Not published');
952 }
953
954 // Fan-only preview (premium #3): full content only for logged-in fans.
955 // Anonymous visitors get a clean login gate instead of the content (the title/
956 // teaser may still appear elsewhere as a teaser).
957 if (post.fan_only && !(req.session && req.session.user)) {
958 // Same Newer/Older navigation as on a normal post, so the visitor doesn't get
959 // stuck on the fan gate but can keep browsing.
960 const { newerPost, olderPost } = postNeighbors(site, post, res.locals.tenancy === 'hub');
961 return renderPage(req, res, 'pages/fan-gate', {
962 pageTitle: post.title || 'Alleen voor fans',
963 bodyClass: 'on-special',
964 fgTitle: post.title || '',
965 fgNext: (res.locals.siteUrlBase || '') + '/' + post.slug,
966 newerPost,
967 olderPost,
968 });
969 }
970
971 // Statistics: count the view (skips admins + unpublished own-preview).
972 if (post.status === 'published') recordPostView(post, req);
973
974 // Render content. Content is now user-authored HTML (already sanitized on
975 // save). The pipeline still adds autoembed iframes and shortcode embeds:
976 // stored HTML → autoembed → [[track]]/[[album]]/[[playlist]] → response
977 let html = post.content || '';
978 if (audioEnabled()) {
979 if (site.enable_audio_player !== 0) {
980 html = AudioEmbedService.autoembed(html);
981 html = AudioEmbedService.embedMediaShortcodes(html);
982 html = AudioEmbedService.embedExternalLinkShortcodes(html);
983
984 // Fetch any tracks referenced by [[track:id]] in this post.
985 // Cheap to do unconditionally — only matches if the post actually has shortcodes.
986 const trackIds = [...html.matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)].map(m => m[1]);
987 if (trackIds.length) {
988 const placeholders = trackIds.map(() => '?').join(',');
989 const rows = db.prepare(`
990 SELECT t.id, t.title, t.artist, t.cover_url, t.credit, t.license,
991 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
992 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
993 WHERE t.site_id = ? AND t.id IN (${placeholders})
994 `).all(site.id, ...trackIds);
995 const byId = new Map(rows.map(r => [r.id, r]));
996 html = AudioEmbedService.embedTrackShortcodes(html, (id) => {
997 const r = byId.get(id);
998 if (!r) return null;
999 return {
1000 id: r.id,
1001 title: r.title,
1002 artist: r.artist,
1003 cover: r.cover_url,
1004 credit: r.credit || '',
1005 license: r.license || '',
1006 link_spotify: r.link_spotify || '',
1007 link_youtube: r.link_youtube || '',
1008 link_soundcloud: r.link_soundcloud || '',
1009 url: r.filename ? audioUrl(r.filename) : '', // '' = link-only track
1010 };
1011 });
1012 }
1013
1014 // Album shortcodes: [[album:Some Album Name]]
1015 const albumNames = [...html.matchAll(/\[\[album:([^\]]+)\]\]/g)].map(m => m[1].trim());
1016 if (albumNames.length) {
1017 const placeholders = albumNames.map(() => '?').join(',');
1018 const albumRows = db.prepare(`
1019 SELECT t.id, t.title, t.artist, t.album, t.cover_url, t.position,
1020 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
1021 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
1022 WHERE t.site_id = ? AND t.album IN (${placeholders})
1023 ORDER BY t.position ASC, t.created_at ASC
1024 `).all(site.id, ...albumNames);
1025 const byAlbum = new Map();
1026 for (const r of albumRows) {
1027 // Link-only tracks (no file) remain in the album overview (url '').
1028 if (!byAlbum.has(r.album)) byAlbum.set(r.album, []);
1029 byAlbum.get(r.album).push({
1030 id: r.id,
1031 url: r.filename ? audioUrl(r.filename) : '',
1032 title: r.title || 'Untitled',
1033 artist: r.artist || '',
1034 cover: r.cover_url || '',
1035 link_spotify: r.link_spotify || '',
1036 link_youtube: r.link_youtube || '',
1037 link_soundcloud: r.link_soundcloud || '',
1038 });
1039 }
1040 html = AudioEmbedService.embedAlbumShortcodes(html, (name) => {
1041 const tracks = byAlbum.get(name);
1042 if (!tracks || !tracks.length) return null;
1043 return {
1044 title: name,
1045 artist: tracks[0].artist || '',
1046 cover: tracks[0].cover || '',
1047 tracks,
1048 };
1049 });
1050 }
1051
1052 // Playlist shortcodes: [[playlist:some-slug-id]] — first-class entity.
1053 // Editing the playlist propagates to every post that embeds it.
1054 const playlistIds = [...html.matchAll(/\[\[playlist:([a-z0-9][a-z0-9-]*)\]\]/gi)]
1055 .map(m => m[1].toLowerCase());
1056 if (playlistIds.length) {
1057 const isAdmin = req.session?.user?.role === 'god';
1058 html = AudioEmbedService.embedPlaylistShortcodes(html, (id) => {
1059 return PlaylistService.get(site.id, id, audioUrl);
1060 }, { isAdmin });
1061 }
1062 }
1063 } else {
1064 // LITE mode (KLONKT_AUDIO=off): no own audio (no ffmpeg/stream route).
1065 // External embeds (YouTube/SoundCloud/Spotify) remain; the own-audio
1066 // shortcodes ([[track]]/[[album]]/[[playlist]]) are cleanly stripped.
1067 html = AudioEmbedService.autoembed(html);
1068 html = AudioEmbedService.embedMediaShortcodes(html);
1069 html = AudioEmbedService.embedExternalLinkShortcodes(html);
1070 html = html.replace(/\[\[(track|album|playlist):[^\]]+\]\]/gi, '');
1071 }
1072 // Linkify inline #hashtags and bare URLs for on-site display — same rules as the
1073 // federated copy (buildNote). Was: only the Mastodon copy got links; the website
1074 // showed raw "#tag"/URL text. Idempotent, so editor links + embeds are untouched.
1075 html = ActivityPubService.linkifyBody('', html);
1076 post.content_html = html;
1077
1078 if (post.tags) {
1079 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
1080 } else {
1081 post.tags = [];
1082 }
1083
1084 // Native comments removed: social interaction is fediverse-only (see the
1085 // "From the fediverse" section below).
1086
1087 // Prev / next chronological (kept for back-compat — "post-nav" feature
1088 // below the article still uses these as a simple linear navigation).
1089 // Hub mode: Related posts + Newer/Older pull from ALL users (all sites),
1090 // newest first. Solo mode: within the current site (old behaviour).
1091 const isHub = res.locals.tenancy === 'hub';
1092 // Per-post URL base: in hub a link points to /user/<site-slug>/<post-slug>.
1093 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
1094
1095 // Newer/Older across ALL posts (shared helper — also used by the fan gate).
1096 const { newerPost, olderPost } = postNeighbors(site, post, isHub);
1097
1098 // ── Related posts: same-tag matching with recency fallback ─────
1099 // Fetch ~50 candidates, score by tag overlap, take top 3.
1100 // Excluding self via `id != ?`.
1101 const candidates = isHub
1102 ? db.prepare(`
1103 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
1104 FROM posts p JOIN sites s ON s.id = p.site_id
1105 WHERE p.status = 'published' AND p.id != ?
1106 ORDER BY p.published_at DESC LIMIT 50
1107 `).all(post.id)
1108 : db.prepare(`
1109 SELECT id, slug, title, cover_image_url, cover_video_url, published_at, tags, nsfw, content_warning
1110 FROM posts
1111 WHERE site_id = ? AND status = 'published' AND id != ?
1112 ORDER BY published_at DESC LIMIT 50
1113 `).all(site.id, post.id);
1114
1115 // Parse tags JSON safely; missing/malformed → empty array.
1116 const parseTags = (raw) => {
1117 if (!raw) return [];
1118 try {
1119 const v = JSON.parse(raw);
1120 return Array.isArray(v) ? v.map(String) : [];
1121 } catch { return []; }
1122 };
1123
1124 const myTags = new Set(parseTags(post.tags));
1125 let relatedPosts;
1126 if (myTags.size > 0) {
1127 // Score = number of overlapping tags. Posts with zero overlap are
1128 // included only if we don't have 3 with-overlap candidates.
1129 const scored = candidates.map(p => {
1130 const theirTags = parseTags(p.tags);
1131 const overlap = theirTags.reduce((n, t) => n + (myTags.has(t) ? 1 : 0), 0);
1132 return { ...p, _overlap: overlap };
1133 });
1134 const withOverlap = scored.filter(p => p._overlap > 0)
1135 .sort((a, b) => b._overlap - a._overlap || new Date(b.published_at) - new Date(a.published_at));
1136 if (withOverlap.length >= 3) {
1137 relatedPosts = withOverlap.slice(0, 3);
1138 } else {
1139 // Pad with most-recent non-overlap posts so the section is never empty
1140 const overlapIds = new Set(withOverlap.map(p => p.id));
1141 const filler = candidates.filter(p => !overlapIds.has(p.id));
1142 relatedPosts = [...withOverlap, ...filler].slice(0, 3);
1143 }
1144 } else {
1145 // No tags on current post → just show 3 most-recent
1146 relatedPosts = candidates.slice(0, 3);
1147 }
1148 // Strip the internal _overlap field before sending to view
1149 relatedPosts = relatedPosts.map(({ _overlap, tags, ...rest }) => ({ ...rest, _urlBase: urlBaseFor(rest) }));
1150
1151 // Inbound fediverse activity (threaded) for this post.
1152 let fediverse = { thread: [], likeCount: 0, announceCount: 0, total: 0 };
1153 try {
1154 const _apBase = (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
1155 fediverse = ActivityPubService.getInteractions(post.id, _apBase, site);
1156 // Stale-while-revalidate: render from cache now; refresh the remote thread in the
1157 // background (TTL-gated, non-blocking) so undelivered replies-to-replies fill in next view.
1158 if (res.locals.apEnabled !== false) ActivityPubService.maybeCrawlThread(post.id);
1159 } catch { /* non-fatal */ }
1160 // Owner/admin of this site may reply back to a fediverse interaction.
1161 const canManageSite = !!(req.session?.user && PermissionsService.canAdminSite(req.session.user, site));
1162 // Avatar for our own (outbound) fediverse replies = the site's profile photo.
1163 const siteAvatar = (site && site.profile_photo) ? site.profile_photo : null;
1164
1165 renderPage(req, res, 'pages/post', {
1166 post,
1167 poll: ActivityPubService.ownPollView(post),
1168 newerPost,
1169 olderPost,
1170 relatedPosts,
1171 fediverse,
1172 canManageSite,
1173 siteAvatar,
1174 postHasPlayableAudio: ActivityPubService.hasPlayableAudio(post.content || '', site.id),
1175 musicLd: MusicMeta.build((process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, ''), site, post),
1176 pageTitle: post.title + ' - ' + site.title,
1177 socialDescr: post.excerpt || '',
1178 socialImage: post.cover_image_url || '',
1179 bodyClass: 'on-post',
1180 });
1181});
1182
1183// ── Reply back to a fediverse interaction (site owner/admin only) ──
1184router.post('/posts/:slug/fedi-reply', requireSiteManager, async (req, res) => {
1185 const site = res.locals.site;
1186 if (!site) return res.status(404).send('Site required');
1187 const post = db.prepare('SELECT id, slug FROM posts WHERE site_id = ? AND slug = ?').get(site.id, req.params.slug);
1188 if (!post) return res.status(404).send('Not found');
1189 const parent = ActivityPubService.getInteractionById(req.body.interaction_id);
1190 const text = (req.body.text || '').toString();
1191 if (parent && parent.post_id === post.id && text.trim()) {
1192 try {
1193 await ActivityPubService.deliverReply(site, { postId: post.id, postSlug: post.slug, parent, text });
1194 } catch (e) { console.warn('[AP] reply send failed:', e.message); }
1195 }
1196 res.redirect(`${res.locals.siteUrlBase || ''}/${post.slug}#fediverse`);
1197});
1198
1199// Owner likes/boosts a fediverse comment on their own post — directly as the
1200// site, no "your server" detour (mirrors /fedi-reply).
1201router.post('/posts/:slug/fedi-react', requireSiteManager, async (req, res) => {
1202 const site = res.locals.site;
1203 if (!site) return res.status(404).send('Site required');
1204 const post = db.prepare('SELECT id, slug FROM posts WHERE site_id = ? AND slug = ?').get(site.id, req.params.slug);
1205 if (!post) return res.status(404).send('Not found');
1206 const parent = ActivityPubService.getInteractionById(req.body.interaction_id);
1207 const kind = req.body.kind === 'boost' ? 'boost' : 'like';
1208 if (parent && parent.post_id === post.id && parent.object_uri) {
1209 if (kind === 'boost') {
1210 // Toggle: boost an unboosted comment, or retract it (Undo Announce) if already boosted.
1211 const on = !parent.acted_boost;
1212 ActivityPubService.sendInteraction(site, on ? 'boost' : 'unboost', parent.object_uri, parent.actor_uri)
1213 .catch((e) => console.warn('[AP] reaction failed:', e.message));
1214 ActivityPubService.setInteractionBoosted(parent.id, on);
1215 } else {
1216 // Toggle: like an unliked comment, or un-favourite (Undo Like) if already liked.
1217 const on = !parent.acted_like;
1218 ActivityPubService.sendInteraction(site, on ? 'like' : 'unlike', parent.object_uri, parent.actor_uri)
1219 .catch((e) => console.warn('[AP] reaction failed:', e.message));
1220 ActivityPubService.setInteractionLiked(parent.id, on);
1221 }
1222 }
1223 res.redirect(`${res.locals.siteUrlBase || ''}/${post.slug}#fediverse`);
1224});
1225
1226export default router;
1227export { postNeighbors };
Note: See TracBrowser for help on using the repository browser.