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

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

feat(fediverse): host your own polls (federate as AS2 Question)

A post can carry a poll that federates as an AS2 Question so remote (Mastodon)
followers vote from their own app; votes are tallied server-side and the fresh
counts are pushed back as Update(Question). Voting is fediverse-only; the site
shows live, read-only results. Complements the existing inbound poll support.

  • src/config/database.js — posts.poll_json (our poll definition) + poll_votes table (post_id, actor_uri, choice; UNIQUE) backing the tally + per-actor dedupe.
  • src/services/ActivityPubService.js — parseOwnPoll/pollTally/ownPollView helpers; buildNote emits a Question (oneOf/anyOf + replies.totalItems + endTime/closed + votersCount) for a poll post; handleInbox records a ballot (Note with name + inReplyTo our poll) before the reply path, deduped per actor; a debounced Update(Question) pushes fresh counts to followers; votersCount added to AP_CONTEXT.
  • src/services/Scheduler.js — closeExpiredPolls() marks a poll closed once its endTime passes and pushes the final tally; runs on the existing 60s tick.
  • src/routes/posts.js — parsePollForm() turns the editor fields into poll_json on create/save (a poll with votes is frozen), passes poll_json to the federation hooks, and hands the post page a render-ready ownPollView.
  • src/views/pages/post-edit.ejs — poll section (options, multiple-choice, duration); disabled once the poll has votes.
  • src/views/pages/post.ejs — display-only poll with result bars + voter/close meta.
  • src/services/i18n.js — poll.* + pedit.poll_* strings (nl/en/de).
  • test/polls.test.js — Question shape, tally, percentages, closed state, AS2 term.
  • CHANGELOG(.nl/.de).md — "Create your own polls" under Unreleased.

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

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