source: Klonkt/src/routes/posts.js@ 80c36a1

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

feat(fedi): fans-only = followers-only federation (option A)

A fan_only post now federates to your followers but addressed followers-only (to:
followers, no Public) so only they see it in their feed and it can't be boosted public.
buildNote sets the audience from post.fan_only; create/save/scheduler/delete hooks no
longer skip fan_only (they pass fan_only through). The public outbox still excludes
fan_only, and the on-site fan-gate is unchanged (so it stays hidden on the site).

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