source: Klonkt/src/routes/posts.js@ e685f55

main
Last change on this file since e685f55 was d48ea02, checked in by Robin <roboburr@…>, 7 weeks ago

Fix: paid gate wins from the fan gate (no more login page on paid posts)

A post that is both fan_only and paid sent anonymous visitors to the
fan login gate, because the fan gate was checked first. They never saw
the unlock button. A paid post unlocks with a passkey, not with a
Klonkt-login, so the paid gate now runs first; the fan gate stays as-is
for posts that are only fan_only.

Changed files:
src/routes/posts.js

  • paid-gate block moved above the fan-gate block, comment explains the order

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

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