source: Klonkt/src/routes/posts.js@ 89cc8c4

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

fix(related): blur NSFW covers in the Related Posts section

The related-posts grid on a post page didn't blur sensitive covers. Now it selects nsfw +
content_warning and renders the same click-to-reveal veil as the feed/grid/Circle cards.

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