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

main
Last change on this file since f2eacca was 328d837, checked in by roboburr <roboburr@…>, 2 months ago

feat(music): schema.org MusicRecording/MusicAlbum structured data on audio posts (music federation Fase 1)

An audio post now emits standard schema.org MusicRecording (single track) or MusicAlbum
(album/playlist) JSON-LD alongside the existing Article data — a real web standard read by
search engines and generic JSON-LD consumers, NOT a Klonkt-invented field. The url points
to the gated player page, so the anti-steal posture is unchanged. The track-resolution helper
is the reusable base for the (future) Funkwhale Audio/Library federation (Fase 2).

  • src/services/MusicMeta.js (new) — resolves a post's track/album/playlist shortcodes to hosted tracks and builds a schema.org MusicRecording/MusicAlbum (name, byArtist=MusicGroup, inAlbum, ISO-8601 duration, license, creditText, image, url)
  • src/routes/posts.js — passes a musicLd local on the post page
  • src/views/shell.ejs — renders a second ld+json script for music posts (Article kept intact)

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

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