source: Klonkt/src/routes/posts.js@ 92a2c46

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

Fix: three UI nits (interact page title i18n, Apple icon, stats columns)

  1. authorize_interaction page title was hardcoded Dutch ('Interacteer via de fediverse'); both renders now use pageTitleKey (fedi.remote_interact / fedi.manage_title) so the tab title follows the interface language. Verified: an English UI now titles 'Interact via the fediverse'.
  2. The Apple Music platform icon was a garbled path that did not read as the Apple logo; replaced with the classic Apple mark. Verified visually at 96px.
  3. Stats chart columns jumped in the 30/90-day views: unlabeled .sc-day spans collapsed to 0 height. Unlabeled columns now hold an NBSP (Bart's suggestion) so every column keeps its label line. Verified: 30-day view has one unique bar baseline and uniform label heights; 90-day has 0 empty spans.

Reported by Bart.

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

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