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

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

feat(fediverse): alt text for images (accessibility → AS2 attachment name)

Media federated to the fediverse now carries a description (AS2 name on the
attachment), which Mastodon shows and screen readers read. The cover gets an alt
field in the editor; inline images keep their own <img alt="…">. Also used as the
cover's on-site alt.

  • src/config/database.js — posts.cover_alt column.
  • src/services/ActivityPubService.js — buildNote carries alt per media URL (cover_alt + inline <img alt>) and emits it as the attachment name (and on the image fallback).
  • src/routes/posts.js — capture/store cover_alt on create/save and pass it to the federation hooks.
  • src/services/Scheduler.js — carry cover_alt when a scheduled post goes live.
  • src/views/pages/post-edit.ejs — "Alt text (description)" field under the cover URL.
  • src/views/pages/post.ejs — the on-page cover <img> uses cover_alt.
  • src/services/i18n.js — pedit.f_cover_alt + pedit.cover_alt_placeholder (nl/en/de).
  • test/media-alt.test.js — cover alt, inline alt, and no-alt = no name.
  • CHANGELOG(.nl/.de).md — "Alt text for images" under Unreleased.

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

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