source: Klonkt/src/routes/posts.js@ 0688b5f

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

feat(fediverse): post language → AS2 contentMap

A post can now carry a language; it federates as an AS2 contentMap (a BCP-47-keyed
copy of the content, alongside plain content) so Mastodon's timeline language filter
and translate button work. Editor gets a language picker (defaults to the author's
UI language).

  • src/config/database.js — posts.language column.
  • src/services/ActivityPubService.js — buildNote emits contentMap { <lang>: content } when the post has a valid BCP-47 language.
  • src/routes/posts.js — capture/validate/store language on create/save (default = the author's current language) and pass it to the federation hooks.
  • src/services/Scheduler.js — carry language when a scheduled post goes live.
  • src/views/pages/post-edit.ejs — language <select> (18 common languages).
  • src/services/i18n.js — pedit.f_language + pedit.language_hint (nl/en/de).
  • test/activitypub-as2.test.js — allow contentMap/nameMap/summaryMap; don't treat a language-map's keys as vocab terms; kitchen-sink post now sets a language.
  • test/post-language.test.js — contentMap shape, no-language, invalid-code = ignored.
  • CHANGELOG(.nl/.de).md — "Set a post's language" under Unreleased.

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

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