source: Klonkt/src/routes/posts.js@ 837fc9c

main
Last change on this file since 837fc9c was 837fc9c, checked in by Robin Genis <roboburr@…>, 2 months ago

feat(posts): NSFW / sensitive content

Mark a post NSFW (checkbox in the editor, available to all). On-site the cover blurs in
feed/grid and the whole post blurs behind a 'Gevoelige inhoud' banner until clicked. In the
fediverse the Note gets sensitive:true + a content-warning summary (Mastodon CW). i18n NL/EN/DE.

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