source: Klonkt/src/routes/posts.js@ 757eea0

main
Last change on this file since 757eea0 was e0a1ec1, checked in by roboburr <roboburr@…>, 2 months ago

feat(editor): per-post "share audio on the fediverse" toggle

Adds a per-post checkbox in the post editor that sets fedi_open on the post's hosted tracks
on save — so opening audio + federating it happens in one step, instead of toggling per track
in Beheer -> Audio and then re-saving the post. The underlying flag stays per track.

  • src/routes/posts.js — setAudioFediOpen()/postAudioFediOpen() helpers; create + save set fedi_open on the post's track/album/playlist tracks before federating; the edit form computes the checkbox's initial state
  • src/views/pages/post-edit.ejs — the fedi_open_audio checkbox next to NSFW/noindex
  • src/services/i18n.js — pedit.fedi_audio_label (nl/en/de)

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

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