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

main
Last change on this file since 0202104 was 0202104, checked in by Robin Genis <roboburr@…>, 6 weeks ago

De gebruikerskant van 3.6: de ward ziet zijn vangnet, de guardian handelt

Drie oppervlakken rondgemaakt op de beschikbaarheid die er sinds vanmorgen
server-side in zit.

Berichten (de ward): de guardians-balk toont per guardian de buddy-list-stip
met het label erbij: beschikbaar, afwezig tot een datum, offline. Het kind ziet
de echte omvang van zijn vangnet, niet alleen de namen. Owner-only omdat de
pagina dat is.

De Guardian-PWA (de guardian): in het paneel per kind staan de mede-guardians
met dezelfde stippen; op een slapende verschijnt de bewuste, zeldzame
vervolgstap "Voorstel: loslaten bij afwezigheid", die langs dezelfde
C2S-pijplijn loopt als de Shaer-apps (Offer van shaer:Lapse, lokaal ward opent
direct, remote ward krijgt het voorstel bezorgd). Lopende lapses staan als
kaart bij de aanvragen, met Eens/Oneens over de bestaande offer-draad en de zin
die het frame bewaakt. En "Even afwezig": een week of een maand, een directe
note met shaer:away naar alle wards, lokaal direct toegepast.

Shaer (beide apps): de lapse-kaart toont stemknoppen alleen aan leden van de
set. De ward kijkt mee naar wat zijn guardians beslissen; het is daar niet de
rechter, om precies de reden uit de editor's note van 3.6.3.

Onderweg gerepareerd: parseStamp kende alleen strings, waardoor een epoch-ms
endTime als lege datum rendde ("unavailable till" zonder datum).

Changed files:
src/routes/posts.js

  • /messages geeft de guardians hun beschikbaarheid mee

src/views/pages/messages.ejs

  • de stip en het label per guardian, met de opmaak erbij

src/routes/guardian.js

  • dashboardState: mede-guardians met status per lokaal kind, plus lapses
  • POST /guardian/api/away en /guardian/api/lapse
  • de nieuwe labels in uiStrings

src/assets/js/guardian.js

  • de guardians-sectie in het paneel, de lapse-kaart, de afwezig-knoppen

src/views/pages/guardian.ejs

  • de "Even afwezig"-sectie

src/assets/css/guardian.css

  • de stippen en de lapse-kaart

src/middleware/render.js

  • parseStamp accepteert epoch ms

src/services/i18n.js

  • de labels en teksten in nl, en, de

remarks: end-to-end in de browser nagelopen op de wegwerp-database: het kind
ziet oma afwezig-tot, opa offline en guard beschikbaar; de guardian opent het
paneel, stelt de lapse voor op de slapende opa (kaart verschijnt, eigen stem
geteld), drukt "A week", en bij het kind staat guard meteen op afwezig tot
5 augustus. 276 tests groen. Niet uitgerold.

-robo
Co-Authored-By: Claude Fable 5 <noreply@…>

  • Property mode set to 100644
File size: 75.3 KB
Line 
1import express from 'express';
2import { v4 as uuid } from 'uuid';
3import path from 'path';
4import fs from 'fs';
5import { fileURLToPath } from 'url';
6import multer from 'multer';
7import ejs from 'ejs';
8import db from '../config/database.js';
9import { requireAuth, requireSiteManager, isViewer } from '../middleware/auth.js';
10import { renderPage } from '../middleware/render.js';
11import { recordPageview, recordPostView } from '../services/StatsService.js';
12import PermissionsService from '../services/PermissionsService.js';
13import MarkdownService from '../services/MarkdownService.js';
14import HtmlSanitizerService from '../services/HtmlSanitizerService.js';
15import AudioEmbedService from '../services/AudioEmbedService.js';
16import PlaylistService from '../services/PlaylistService.js';
17import { audioEnabled } from '../config/features.js';
18import { audioUrl } from '../services/AudioStreamService.js';
19import { toWebp } from '../services/ImageWebpService.js';
20import VideoCoverService from '../services/VideoCoverService.js';
21import ActivityPubService from '../services/ActivityPubService.js';
22import * as Guardianship from '../services/guardianship/index.js';
23import { premiumUnlocked } from '../services/PatreonService.js';
24import { defaultMinCents as paidDefaultMinCents, patreonUrl as paidPatronUrl } from '../services/PaidPatreonService.js';
25import { verifyBlob } from '../services/CryptoBox.js';
26import MusicMeta from '../services/MusicMeta.js';
27
28const __dirname = path.dirname(fileURLToPath(import.meta.url));
29const POST_IMAGES_DIR = path.resolve(
30 process.env.POST_IMAGES_PATH ||
31 path.join(__dirname, '..', '..', 'storage', 'media', 'post-images')
32);
33fs.mkdirSync(POST_IMAGES_DIR, { recursive: true });
34
35const ALLOWED_IMAGE_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
36const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
37
38// Rich replies: media dropped/pasted into the reply editor. Images, audio and
39// video, stored as-is (no transcode; a reply attachment is not a track).
40const REPLY_MEDIA_DIR = path.resolve(
41 process.env.REPLY_MEDIA_PATH ||
42 path.join(__dirname, '..', '..', 'storage', 'media', 'reply-media')
43);
44fs.mkdirSync(REPLY_MEDIA_DIR, { recursive: true });
45const ALLOWED_REPLY_MEDIA_EXT = new Set([
46 '.jpg', '.jpeg', '.png', '.webp', '.gif',
47 '.mp3', '.m4a', '.ogg', '.opus', '.flac', '.wav',
48 '.mp4', '.webm', '.mov',
49]);
50const MAX_REPLY_MEDIA_BYTES = 32 * 1024 * 1024;
51const replyMediaUpload = multer({
52 storage: multer.diskStorage({
53 destination: (req, file, cb) => cb(null, REPLY_MEDIA_DIR),
54 filename: (req, file, cb) => cb(null, `${uuid()}${path.extname(file.originalname).toLowerCase()}`),
55 }),
56 limits: { fileSize: MAX_REPLY_MEDIA_BYTES },
57 fileFilter: (req, file, cb) => {
58 const ext = path.extname(file.originalname).toLowerCase();
59 if (!ALLOWED_REPLY_MEDIA_EXT.has(ext)) return cb(new Error('Media must be an image, audio or video file'));
60 cb(null, true);
61 },
62});
63
64const imageStorage = multer.diskStorage({
65 destination: (req, file, cb) => cb(null, POST_IMAGES_DIR),
66 filename: (req, file, cb) => {
67 const ext = path.extname(file.originalname).toLowerCase();
68 cb(null, `${uuid()}${ext}`);
69 },
70});
71const imageUpload = multer({
72 storage: imageStorage,
73 limits: { fileSize: MAX_IMAGE_BYTES },
74 fileFilter: (req, file, cb) => {
75 const ext = path.extname(file.originalname).toLowerCase();
76 if (!ALLOWED_IMAGE_EXT.has(ext)) {
77 return cb(new Error('Image must be jpg/png/webp/gif'));
78 }
79 cb(null, true);
80 },
81});
82
83// Generates a unique slug within the site: 'title', 'title-2', 'title-3', …
84// A second post with the same title is NOT rejected ("already exists"),
85// but automatically gets a free suffix. exceptId = the post being updated
86// (allowed to keep its own slug).
87function uniqueSlug(siteId, base, exceptId = null) {
88 let candidate = base;
89 let n = 2;
90 for (;;) {
91 const row = exceptId
92 ? db.prepare('SELECT id FROM posts WHERE site_id = ? AND slug = ? AND id != ?').get(siteId, candidate, exceptId)
93 : db.prepare('SELECT id FROM posts WHERE site_id = ? AND slug = ?').get(siteId, candidate);
94 if (!row) return candidate;
95 candidate = `${base}-${n++}`;
96 }
97}
98
99const router = express.Router();
100
101// Feed page size for "Load more" (Solo, News, Messages, Cirkel). 72 is divisible
102// by 2/3/4 so every grid column count ends on a full row.
103const FEED_PAGE = 72;
104
105// ==================== UPLOAD IMAGE (cover or content) ====================
106// Returns JSON {url} so the editor can stick it into the cover field or
107// insert a markdown ![](url) into content.
108router.post('/posts/upload-image', requireAuth, (req, res) => {
109 imageUpload.single('image')(req, res, async (err) => {
110 if (err) return res.status(400).json({ error: err.message });
111 if (!req.file) return res.status(400).json({ error: 'No file' });
112 const name = toWebp(req.file);
113 const url = '/media/post-images/' + name;
114 // An animated WebP cover → also make a muted loop MP4 (Safari plays it smoothly where the
115 // animated WebP is janky on iOS). Best-effort; on failure we just return the still image.
116 // The editor stores `video` in the hidden cover_video_url field for the cover.
117 let video = null;
118 try {
119 const src = path.join(POST_IMAGES_DIR, name);
120 if (VideoCoverService.isAnimatedWebp(src)) {
121 const r = await VideoCoverService.animatedWebpToVideo(src, POST_IMAGES_DIR, path.basename(name, path.extname(name)) + '-v');
122 if (r) video = '/media/post-images/' + path.basename(r.videoPath);
123 }
124 } catch { /* keep the still image */ }
125 res.json({ url, video, size: req.file.size, mime: req.file.mimetype });
126 });
127});
128
129// Rich replies: media for a reply (image/audio/video). Returns { url, mediaType, name }
130// exactly as the editor's attachments JSON wants it; deliverReply re-validates.
131router.post('/posts/upload-reply-media', requireSiteManager, (req, res) => {
132 replyMediaUpload.single('media')(req, res, (err) => {
133 if (err) return res.status(400).json({ error: err.message });
134 if (!req.file) return res.status(400).json({ error: 'No file' });
135 const mime = String(req.file.mimetype || '');
136 if (!/^(image|audio|video)\//.test(mime)) {
137 try { fs.unlinkSync(req.file.path); } catch { /* best effort */ }
138 return res.status(400).json({ error: 'Media must be an image, audio or video file' });
139 }
140 res.json({
141 url: '/media/reply-media/' + req.file.filename,
142 mediaType: mime,
143 name: String(req.file.originalname || '').slice(0, 120),
144 });
145 });
146});
147
148const RESERVED_SLUGS = new Set([
149 'auth', 'admin', 'login', 'register', 'logout',
150 'archive', 'search', 'account', 'sites', 'comments',
151 'posts', 'media', 'audio', 'forum',
152 'tag', 'type', 'user', 'users', 'artiesten', 'leden', 'favorieten', 'feed.xml', 'atom.xml', 'sitemap.xml',
153 'manifest.webmanifest', 'sw.js', 'favicon.ico', 'favicon.svg', 'assets',
154 'authorize_interaction', 'fediverse', 'news', 'following', 'notifications', 'blocking',
155 'paid', 'push', 'guardian',
156]);
157
158/**
159 * Parse the form's `pinned` field into a non-negative integer rank.
160 * Empty / undefined / NaN / negative → 0 (= not pinned).
161 * Otherwise: integer rank (1 = top of pinned stack, 2 = below, ...).
162 *
163 * Multiple posts CAN share the same rank — UI shows them tiebroken by
164 * published_at DESC. Saying #2 twice doesn't error, it just duplicates.
165 * (We don't enforce uniqueness at this layer because race conditions and
166 * "swap two ranks" workflows are easier without a UNIQUE constraint.)
167 */
168function parsePinnedRank(raw) {
169 const n = parseInt(raw, 10);
170 if (!Number.isFinite(n) || n < 0) return 0;
171 return n;
172}
173
174// Poll durations offered in the editor (seconds) — the Mastodon set (5m … 7d).
175const POLL_DURATIONS = new Set([300, 1800, 3600, 21600, 43200, 86400, 259200, 604800]);
176// Parse the editor's poll fields into the poll_json we store on the post (which
177// buildNote federates as an AS2 Question). Returns null when no valid poll (< 2
178// options or the poll checkbox is off). endTime is set from the chosen duration
179// (default 1 day) so the Scheduler can close it.
180function parsePollForm(body) {
181 if (!body || !body.poll_enabled) return null;
182 const raw = body.poll_option == null ? [] : (Array.isArray(body.poll_option) ? body.poll_option : [body.poll_option]);
183 const options = [];
184 const seen = new Set();
185 for (const o of raw) {
186 const name = String(o == null ? '' : o).trim().slice(0, 100);
187 if (!name) continue;
188 const key = name.toLowerCase();
189 if (seen.has(key)) continue; seen.add(key);
190 options.push({ name });
191 if (options.length >= 8) break;
192 }
193 if (options.length < 2) return null;
194 const dur = parseInt(body.poll_duration, 10);
195 const secs = POLL_DURATIONS.has(dur) ? dur : 86400;
196 return JSON.stringify({ multiple: !!body.poll_multiple, options, endTime: new Date(Date.now() + secs * 1000).toISOString(), closed: false });
197}
198
199// ==================== HOME (Posts list) ====================
200router.get('/', (req, res) => {
201 const site = res.locals.site;
202
203 if (!site) {
204 return renderPage(req, res, 'pages/welcome', {
205 pageTitle: 'Welcome',
206 bodyClass: 'on-special',
207 });
208 }
209
210 // Pinned first — ordered by their rank (1 = top, 2 = below, etc).
211 // pinned column is now an integer rank: 0 = not pinned, 1+ = pinned at
212 // that position. Older boolean usage where pinned was always 1 still
213 // works because integer ranks 1, 2, 3 sort the same as a flat 1.
214 const pinnedPosts = db.prepare(`
215 SELECT p.*, u.username as author_username
216 FROM posts p JOIN users u ON p.author_id = u.id
217 WHERE p.site_id = ? AND p.status = 'published' AND p.pinned > 0
218 ORDER BY p.pinned ASC, p.published_at DESC
219 `).all(site.id);
220
221 // Regular posts: anything with pinned = 0. Paged in blocks of 72 (Load more).
222 const append = req.query.append === '1';
223 const offset = Math.max(0, parseInt(req.query.offset, 10) || 0);
224 const rows = db.prepare(`
225 SELECT p.*, u.username as author_username
226 FROM posts p JOIN users u ON p.author_id = u.id
227 WHERE p.site_id = ? AND p.status = 'published' AND p.pinned = 0
228 ORDER BY p.published_at DESC
229 LIMIT ? OFFSET ?
230 `).all(site.id, FEED_PAGE + 1, offset);
231 const hasMore = rows.length > FEED_PAGE;
232 const posts = rows.slice(0, FEED_PAGE);
233 const moreBase = res.locals.siteUrlBase || '';
234
235 if (append) {
236 return renderPage(req, res, 'partials/home-append', { posts, hasMore, nextOffset: offset + FEED_PAGE, moreBase });
237 }
238
239 recordPageview(site.id, req);
240
241 renderPage(req, res, 'pages/home', {
242 pinnedPosts,
243 posts,
244 hasMore, nextOffset: offset + FEED_PAGE, moreBase,
245 pageTitle: site.title,
246 socialDescr: site.description || site.tagline || '',
247 bodyClass: 'on-home',
248 });
249});
250
251// ==================== NEW POST FORM ====================
252router.get('/posts/new', requireAuth, (req, res) => {
253 const site = res.locals.site;
254 if (!site) return res.status(404).send('Site required');
255 if (!PermissionsService.canCreatePost(req.session.user, site)) {
256 return res.status(403).send('No permission');
257 }
258
259 renderPage(req, res, 'pages/post-edit', {
260 post: {
261 id: uuid(),
262 title: '', slug: '', content: '', excerpt: '',
263 status: 'draft', pinned: 0, tags: [],
264 cover_image_url: '',
265 },
266 isNew: true,
267 pageTitle: 'New post',
268 bodyClass: 'on-special',
269 });
270});
271
272// ==================== CREATE POST ====================
273// ── Per-post audio federation ──────────────────────────────────────────────
274// "Share audio on the fediverse" is a per-post choice in the editor, but the underlying
275// flag is per track (audio_tracks.fedi_open — it gates the file + drives the AS2 Audio
276// attachment). NB: the file gate is per file, so opening a track in one post makes its file
277// fetchable for every post that reuses it.
278// ONE-WAY: opening is permanent. Once the file has federated it's out there — re-gating
279// would be false security (remote copies keep the URL), so we never write fedi_open back to 0.
280function setAudioFediOpen(siteId, content, open) {
281 if (!open) return; // never close — see one-way note above
282 const c = content || '';
283 try {
284 for (const m of c.matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)) db.prepare('UPDATE audio_tracks SET fedi_open = 1 WHERE id = ? AND site_id = ?').run(m[1], siteId);
285 for (const m of c.matchAll(/\[\[album:([^\]]+)\]\]/g)) db.prepare('UPDATE audio_tracks SET fedi_open = 1 WHERE site_id = ? AND album = ?').run(siteId, m[1].trim());
286 for (const m of c.matchAll(/\[\[playlist:([A-Za-z0-9_-]+)\]\]/g)) db.prepare('UPDATE audio_tracks SET fedi_open = 1 WHERE id IN (SELECT track_id FROM playlist_tracks WHERE playlist_id = ?)').run(m[1]);
287 } catch { /* non-fatal */ }
288}
289// True when the post references hosted audio AND all of it is currently fedi_open (drives the
290// editor checkbox's initial state).
291function postAudioFediOpen(siteId, content) {
292 const c = content || '';
293 if (!/\[\[(track|album|playlist):/i.test(c)) return false;
294 let total = 0, open = 0;
295 const tally = (r) => { if (r && r.media_id) { total++; if (r.fedi_open) open++; } };
296 try {
297 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));
298 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);
299 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);
300 } catch { /* non-fatal */ }
301 return total > 0 && open === total;
302}
303
304// Bake + cache a post's display HTML (ActivityPub `source` model): `content` stays the raw
305// source (used by the editor + re-rendering), content_rendered holds the linkified render the
306// page serves. Called after every create/edit. Non-fatal: the render route falls back to
307// baking on the fly if this ever fails.
308function cacheRenderedContent(postId, rawContent) {
309 const raw = rawContent || '';
310 // 1. Immediate + synchronous: bake #hashtags + URLs so the post renders enriched at once.
311 try {
312 db.prepare('UPDATE posts SET content_rendered = ? WHERE id = ?')
313 .run(ActivityPubService.bakePostContent(raw), postId);
314 } catch (e) { /* fallback bake in the render route keeps display correct */ }
315 // 2. Async: resolve @mentions (webfinger, once) and re-store, WITHOUT blocking the save
316 // response — a moment later the post's @mentions are clickable too. A slow/dead remote
317 // server can't stall the save; on failure the sync bake from step 1 stands.
318 ActivityPubService.bakePostContentWithMentions(raw)
319 .then((html) => {
320 try { db.prepare('UPDATE posts SET content_rendered = ? WHERE id = ?').run(html, postId); }
321 catch (e) { /* keep the sync bake */ }
322 })
323 .catch(() => { /* keep the sync bake */ });
324}
325
326router.post('/posts/create', requireAuth, (req, res) => {
327 const site = res.locals.site;
328 if (!site || !PermissionsService.canCreatePost(req.session.user, site)) {
329 return res.status(403).send('No permission');
330 }
331
332 const { title, slug, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
333 const fanOnly = req.body.fan_only ? 1 : 0;
334 const paid = (premiumUnlocked() && req.body.paid) ? 1 : 0; // paid posts (klonkt-demo-aki)
335 const paidEur = String(req.body.paid_min_eur || '').replace(',', '.').trim();
336 const paidMinCents = paid && paidEur ? Math.round(parseFloat(paidEur) * 100) : null;
337 const nsfw = req.body.nsfw ? 1 : 0;
338 const cw = (req.body.content_warning || '').trim().slice(0, 200);
339 const coverAlt = (req.body.cover_alt || '').trim().slice(0, 1500) || null; // cover alt text (a11y)
340 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
341
342 // Content arrives as user-authored HTML from the WYSIWYG editor — sanitize
343 // before storage. Shortcode text tokens like [[track:UUID]] live in text
344 // nodes and pass through untouched.
345 const cleanContent = HtmlSanitizerService.sanitize(content || '');
346
347 // Generate slug from title if empty
348 let finalSlug = (slug || title || '')
349 .toLowerCase()
350 .replace(/[^a-z0-9]+/g, '-')
351 .replace(/^-|-$/g, '');
352
353 if (!finalSlug) return res.status(400).send('Title or slug required');
354 if (RESERVED_SLUGS.has(finalSlug)) finalSlug = `${finalSlug}-post`;
355
356 // Duplicate title/slug? Make it unique automatically (title-2, title-3, …) instead of rejecting.
357 finalSlug = uniqueSlug(site.id, finalSlug);
358
359 const validTypes = new Set(['post', 'foto', 'video', 'audio']);
360 const finalType = validTypes.has(type) ? type : 'post';
361 const pollJson = parsePollForm(req.body); // AS2 Question definition, or null
362 const postId = uuid();
363 const now = new Date().toISOString();
364 let finalStatus = status || 'draft';
365 let publishedAt = finalStatus === 'published' ? now : null;
366 // Release planning: published + a future publish_at -> 'scheduled'
367 // (the Scheduler makes it live at that moment). Past/empty -> live immediately.
368 let publishAt = null;
369 const pa = Date.parse(req.body.publish_at || '');
370 if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
371 finalStatus = 'scheduled';
372 publishAt = new Date(pa).toISOString();
373 publishedAt = null;
374 }
375
376 db.prepare(`
377 INSERT INTO posts (
378 id, site_id, slug, author_id, title, content, excerpt,
379 status, cover_image_url, cover_video_url, cover_alt, language, pinned, tags, type, noindex, fan_only, nsfw, content_warning, poll_json, publish_at,
380 created_at, updated_at, published_at
381 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
382 `).run(
383 postId, site.id, finalSlug, req.session.user.id,
384 title || finalSlug, cleanContent, excerpt || '',
385 finalStatus, cover_image_url || null, (req.body.cover_video_url || null), coverAlt, language, parsePinnedRank(pinned),
386 JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
387 finalType, noindex ? 1 : 0, fanOnly, nsfw, cw, pollJson, publishAt,
388 now, now, publishedAt
389 );
390 cacheRenderedContent(postId, cleanContent); // bake display HTML (ActivityPub `source` model)
391 db.prepare('UPDATE posts SET paid = ?, paid_min_cents = ? WHERE id = ?').run(paid, paidMinCents, postId);
392
393 // Per-post "share audio on the fediverse" → set fedi_open on this post's hosted tracks
394 // BEFORE federating, so the Create note carries the right Audio attachments.
395 setAudioFediOpen(site.id, cleanContent, req.body.fedi_open_audio);
396
397 if (finalStatus === 'published') {
398 try {
399 db.prepare(
400 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
401 ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, postId);
402 } catch (e) { /* FTS index issues are non-fatal */ }
403
404 // ActivityPub: federate a freshly published post to followers. fan_only → delivered
405 // to followers but addressed followers-only (option A: "fans" = your fedi followers).
406 if (status === 'published') {
407 ActivityPubService.deliverCreate(site, {
408 id: postId, slug: finalSlug, title: title || finalSlug,
409 content: cleanContent, cover_image_url: cover_image_url || null, cover_video_url: req.body.cover_video_url || null, cover_alt: coverAlt, language,
410 published_at: publishedAt, created_at: now, fan_only: fanOnly, paid, paid_min_cents: paidMinCents, excerpt: excerpt || '', nsfw, content_warning: cw, poll_json: pollJson,
411 }).catch(() => { /* best-effort */ });
412 }
413 }
414
415 // HTMX request -> return redirect header
416 if (req.headers['hx-request']) {
417 res.setHeader('HX-Redirect', `${res.locals.siteUrlBase || ''}/${finalSlug}`);
418 return res.send('OK');
419 }
420
421 res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
422});
423
424// ==================== EDIT POST FORM ====================
425router.get('/posts/:slug/edit', requireAuth, (req, res) => {
426 const site = res.locals.site;
427 if (!site) return res.status(404).send('Site required');
428
429 const post = db.prepare(
430 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
431 ).get(site.id, req.params.slug);
432
433 if (!post) return res.status(404).send('Post not found');
434 if (!PermissionsService.canEditPost(req.session.user, post, site)) {
435 return res.status(403).send('No permission');
436 }
437
438 if (post.tags) {
439 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
440 } else {
441 post.tags = [];
442 }
443
444 // A poll with votes is frozen (options can't change) — flag it so the editor disables the poll fields.
445 let pollLocked = false;
446 try { pollLocked = !!(post.poll_json && db.prepare('SELECT 1 FROM poll_votes WHERE post_id = ? LIMIT 1').get(post.id)); } catch { /* ignore */ }
447
448 renderPage(req, res, 'pages/post-edit', {
449 post,
450 isNew: false,
451 pollLocked,
452 fediOpenAudio: postAudioFediOpen(site.id, post.content),
453 pageTitle: 'Edit: ' + (post.title || 'Untitled'),
454 bodyClass: 'on-special',
455 });
456});
457
458// ==================== SAVE POST ====================
459router.post('/posts/:slug/save', requireAuth, (req, res) => {
460 const site = res.locals.site;
461 if (!site) return res.status(404).send('Site required');
462
463 const post = db.prepare(
464 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
465 ).get(site.id, req.params.slug);
466
467 if (!post) return res.status(404).send('Post not found');
468 if (!PermissionsService.canEditPost(req.session.user, post, site)) {
469 return res.status(403).send('No permission');
470 }
471
472 const { title, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
473 const fanOnly = req.body.fan_only ? 1 : 0;
474 const paid = (premiumUnlocked() && req.body.paid) ? 1 : 0; // paid posts (klonkt-demo-aki)
475 const paidEur = String(req.body.paid_min_eur || '').replace(',', '.').trim();
476 const paidMinCents = paid && paidEur ? Math.round(parseFloat(paidEur) * 100) : null;
477 const nsfw = req.body.nsfw ? 1 : 0;
478 const cw = (req.body.content_warning || '').trim().slice(0, 200);
479 const coverAlt = (req.body.cover_alt || '').trim().slice(0, 1500) || null; // cover alt text (a11y)
480 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
481 const newSlug = req.body.slug;
482 const action = req.body.action || 'save';
483 const validTypes = new Set(['post', 'foto', 'video', 'audio']);
484 const finalType = validTypes.has(type) ? type : (post.type || 'post');
485
486 // A poll that has already received votes is frozen (you can still edit the surrounding
487 // post, but not the options) — changing options after votes would scramble the tally and
488 // is disallowed on the fediverse too. Otherwise re-parse the poll form (add/remove/disable).
489 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; } })());
490 const pollJson = hasVotes ? post.poll_json : parsePollForm(req.body);
491
492 // Sanitize before storage — same pipeline as create.
493 const cleanContent = HtmlSanitizerService.sanitize(content || '');
494
495 let finalSlug = post.slug;
496 if (newSlug && newSlug !== post.slug) {
497 const cleaned = newSlug.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
498 const safe = RESERVED_SLUGS.has(cleaned) ? `${cleaned}-post` : cleaned;
499 // Duplicate slug? Make it unique automatically instead of rejecting (own post may keep its slug).
500 finalSlug = uniqueSlug(site.id, safe, post.id);
501 }
502
503 const now = new Date().toISOString();
504 let finalStatus = status || post.status;
505 let publishedAt = post.published_at;
506
507 if (action === 'publish') {
508 finalStatus = 'published';
509 if (!publishedAt) publishedAt = now;
510 }
511
512 // Release planning: published + future publish_at -> 'scheduled'.
513 let publishAt = null;
514 const pa = Date.parse(req.body.publish_at || '');
515 if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
516 finalStatus = 'scheduled';
517 publishAt = new Date(pa).toISOString();
518 publishedAt = null;
519 }
520
521 db.prepare(`
522 UPDATE posts SET
523 title = ?, content = ?, excerpt = ?, status = ?,
524 cover_image_url = ?, cover_video_url = ?, cover_alt = ?, language = ?, pinned = ?, tags = ?,
525 type = ?, noindex = ?, fan_only = ?, nsfw = ?, content_warning = ?, poll_json = ?, publish_at = ?,
526 slug = ?, published_at = ?, updated_at = ?
527 WHERE id = ?
528 `).run(
529 title, cleanContent, excerpt, finalStatus,
530 cover_image_url || null, (req.body.cover_video_url || null), coverAlt, language, parsePinnedRank(pinned),
531 JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
532 finalType, noindex ? 1 : 0, fanOnly, nsfw, cw, pollJson, publishAt,
533 finalSlug, publishedAt, now, post.id
534 );
535 cacheRenderedContent(post.id, cleanContent); // re-bake display HTML on edit (ActivityPub `source` model)
536 db.prepare('UPDATE posts SET paid = ?, paid_min_cents = ? WHERE id = ?').run(paid, paidMinCents, post.id);
537
538 // Per-post "share audio on the fediverse" → set fedi_open on this post's hosted tracks
539 // BEFORE federating, so the Update/Create note carries the right Audio attachments.
540 setAudioFediOpen(site.id, cleanContent, req.body.fedi_open_audio);
541
542 // Update FTS
543 try {
544 db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id);
545 if (finalStatus === 'published') {
546 db.prepare(
547 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
548 ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, post.id);
549 }
550 } catch (e) { /* FTS issues non-fatal */ }
551
552 // ActivityPub: federate edits to followers. A post that BECOMES published →
553 // Create (new post); an already-published post that's edited → Update (so
554 // Mastodon refreshes its cached copy). fan_only → followers-only (option A).
555 if (finalStatus === 'published') {
556 const apPost = {
557 id: post.id, slug: finalSlug, title: title || finalSlug,
558 content: cleanContent, cover_image_url: cover_image_url || null, cover_video_url: req.body.cover_video_url || null, cover_alt: coverAlt, language,
559 published_at: publishedAt, created_at: post.created_at, fan_only: fanOnly, paid, paid_min_cents: paidMinCents, excerpt: excerpt || '', nsfw, content_warning: cw, poll_json: pollJson,
560 };
561 if (post.status !== 'published') ActivityPubService.deliverCreate(site, apPost).catch(() => { /* best-effort */ });
562 else ActivityPubService.deliverUpdate(site, apPost).catch(() => { /* best-effort */ });
563 }
564
565 // Pin/unpin/reorder → push Add/Remove activities so followers' instances update the
566 // pinned order immediately (reliable, unlike re-fetching the cached featured collection).
567 if ((post.pinned || 0) !== parsePinnedRank(pinned)) {
568 const unpinned = (post.pinned || 0) > 0 && parsePinnedRank(pinned) === 0 ? [post.id] : [];
569 ActivityPubService.resyncFeaturedPins(site, unpinned).catch(() => { /* best-effort */ });
570 }
571
572 res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
573});
574
575// ==================== DELETE POST ====================
576router.post('/posts/:slug/delete', requireAuth, (req, res) => {
577 const site = res.locals.site;
578 if (!site) return res.status(404).send('Site required');
579
580 const post = db.prepare(
581 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
582 ).get(site.id, req.params.slug);
583
584 if (!post) return res.status(404).send('Not found');
585 if (!PermissionsService.canDeletePost(req.session.user, post, site)) {
586 return res.status(403).send('No permission');
587 }
588
589 // ActivityPub: tell followers the post is gone (Delete + Tombstone) if it was
590 // federated (any published post now federates — fan_only goes followers-only).
591 // Fire before the row is removed — we still have post.id (= the Note id).
592 if (post.status === 'published') {
593 ActivityPubService.deliverDelete(site, post).catch(() => { /* best-effort */ });
594 }
595
596 // Cascade: comments + FTS row, THEN the post itself.
597 // FK constraints are ON (config/database.js), so a bare DELETE on posts
598 // fails when comments still reference it.
599 const cascade = db.transaction(() => {
600 db.prepare('DELETE FROM comments WHERE post_id = ?').run(post.id);
601 try { db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id); } catch {}
602 db.prepare('DELETE FROM posts WHERE id = ?').run(post.id);
603 });
604 cascade();
605
606 if (req.headers['hx-request']) {
607 res.setHeader('HX-Redirect', res.locals.siteUrlBase || '/');
608 return res.send('OK');
609 }
610 res.redirect(res.locals.siteUrlBase || '/');
611});
612
613// ==================== ARCHIVE ====================
614router.get('/archive', (req, res) => {
615 const site = res.locals.site;
616 if (!site) return res.status(404).send('No site');
617
618 const posts = db.prepare(`
619 SELECT p.*, u.username as author_username
620 FROM posts p JOIN users u ON p.author_id = u.id
621 WHERE p.site_id = ? AND p.status = 'published'
622 ORDER BY p.published_at DESC
623 `).all(site.id);
624
625 // Group by year/month
626 const grouped = {};
627 for (const post of posts) {
628 if (!post.published_at) continue;
629 const d = new Date(post.published_at);
630 const year = d.getFullYear();
631 const month = d.getMonth();
632 const monthName = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'][month];
633
634 if (!grouped[year]) grouped[year] = {};
635 if (!grouped[year][monthName]) grouped[year][monthName] = [];
636 grouped[year][monthName].push(post);
637 }
638
639 renderPage(req, res, 'pages/archive', {
640 grouped,
641 totalPosts: posts.length,
642 pageTitle: 'Archive - ' + site.title,
643 bodyClass: 'on-archive',
644 });
645});
646
647// Local likes/favourites are removed — engagement is fediverse-only now
648// (the ⭐ on a post likes via the fediverse). No post_likes, no /favorieten.
649
650// Newer/Older neighbours across ALL posts in feed order. Shared by the full
651// post render and the fan gate (premium fan_only) so navigation is consistent
652// everywhere. Solo: within the site (pinned first, then date). Hub: globally by date.
653// Renders a post's display HTML: baked content + the dynamic audio/embed layer.
654// Extracted so the paid unlock (slice 4) serves the exact same body as the page.
655export function renderPostBodyHtml(site, post, req) {
656 let html = (post.content_rendered != null && post.content_rendered !== '')
657 ? post.content_rendered
658 : ActivityPubService.bakePostContent(post.content || '');
659 if (audioEnabled()) {
660 if (site.enable_audio_player !== 0) {
661 html = AudioEmbedService.autoembed(html);
662 html = AudioEmbedService.embedMediaShortcodes(html);
663 html = AudioEmbedService.embedExternalLinkShortcodes(html);
664
665 // Fetch any tracks referenced by [[track:id]] in this post.
666 // Cheap to do unconditionally — only matches if the post actually has shortcodes.
667 const trackIds = [...html.matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)].map(m => m[1]);
668 if (trackIds.length) {
669 const placeholders = trackIds.map(() => '?').join(',');
670 const rows = db.prepare(`
671 SELECT t.id, t.title, t.artist, t.cover_url, t.credit, t.license,
672 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
673 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
674 WHERE t.site_id = ? AND t.id IN (${placeholders})
675 `).all(site.id, ...trackIds);
676 const byId = new Map(rows.map(r => [r.id, r]));
677 html = AudioEmbedService.embedTrackShortcodes(html, (id) => {
678 const r = byId.get(id);
679 if (!r) return null;
680 return {
681 id: r.id,
682 title: r.title,
683 artist: r.artist,
684 cover: r.cover_url,
685 credit: r.credit || '',
686 license: r.license || '',
687 link_spotify: r.link_spotify || '',
688 link_youtube: r.link_youtube || '',
689 link_soundcloud: r.link_soundcloud || '',
690 url: r.filename ? audioUrl(r.filename) : '', // '' = link-only track
691 };
692 });
693 }
694
695 // Album shortcodes: [[album:Some Album Name]]
696 const albumNames = [...html.matchAll(/\[\[album:([^\]]+)\]\]/g)].map(m => m[1].trim());
697 if (albumNames.length) {
698 const placeholders = albumNames.map(() => '?').join(',');
699 const albumRows = db.prepare(`
700 SELECT t.id, t.title, t.artist, t.album, t.cover_url, t.position,
701 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
702 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
703 WHERE t.site_id = ? AND t.album IN (${placeholders})
704 ORDER BY t.position ASC, t.created_at ASC
705 `).all(site.id, ...albumNames);
706 const byAlbum = new Map();
707 for (const r of albumRows) {
708 // Link-only tracks (no file) remain in the album overview (url '').
709 if (!byAlbum.has(r.album)) byAlbum.set(r.album, []);
710 byAlbum.get(r.album).push({
711 id: r.id,
712 url: r.filename ? audioUrl(r.filename) : '',
713 title: r.title || 'Untitled',
714 artist: r.artist || '',
715 cover: r.cover_url || '',
716 link_spotify: r.link_spotify || '',
717 link_youtube: r.link_youtube || '',
718 link_soundcloud: r.link_soundcloud || '',
719 });
720 }
721 html = AudioEmbedService.embedAlbumShortcodes(html, (name) => {
722 const tracks = byAlbum.get(name);
723 if (!tracks || !tracks.length) return null;
724 return {
725 title: name,
726 artist: tracks[0].artist || '',
727 cover: tracks[0].cover || '',
728 tracks,
729 };
730 });
731 }
732
733 // Playlist shortcodes: [[playlist:some-slug-id]] — first-class entity.
734 // Editing the playlist propagates to every post that embeds it.
735 const playlistIds = [...html.matchAll(/\[\[playlist:([a-z0-9][a-z0-9-]*)\]\]/gi)]
736 .map(m => m[1].toLowerCase());
737 if (playlistIds.length) {
738 const isAdmin = req.session?.user?.role === 'god';
739 html = AudioEmbedService.embedPlaylistShortcodes(html, (id) => {
740 return PlaylistService.get(site.id, id, audioUrl);
741 }, { isAdmin });
742 }
743 }
744 } else {
745 // LITE mode (KLONKT_AUDIO=off): no own audio (no ffmpeg/stream route).
746 // External embeds (YouTube/SoundCloud/Spotify) remain; the own-audio
747 // shortcodes ([[track]]/[[album]]/[[playlist]]) are cleanly stripped.
748 html = AudioEmbedService.autoembed(html);
749 html = AudioEmbedService.embedMediaShortcodes(html);
750 html = AudioEmbedService.embedExternalLinkShortcodes(html);
751 html = html.replace(/\[\[(track|album|playlist):[^\]]+\]\]/gi, '');
752 }
753 return html;
754}
755
756// A short public teaser for a paid post: its excerpt, else the first ~280 chars
757// of the (stripped) content. Shared by the web gate and federation.
758function paidTeaser(post, max = 280) {
759 if (post && post.excerpt && String(post.excerpt).trim()) return String(post.excerpt).trim();
760 // Only the FIRST paragraph: a paid teaser must never spill later content.
761 const html = String((post && post.content) || '');
762 const firstP = (html.match(/<p[^>]*>([\s\S]*?)<\/p>/i) || [null, html])[1] || '';
763 const text = firstP.replace(/<[^>]+>/g, ' ').replace(/&[a-z#0-9]+;/gi, ' ').replace(/\s+/g, ' ').trim();
764 return text.length > max ? text.slice(0, max).replace(/\s+\S*$/, '') + '…' : text;
765}
766
767function postNeighbors(site, post, isHub) {
768 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
769 const ordered = isHub
770 ? db.prepare(`
771 SELECT p.id, p.slug, p.title, p.pinned, s.slug AS site_slug
772 FROM posts p JOIN sites s ON s.id = p.site_id
773 WHERE p.status = 'published'
774 ORDER BY p.published_at DESC
775 `).all()
776 : db.prepare(`
777 SELECT id, slug, title, pinned FROM posts
778 WHERE site_id = ? AND status = 'published'
779 ORDER BY (pinned = 0) ASC, pinned ASC, published_at DESC
780 `).all(site.id);
781 const idx = ordered.findIndex((p) => p.id === post.id);
782 const newerPost = idx > 0 ? ordered[idx - 1] : null;
783 const olderPost = (idx >= 0 && idx < ordered.length - 1) ? ordered[idx + 1] : null;
784 if (newerPost) newerPost._urlBase = urlBaseFor(newerPost);
785 if (olderPost) olderPost._urlBase = urlBaseFor(olderPost);
786 return { newerPost, olderPost };
787}
788
789// ==================== REMOTE INTERACTION (reply to a fediverse post as your site) ====================
790// Standard fediverse "reply from your own server" landing endpoint. A post page
791// elsewhere bounces the visitor here with ?uri=<remote post>; the site owner
792// composes a reply that federates back to that post.
793router.get('/authorize_interaction', requireSiteManager, async (req, res) => {
794 const site = res.locals.site;
795 const uri = (req.query.uri || '').toString();
796 const sent = !!req.query.sent;
797 const followed = !!req.query.followed;
798 const voted = !!req.query.voted;
799 const reported = !!req.query.reported;
800 let target = null, followTarget = null;
801 if (!sent && !followed && !voted && !reported && uri) {
802 try { target = await ActivityPubService.resolveRemoteNote(uri); } catch { /* ignore */ }
803 // Not a post? Maybe the URI is a profile/actor → offer Follow, not reply.
804 if (!target) { try { followTarget = await ActivityPubService.resolveRemoteActor(uri); } catch { /* ignore */ } }
805 }
806 renderPage(req, res, 'pages/authorize-interaction', {
807 pageTitleKey: 'fedi.remote_interact', // i18n: was hardcoded Dutch on non-NL sites
808 bodyClass: 'on-special',
809 uri,
810 target,
811 followTarget,
812 sent,
813 followed,
814 voted: !!req.query.voted,
815 reported: !!req.query.reported,
816 liked: !!req.query.liked,
817 boosted: !!req.query.boosted,
818 reacted: (site && uri) ? ActivityPubService.getMyReactions(site.slug, uri) : { liked: false, boosted: false },
819 siteTitle: site ? site.title : '',
820 });
821});
822
823// 📊 Vote on a remote fediverse poll from the interact page (any poll by URL, not just
824// followed ones). Casts the Mastodon-standard ballot straight to the poll's author.
825router.post('/authorize_interaction/vote', requireSiteManager, async (req, res) => {
826 const site = res.locals.site;
827 const uri = (req.body.uri || '').toString();
828 let choice = req.body.choice;
829 if (choice == null) choice = [];
830 if (!Array.isArray(choice)) choice = [choice];
831 if (site && uri && choice.length) { try { await ActivityPubService.voteOnRemotePoll(site, uri, choice.map(String)); } catch { /* ignore */ } }
832 res.redirect('/authorize_interaction?voted=1&uri=' + encodeURIComponent(uri));
833});
834
835// 🚩 Report a remote post/account to its home instance (sends an AS2 Flag).
836router.post('/authorize_interaction/report', requireSiteManager, async (req, res) => {
837 const site = res.locals.site;
838 const uri = (req.body.uri || '').toString();
839 const actorUri = (req.body.actor_uri || '').toString();
840 const reason = (req.body.reason || '').toString();
841 if (site && (uri || actorUri)) { try { await ActivityPubService.sendReport(site, { objectUri: uri, actorUri, reason }); } catch { /* ignore */ } }
842 res.redirect('/authorize_interaction?reported=1&uri=' + encodeURIComponent(uri || actorUri));
843});
844
845// ⭐ Like / unlike a remote post from your own site (toggle on the interact page).
846router.post('/authorize_interaction/like', requireSiteManager, (req, res) => {
847 const site = res.locals.site;
848 const uri = (req.body.uri || '').toString();
849 let on = false;
850 if (site && uri) {
851 on = !ActivityPubService.getMyReactions(site.slug, uri).liked;
852 ActivityPubService.resolveRemoteNote(uri)
853 .then((note) => note && ActivityPubService.sendInteraction(site, on ? 'like' : 'unlike', note.object_uri || uri, note.actor_uri))
854 .catch((e) => console.warn('[AP] remote like failed:', e.message));
855 ActivityPubService.setMyReaction(site.slug, uri, 'like', on);
856 }
857 if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
858 res.redirect('/authorize_interaction?uri=' + encodeURIComponent(uri));
859});
860
861// 🔁 Boost / unboost a remote post from your own site (toggle on the interact page).
862// Also flags it for the Cirkel (markBoosted is a no-op if the post isn't in your timeline).
863router.post('/authorize_interaction/boost', requireSiteManager, (req, res) => {
864 const site = res.locals.site;
865 const uri = (req.body.uri || '').toString();
866 let on = false;
867 if (site && uri) {
868 on = !ActivityPubService.getMyReactions(site.slug, uri).boosted;
869 ActivityPubService.resolveRemoteNote(uri)
870 .then((note) => {
871 if (!note) return;
872 const id = note.object_uri || uri;
873 return Promise.resolve(ActivityPubService.sendInteraction(site, on ? 'boost' : 'unboost', id, note.actor_uri))
874 // Boost → store the post in the timeline (even if you don't follow the author) so it
875 // surfaces in the Cirkel; unboost → just clear the flag.
876 .then(() => on ? ActivityPubService.upsertBoostedNote(site.slug, note) : ActivityPubService.unmarkBoosted(site.slug, id));
877 })
878 .catch((e) => console.warn('[AP] remote boost failed:', e.message));
879 ActivityPubService.setMyReaction(site.slug, uri, 'boost', on);
880 }
881 if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
882 res.redirect('/authorize_interaction?uri=' + encodeURIComponent(uri));
883});
884
885// Follow a remote actor from your own site (when the target is a profile, not a post).
886router.post('/authorize_interaction/follow', requireSiteManager, (req, res) => {
887 const site = res.locals.site;
888 const uri = (req.body.uri || '').toString();
889 if (site && uri) {
890 ActivityPubService.followActor(site, uri)
891 .catch((e) => console.warn('[AP] remote follow failed:', e.message));
892 }
893 res.redirect('/authorize_interaction?followed=1&uri=' + encodeURIComponent(uri));
894});
895
896router.post('/authorize_interaction', requireSiteManager, (req, res) => {
897 const site = res.locals.site;
898 const uri = (req.body.uri || '').toString();
899 const text = (req.body.text || '').toString();
900 const html = (req.body.content || '').toString(); // rich reply editor HTML (sanitized in deliverReply)
901 const language = (req.body.language || '').toString();
902 let attachments = [];
903 try { attachments = JSON.parse(req.body.attachments || '[]'); } catch { /* geen media */ }
904 let mentions; // undefined = geen balk meegestuurd (legacy addressing)
905 try { if (req.body.mentions !== undefined) mentions = JSON.parse(req.body.mentions || '[]'); } catch { mentions = undefined; }
906 if (site && uri && (text.trim() || html.trim() || (Array.isArray(attachments) && attachments.length))) {
907 // Resolve + deliver in the background so Send responds instantly.
908 ActivityPubService.resolveRemoteNote(uri)
909 .then((parent) => parent && ActivityPubService.deliverReply(site, { postId: parent.localPostId || '', postSlug: null, parent, text, html, language, attachments, mentions }))
910 .catch((e) => console.warn('[AP] remote reply failed:', e.message));
911 }
912 res.redirect('/authorize_interaction?sent=1&uri=' + encodeURIComponent(uri));
913});
914
915// Manage / delete your own outbound fediverse replies (site owner only).
916// Messages = Reacties + Meldingen in ONE inbox (your sent replies join the stream).
917// The old /fediverse (manage) and /notifications pages redirect here.
918router.get('/messages', requireSiteManager, (req, res) => {
919 const site = res.locals.site;
920 const append = req.query.append === '1';
921 const offset = Math.max(0, parseInt(req.query.offset, 10) || 0);
922 const page = gateEmbeds(site, site ? ActivityPubService.getMessages(site.slug, FEED_PAGE + 1, offset) : []);
923 const hasMore = page.length > FEED_PAGE;
924 const items = page.slice(0, FEED_PAGE);
925 // Read the watermark BEFORE marking seen → unread dots on items newer than last visit.
926 const seenAt = site ? ActivityPubService.notificationsSeenAt(site.slug) : 0;
927 // Only stamp "seen" on the first page load (not on Load-more appends).
928 if (site && !append && !isViewer(req.session.user)) ActivityPubService.markNotificationsSeen(site.slug);
929 const moreBase = res.locals.siteUrlBase || '';
930 if (append) {
931 return renderPage(req, res, 'partials/messages-append', { items, seen: seenAt, hasMore, nextOffset: offset + FEED_PAGE, moreBase });
932 }
933 // FEP-633c: pending guardianship offers TO this account (I am the ward)
934 // show as a special message with an accept button (Robins besluit: the kid
935 // answers in its own Klonkt; safety is out-of-band by the guardians).
936 const gBase = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
937 const gMe = site ? ActivityPubService.actorId(gBase, site.slug) : null;
938 const guardianOffers = (site
939 ? Guardianship.offersCollection(`${gMe}/queues/offers`, site.slug, gMe).orderedItems
940 : []).filter((o) => o['shaer:ward'] === gMe && o['shaer:needsMyAccept']);
941 // FEP-633c §2: who guards this account (committed). Shown so a ward can always
942 // see its guardians, not just pending offers. Derive a display @handle when the
943 // stored one is missing or is the escalation (inbox) handle rather than a @handle.
944 const guardianHandle = (uri, cached) => {
945 if (cached && cached.charAt(0) === '@') return cached;
946 try { const u = new URL(uri); return `@${u.pathname.split('/').filter(Boolean).pop()}@${u.host}`; }
947 catch { return uri; }
948 };
949 // With their availability (FEP-633c 3.6.1): the ward always sees the real
950 // size of its safety net, not just the names. Owner-only by construction:
951 // this page is the owner's.
952 const gStatus = site ? Object.fromEntries(
953 Guardianship.availability.statusesFor(site.slug, Guardianship.listGuardians(site.slug).map((g) => g.other_uri), Date.now())
954 .map((s) => [s.id, s]),
955 ) : {};
956 const myGuardians = (site ? Guardianship.listGuardians(site.slug) : [])
957 .map((g) => ({
958 uri: g.other_uri,
959 handle: guardianHandle(g.other_uri, g.other_handle),
960 availability: (gStatus[g.other_uri] || {})['shaer:availability'] || 'active',
961 awayUntil: (gStatus[g.other_uri] || {})['shaer:awayUntil'] || null,
962 }));
963 renderPage(req, res, 'pages/messages', {
964 pageTitleKey: 'msg.title', bodyClass: 'on-special', items, seenAt,
965 hasMore, nextOffset: offset + FEED_PAGE, moreBase, guardianOffers, myGuardians,
966 success: req.query.success || null, error: req.query.error || null,
967 });
968});
969
970// The kid answers a guardianship offer from Berichten: the same C2S
971// Accept/Reject pipeline the Shaer apps use (one path, one behavior).
972router.post('/messages/guardianship', requireSiteManager, async (req, res) => {
973 const site = res.locals.site;
974 const back = `${res.locals.siteUrlBase || ''}/messages`;
975 const answer = req.body.answer === 'accept' ? 'Accept' : (req.body.answer === 'reject' ? 'Reject' : null);
976 const offer = String(req.body.offer || '').trim();
977 if (!site || !answer || !offer) return res.redirect(back + '?error=guardianship');
978 try {
979 // Same C2S Accept/Reject the apps use; the handshake module records the
980 // ward's accept and (once the candidate returns the handle) commits.
981 const r = await ActivityPubService.ingestOutboxActivity(site, req.session.user, { type: answer, object: offer });
982 if (r && r.status < 400) return res.redirect(back + '?success=' + (answer === 'Accept' ? 'guardian_accepted' : 'guardian_rejected'));
983 } catch { /* fall through */ }
984 res.redirect(back + '?error=guardianship');
985});
986// A ward answers a guardian's wave without publishing: a canned private note
987// back to the sender (FEP-633c §5, shaer:wave reply). Same direct-note leg.
988router.post('/messages/quick-reply', requireSiteManager, express.urlencoded({ extended: false }), async (req, res) => {
989 const site = res.locals.site;
990 const back = `${res.locals.siteUrlBase || ''}/messages`;
991 const to = String(req.body.to || '').trim();
992 const text = String(req.body.text || '').trim().slice(0, 200);
993 if (!site || !/^https?:\/\//i.test(to) || !text) return res.redirect(back + '?error=quickreply');
994 try {
995 const r = await ActivityPubService.deliverDirectNote(site, { recipients: [to], text, wave: true });
996 if (r) return res.redirect(back + '?success=wave_sent');
997 } catch { /* fall through */ }
998 res.redirect(back + '?error=quickreply');
999});
1000
1001router.get('/fediverse', requireSiteManager, (req, res) => res.redirect(`${res.locals.siteUrlBase || ''}/messages`));
1002
1003router.post('/fediverse/:id/delete', requireSiteManager, async (req, res) => {
1004 const site = res.locals.site;
1005 if (site) {
1006 try { await ActivityPubService.deliverOutboxDelete(site, req.params.id); }
1007 catch (e) { console.warn('[AP] outbox delete failed:', e.message); }
1008 }
1009 res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/fediverse`);
1010});
1011
1012// Moderation: remove an INCOMING reply from your thread (owner only). Tombstones the
1013// object URI so re-delivery and thread-crawling never bring it back. Works for private
1014// notes too (acts on the local copy; no remote fetch involved).
1015router.post('/interactions/:id/remove', requireSiteManager, (req, res) => {
1016 const site = res.locals.site;
1017 if (site) {
1018 const r = ActivityPubService.rejectInteraction(site, parseInt(req.params.id, 10) || 0, 'removed by site owner');
1019 if (r.error) console.warn('[AP] interaction remove failed:', r.error);
1020 }
1021 res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/`);
1022});
1023
1024// Moderation: report an INCOMING reply to its home instance (owner only). Uses the
1025// locally stored object/actor URIs, so it also works for private notes that
1026// authorize_interaction cannot fetch (401/404).
1027router.post('/interactions/:id/report', requireSiteManager, async (req, res) => {
1028 const site = res.locals.site;
1029 if (site) {
1030 const tgt = ActivityPubService.interactionReportTarget(site, parseInt(req.params.id, 10) || 0);
1031 if (tgt && (tgt.objectUri || tgt.actorUri)) {
1032 try {
1033 const r = await ActivityPubService.sendReport(site, { objectUri: tgt.objectUri, actorUri: tgt.actorUri, reason: (req.body.reason || '').toString().slice(0, 500) });
1034 if (r && r.error) console.warn('[AP] interaction report failed:', r.error);
1035 } catch (e) { console.warn('[AP] interaction report failed:', e.message); }
1036 }
1037 }
1038 res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/`);
1039});
1040
1041// Edit one of your own outbound fediverse replies (owner only) → sends an Update(Note).
1042router.post('/fediverse/:id/edit', requireSiteManager, async (req, res) => {
1043 const site = res.locals.site;
1044 const text = String(req.body.text || '');
1045 const html = String(req.body.content || ''); // rich reply editor HTML (sanitized in deliverOutboxUpdate)
1046 if (site && (text.trim() || html.trim())) {
1047 try {
1048 await ActivityPubService.deliverOutboxUpdate(site, req.params.id, text, {
1049 html, language: String(req.body.language || ''),
1050 });
1051 } catch (e) { console.warn('[AP] outbox edit failed:', e.message); }
1052 }
1053 res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/fediverse`);
1054});
1055
1056// ==================== FEDIVERSE CLIENT: home timeline + following ====================
1057// Build a direct embed iframe for the first embeddable link (YouTube/Spotify/
1058// SoundCloud/Vimeo) in a remote post's content, so others' media plays inline.
1059function timelineEmbedHtml(html) {
1060 if (!html) return null;
1061 const re = /href=["']([^"']+)["']/gi; let m; const seen = new Set();
1062 while ((m = re.exec(html))) {
1063 const u = m[1]; if (seen.has(u)) continue; seen.add(u);
1064 let p; try { p = AudioEmbedService.detectProvider(u); } catch { p = null; }
1065 if (!p) {
1066 // PeerTube is decentralised (any instance), so it's not in detectProvider — match its watch URL
1067 // (/w/<id> or /videos/watch/<id>) and embed the player. Host is validated (safe chars only), so
1068 // it's safe to inline into the iframe src; a non-PeerTube /w/ URL just yields an empty iframe.
1069 const pt = u.match(/^https?:\/\/([\w.-]+(?::\d+)?)\/(?:w|videos\/watch)\/([\w-]{6,})/i);
1070 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>`;
1071 continue;
1072 }
1073 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>`;
1074 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>`;
1075 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>`;
1076 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>`;
1077 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>`;
1078 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>`; }
1079 }
1080 return null;
1081}
1082
1083// A federated Klonkt audio post renders as "🎵 … listen on <link>". Embed the remote
1084// Klonkt player (its /embed?post=<slug>). A single-segment path = a Klonkt post slug
1085// (skips Mastodon /@user/123). The origin is whitelisted in the response CSP frame-src.
1086function klonktAudioEmbed(html, url) {
1087 if (!html || !url || html.indexOf('🎵') < 0) return null;
1088 let u; try { u = new URL(url); } catch { return null; }
1089 if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;
1090 const slug = u.pathname.replace(/^\/+|\/+$/g, '');
1091 if (!slug || slug.indexOf('/') >= 0) return null; // single segment only
1092 const src = u.origin + '/embed?post=' + encodeURIComponent(slug);
1093 // Drop the now-redundant "🎵 … listen on <site>" line — the embedded player below shows it.
1094 const content = html.replace(/<p>🎵[\s\S]*?<\/p>\s*/i, '');
1095 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>` };
1096}
1097
1098/**
1099 * FEP-633c §5.3-style gated feature: may this account see previews of links
1100 * that point OUTSIDE the fediverse? For a ward that is the guardians' call.
1101 *
1102 * Applied at SERVE time on every surface, the way the app's inbox read already
1103 * does it (routes/activitypub.js): a card the client merely hides has still
1104 * been delivered.
1105 */
1106function gateEmbeds(site, rows) {
1107 if (!site || !rows.length) return rows;
1108 let isWard = false;
1109 try { isWard = Guardianship.listGuardians(site.slug).length > 0; } catch { /* no relations yet */ }
1110 if (Guardianship.externalEmbedsAllowed(site.external_embeds, isWard)) return rows;
1111 return rows.map((r) => (r && r.embed_json ? { ...r, embed_json: null } : r));
1112}
1113
1114router.get('/news', requireSiteManager, (req, res) => {
1115 const site = res.locals.site;
1116 const append = req.query.append === '1';
1117 const offset = Math.max(0, parseInt(req.query.offset, 10) || 0);
1118 const cspOrigins = new Set();
1119 // Fetch one extra to know whether a "Load more" button belongs on this page.
1120 const rows = gateEmbeds(site, site ? ActivityPubService.getTimeline(site.slug, FEED_PAGE + 1, offset) : []);
1121 const hasMore = rows.length > FEED_PAGE;
1122 const timeline = rows.slice(0, FEED_PAGE).map((p) => {
1123 let embedHtml = timelineEmbedHtml(p.content);
1124 let content = p.content;
1125 let embedUrl = null;
1126 if (!embedHtml) {
1127 const k = klonktAudioEmbed(p.content, p.url);
1128 if (k) { embedHtml = k.html; content = k.content; embedUrl = k.embedUrl; cspOrigins.add(k.origin); }
1129 }
1130 // embedUrl = the player's direct /embed?post=… URL. Surfaced so the view can offer a
1131 // top-level "open the player" link that works even when a browser shield/CSP blocks
1132 // the cross-site iframe (a full-page navigation is not a cross-site frame).
1133 let poll = null;
1134 if (p.poll_json) { try { poll = JSON.parse(p.poll_json); } catch { /* ignore */ } }
1135 return { ...p, content, embedHtml, embedUrl, poll };
1136 });
1137 // Option A: allow the followed Klonkt sites' player iframes (you follow them) by
1138 // extending ONLY this response's CSP frame-src. The global policy stays locked down.
1139 if (cspOrigins.size) {
1140 const csp = res.getHeader('Content-Security-Policy');
1141 if (csp) {
1142 const extra = [...cspOrigins].join(' ');
1143 res.setHeader('Content-Security-Policy', String(csp).replace(/frame-src ([^;]*)/i, (m, g) => `frame-src ${g} ${extra}`));
1144 }
1145 }
1146 const moreBase = res.locals.siteUrlBase || '';
1147 if (append) {
1148 return renderPage(req, res, 'partials/news-append', { timeline, hasMore, nextOffset: offset + FEED_PAGE, moreBase });
1149 }
1150 renderPage(req, res, 'pages/news', {
1151 pageTitle: 'News', bodyClass: 'on-special',
1152 timeline, hasMore, nextOffset: offset + FEED_PAGE, moreBase,
1153 success: req.query.success || null, error: req.query.error || null,
1154 });
1155});
1156
1157// Volgend — manage the accounts you follow (+ per-account auto-boost toggles).
1158// Connect = who you follow + who follows you, merged into one page with direction
1159// (following →, follower ←, mutual ↔) and per-account delivery health. Replaces the
1160// separate Following/Followers pages, which redirect here so old links keep working.
1161router.get('/connect', requireSiteManager, (req, res) => {
1162 const site = res.locals.site;
1163 const connections = site ? ActivityPubService.listConnections(site.slug) : [];
1164 renderPage(req, res, 'pages/connect', {
1165 pageTitle: 'Connect', bodyClass: 'on-special',
1166 connections,
1167 success: req.query.success || null, error: req.query.error || null,
1168 });
1169});
1170router.get('/following', requireSiteManager, (req, res) => res.redirect(`${res.locals.siteUrlBase || ''}/connect`));
1171router.get('/followers', requireSiteManager, (req, res) => res.redirect(`${res.locals.siteUrlBase || ''}/connect`));
1172
1173router.post('/followers/:id/remove', requireSiteManager, (req, res) => {
1174 const site = res.locals.site;
1175 const base = res.locals.siteUrlBase || '';
1176 if (!site) return res.redirect(`${base}/connect`);
1177 const ok = ActivityPubService.removeFollower(site.slug, parseInt(req.params.id, 10) || 0);
1178 return res.redirect(`${base}/connect?` + (ok
1179 ? 'success=' + encodeURIComponent('Volger verwijderd')
1180 : 'error=' + encodeURIComponent('Volger niet gevonden')));
1181});
1182
1183router.post('/news/follow', requireSiteManager, async (req, res) => {
1184 const site = res.locals.site;
1185 const handle = (req.body.handle || '').toString();
1186 let q = 'success=' + encodeURIComponent('Volgverzoek verstuurd');
1187 if (site && handle.trim()) {
1188 try {
1189 const r = await ActivityPubService.followActor(site, handle, !!req.body.auto_boost);
1190 if (r && r.error) q = 'error=' + encodeURIComponent(r.error === 'not_found' ? 'Account niet gevonden' : (r.error === 'unreachable' ? 'Server onbereikbaar' : 'Volgen mislukt'));
1191 else {
1192 q = 'success=' + encodeURIComponent('Je volgt nu ' + ((r && r.name) || handle));
1193 }
1194 } catch (e) { q = 'error=' + encodeURIComponent('Volgen mislukt'); }
1195 }
1196 res.redirect('/following?' + q);
1197});
1198
1199router.post('/news/unfollow', requireSiteManager, async (req, res) => {
1200 const site = res.locals.site;
1201 const actorUri = (req.body.actor_uri || '').toString();
1202 if (site && actorUri) { try { await ActivityPubService.unfollowActor(site, actorUri); } catch (e) { /* ignore */ } }
1203 res.redirect('/following?success=' + encodeURIComponent('Ontvolgd'));
1204});
1205
1206// Toggle "Featured" (show this account's posts in your Cirkel) on an account you follow.
1207router.post('/news/autoboost', requireSiteManager, (req, res) => {
1208 const site = res.locals.site;
1209 const actorUri = (req.body.actor_uri || '').toString();
1210 if (site && actorUri) ActivityPubService.setAutoBoost(site.slug, actorUri, !!req.body.auto_boost);
1211 res.redirect('/following?success=' + encodeURIComponent(req.body.auto_boost ? 'Uitgelicht ✨' : 'Niet meer uitgelicht'));
1212});
1213
1214// Like / unlike a feed post — a toggle. Fetch request → JSON {on} (stay on the page,
1215// no banner); no-JS → redirect back.
1216router.post('/news/like', requireSiteManager, async (req, res) => {
1217 const site = res.locals.site;
1218 const note = (req.body.note || '').toString();
1219 let on = false;
1220 if (site && note) {
1221 on = !ActivityPubService.getTimelineReaction(site.slug, note).liked;
1222 try { await ActivityPubService.sendInteraction(site, on ? 'like' : 'unlike', note, (req.body.author || '').toString()); } catch (e) { /* ignore */ }
1223 if (on) ActivityPubService.markLiked(site.slug, note); else ActivityPubService.unmarkLiked(site.slug, note);
1224 }
1225 if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
1226 res.redirect('/news');
1227});
1228
1229// Boost / unboost a feed post — a toggle. markBoosted also surfaces it in the Cirkel.
1230router.post('/news/boost', requireSiteManager, async (req, res) => {
1231 const site = res.locals.site;
1232 const note = (req.body.note || '').toString();
1233 let on = false;
1234 if (site && note) {
1235 on = !ActivityPubService.getTimelineReaction(site.slug, note).boosted;
1236 try { await ActivityPubService.sendInteraction(site, on ? 'boost' : 'unboost', note, (req.body.author || '').toString()); } catch (e) { /* ignore */ }
1237 if (on) {
1238 ActivityPubService.markBoosted(site.slug, note); // instant UI state
1239 // Fire-and-forget: re-resolve the note so the cached row is refreshed
1240 // (cover/content) — boosting again heals a stale copy from EVERY boost
1241 // path, not just the interact page.
1242 ActivityPubService.resolveRemoteNote(note)
1243 .then((n) => { if (n) ActivityPubService.upsertBoostedNote(site.slug, n); })
1244 .catch(() => { /* best-effort */ });
1245 } else {
1246 ActivityPubService.unmarkBoosted(site.slug, note);
1247 }
1248 }
1249 if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
1250 res.redirect('/news');
1251});
1252
1253// Vote on a fediverse poll (a Question in the feed). Owner-only, like the other interactions.
1254router.post('/news/vote', requireSiteManager, async (req, res) => {
1255 const site = res.locals.site;
1256 const note = (req.body.note || '').toString();
1257 let choice = req.body.choice;
1258 if (choice == null) choice = [];
1259 if (!Array.isArray(choice)) choice = [choice];
1260 if (site && note && choice.length) { try { await ActivityPubService.voteOnPoll(site, note, choice.map(String)); } catch (e) { /* ignore */ } }
1261 res.redirect('/news');
1262});
1263
1264// Notifications inbox (new followers + replies/likes/boosts on your posts).
1265router.get('/notifications', requireSiteManager, (req, res) => res.redirect(`${res.locals.siteUrlBase || ''}/messages`));
1266
1267// Blocking / defederation (owner-only).
1268router.get('/blocking', requireSiteManager, (req, res) => {
1269 const site = res.locals.site;
1270 const blocks = site ? ActivityPubService.listBlocks(site.slug) : [];
1271 renderPage(req, res, 'pages/blocks', { pageTitle: 'Blokkeren', bodyClass: 'on-special', blocks, success: req.query.success || null, error: req.query.error || null });
1272});
1273
1274router.post('/blocking/add', requireSiteManager, async (req, res) => {
1275 const site = res.locals.site;
1276 let q = 'success=' + encodeURIComponent('Geblokkeerd');
1277 if (site) {
1278 try {
1279 const r = await ActivityPubService.blockTarget(site, (req.body.target || '').toString());
1280 if (r && r.error) q = 'error=' + encodeURIComponent(r.error === 'not_found' ? 'Account niet gevonden' : 'Voer een @handle of domein in');
1281 else q = 'success=' + encodeURIComponent(((r && r.label) || '') + ' geblokkeerd');
1282 } catch (e) { q = 'error=' + encodeURIComponent('Blokkeren mislukt'); }
1283 }
1284 const ref = req.get('Referer') || '';
1285 res.redirect((ref.includes('/news') ? '/news?' : '/blocking?') + q);
1286});
1287
1288router.post('/blocking/remove', requireSiteManager, (req, res) => {
1289 const site = res.locals.site;
1290 if (site) { try { ActivityPubService.unblock(site, (req.body.target || '').toString()); } catch (e) { /* ignore */ } }
1291 res.redirect('/blocking?success=' + encodeURIComponent('Deblokkeerd'));
1292});
1293
1294// ==================== VIEW POST (last route — catches /:slug) ====================
1295router.get('/:slug', (req, res, next) => {
1296 if (RESERVED_SLUGS.has(req.params.slug)) return next();
1297
1298 const site = res.locals.site;
1299 if (!site) return next(); // -> nette 404 catch-all
1300
1301 const post = db.prepare(`
1302 SELECT p.*, u.username as author_username, u.avatar_url as author_avatar
1303 FROM posts p JOIN users u ON p.author_id = u.id
1304 WHERE p.site_id = ? AND p.slug = ?
1305 `).get(site.id, req.params.slug);
1306
1307 if (!post) return next(); // unknown slug -> clean 404 catch-all
1308
1309 // Permission to view: published OR (logged in + can edit)
1310 if (post.status !== 'published') {
1311 const canEdit = req.session?.user && PermissionsService.canEditPost(req.session.user, post, site);
1312 if (!canEdit) return res.status(403).send('Not published');
1313 }
1314
1315 // Paid gate (klonkt-demo-aki): a paid post shows only a teaser to anyone who
1316 // is not the owner/editor. Checked BEFORE the fan gate: a post that is both
1317 // fan_only and paid unlocks with a passkey, not with a Klonkt-login, so the
1318 // paid gate wins (otherwise anonymous visitors land on the login gate and
1319 // never see the unlock button).
1320 const canEditThis = req.session?.user && PermissionsService.canEditPost(req.session.user, post, site);
1321 // A fresh unlock capability (?u=) from /paid/unlock lets a just-verified
1322 // supporter render the FULL post through this normal template (correct layout,
1323 // scoped styles, working audio). Short-lived signed blob, single post, not a
1324 // cookie and not stored.
1325 const _u = req.query.u ? verifyBlob(String(req.query.u)) : null;
1326 const _unlocked = _u && _u.purpose === 'unlocked' && _u.siteId === site.id && String(_u.post) === String(post.slug);
1327 if (post.paid && !canEditThis && !_unlocked) {
1328 const { newerPost, olderPost } = postNeighbors(site, post, res.locals.tenancy === 'hub');
1329 return renderPage(req, res, 'pages/paid-gate', {
1330 pageTitle: post.title || 'Voor supporters',
1331 bodyClass: 'on-special',
1332 pgTitle: post.title || '',
1333 pgTeaser: paidTeaser(post),
1334 pgCents: post.paid_min_cents || paidDefaultMinCents(site.id),
1335 pgSlug: post.slug,
1336 pgPatronUrl: paidPatronUrl(site.id),
1337 newerPost,
1338 olderPost,
1339 });
1340 }
1341
1342 // Fan-only preview (premium #3): full content only for logged-in fans.
1343 // Anonymous visitors get a clean login gate instead of the content (the title/
1344 // teaser may still appear elsewhere as a teaser).
1345 if (post.fan_only && !(req.session && req.session.user)) {
1346 // Same Newer/Older navigation as on a normal post, so the visitor doesn't get
1347 // stuck on the fan gate but can keep browsing.
1348 const { newerPost, olderPost } = postNeighbors(site, post, res.locals.tenancy === 'hub');
1349 return renderPage(req, res, 'pages/fan-gate', {
1350 pageTitle: post.title || 'Alleen voor fans',
1351 bodyClass: 'on-special',
1352 fgTitle: post.title || '',
1353 fgNext: (res.locals.siteUrlBase || '') + '/' + post.slug,
1354 newerPost,
1355 olderPost,
1356 });
1357 }
1358
1359 // Statistics: count the view (skips admins + unpublished own-preview).
1360 if (post.status === 'published') recordPostView(post, req);
1361
1362 // Render content. Base = the pre-rendered ("baked") display HTML: #hashtags/URLs (and, later,
1363 // @mentions) linkified once at SAVE and cached in content_rendered — the ActivityPub `source`
1364 // model (content = raw source, kept for editing). Old posts with no baked copy fall back to
1365 // baking on the fly (cheap, no network). The dynamic layer (autoembed + [[track/album/
1366 // playlist]] + signed audio URLs) stays per-render on top, since it can't be cached.
1367 post.content_html = renderPostBodyHtml(site, post, req);
1368
1369 if (post.tags) {
1370 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
1371 } else {
1372 post.tags = [];
1373 }
1374
1375 // Native comments removed: social interaction is fediverse-only (see the
1376 // "From the fediverse" section below).
1377
1378 // Prev / next chronological (kept for back-compat — "post-nav" feature
1379 // below the article still uses these as a simple linear navigation).
1380 // Hub mode: Related posts + Newer/Older pull from ALL users (all sites),
1381 // newest first. Solo mode: within the current site (old behaviour).
1382 const isHub = res.locals.tenancy === 'hub';
1383 // Per-post URL base: in hub a link points to /user/<site-slug>/<post-slug>.
1384 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
1385
1386 // Newer/Older across ALL posts (shared helper — also used by the fan gate).
1387 const { newerPost, olderPost } = postNeighbors(site, post, isHub);
1388
1389 // ── Related posts: same-tag matching with recency fallback ─────
1390 // Fetch ~50 candidates, score by tag overlap, take top 3.
1391 // Excluding self via `id != ?`.
1392 const candidates = isHub
1393 ? db.prepare(`
1394 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
1395 FROM posts p JOIN sites s ON s.id = p.site_id
1396 WHERE p.status = 'published' AND p.id != ?
1397 ORDER BY p.published_at DESC LIMIT 50
1398 `).all(post.id)
1399 : db.prepare(`
1400 SELECT id, slug, title, cover_image_url, cover_video_url, published_at, tags, nsfw, content_warning
1401 FROM posts
1402 WHERE site_id = ? AND status = 'published' AND id != ?
1403 ORDER BY published_at DESC LIMIT 50
1404 `).all(site.id, post.id);
1405
1406 // Parse tags JSON safely; missing/malformed → empty array.
1407 const parseTags = (raw) => {
1408 if (!raw) return [];
1409 try {
1410 const v = JSON.parse(raw);
1411 return Array.isArray(v) ? v.map(String) : [];
1412 } catch { return []; }
1413 };
1414
1415 const myTags = new Set(parseTags(post.tags));
1416 let relatedPosts;
1417 if (myTags.size > 0) {
1418 // Score = number of overlapping tags. Posts with zero overlap are
1419 // included only if we don't have 3 with-overlap candidates.
1420 const scored = candidates.map(p => {
1421 const theirTags = parseTags(p.tags);
1422 const overlap = theirTags.reduce((n, t) => n + (myTags.has(t) ? 1 : 0), 0);
1423 return { ...p, _overlap: overlap };
1424 });
1425 const withOverlap = scored.filter(p => p._overlap > 0)
1426 .sort((a, b) => b._overlap - a._overlap || new Date(b.published_at) - new Date(a.published_at));
1427 if (withOverlap.length >= 3) {
1428 relatedPosts = withOverlap.slice(0, 3);
1429 } else {
1430 // Pad with most-recent non-overlap posts so the section is never empty
1431 const overlapIds = new Set(withOverlap.map(p => p.id));
1432 const filler = candidates.filter(p => !overlapIds.has(p.id));
1433 relatedPosts = [...withOverlap, ...filler].slice(0, 3);
1434 }
1435 } else {
1436 // No tags on current post → just show 3 most-recent
1437 relatedPosts = candidates.slice(0, 3);
1438 }
1439 // Strip the internal _overlap field before sending to view
1440 relatedPosts = relatedPosts.map(({ _overlap, tags, ...rest }) => ({ ...rest, _urlBase: urlBaseFor(rest) }));
1441
1442 // Inbound fediverse activity (threaded) for this post.
1443 let fediverse = { thread: [], likeCount: 0, announceCount: 0, total: 0 };
1444 try {
1445 const _apBase = (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
1446 fediverse = ActivityPubService.getInteractions(post.id, _apBase, site);
1447 // Stale-while-revalidate: render from cache now; refresh the remote thread in the
1448 // background (TTL-gated, non-blocking) so undelivered replies-to-replies fill in next view.
1449 if (res.locals.apEnabled !== false) ActivityPubService.maybeCrawlThread(post.id);
1450 } catch { /* non-fatal */ }
1451 // Owner/admin of this site may reply back to a fediverse interaction.
1452 const canManageSite = !!(req.session?.user && PermissionsService.canAdminSite(req.session.user, site));
1453 // Avatar for our own (outbound) fediverse replies = the site's profile photo.
1454 const siteAvatar = (site && site.profile_photo) ? site.profile_photo : null;
1455
1456 renderPage(req, res, 'pages/post', {
1457 post,
1458 poll: ActivityPubService.ownPollView(post),
1459 newerPost,
1460 olderPost,
1461 relatedPosts,
1462 fediverse,
1463 canManageSite,
1464 siteAvatar,
1465 postHasPlayableAudio: ActivityPubService.hasPlayableAudio(post.content || '', site.id),
1466 musicLd: MusicMeta.build((process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, ''), site, post),
1467 pageTitle: post.title + ' - ' + site.title,
1468 socialDescr: post.excerpt || '',
1469 socialImage: post.cover_image_url || '',
1470 bodyClass: 'on-post',
1471 });
1472});
1473
1474// ── Reply back to a fediverse interaction (site owner/admin only) ──
1475router.post('/posts/:slug/fedi-reply', requireSiteManager, async (req, res) => {
1476 const site = res.locals.site;
1477 if (!site) return res.status(404).send('Site required');
1478 const post = db.prepare('SELECT id, slug FROM posts WHERE site_id = ? AND slug = ?').get(site.id, req.params.slug);
1479 if (!post) return res.status(404).send('Not found');
1480 const parent = ActivityPubService.getInteractionById(req.body.interaction_id);
1481 const text = (req.body.text || '').toString();
1482 const html = (req.body.content || '').toString(); // rich reply editor HTML (sanitized in deliverReply)
1483 let attachments = [];
1484 try { attachments = JSON.parse(req.body.attachments || '[]'); } catch { /* geen media */ }
1485 let mentions; // undefined = geen balk meegestuurd (legacy addressing)
1486 try { if (req.body.mentions !== undefined) mentions = JSON.parse(req.body.mentions || '[]'); } catch { mentions = undefined; }
1487 if (parent && parent.post_id === post.id && (text.trim() || html.trim() || (Array.isArray(attachments) && attachments.length))) {
1488 try {
1489 await ActivityPubService.deliverReply(site, {
1490 postId: post.id, postSlug: post.slug, parent, text, html, attachments, mentions,
1491 language: (req.body.language || '').toString(),
1492 });
1493 } catch (e) { console.warn('[AP] reply send failed:', e.message); }
1494 }
1495 res.redirect(`${res.locals.siteUrlBase || ''}/${post.slug}#fediverse`);
1496});
1497
1498// Owner likes/boosts a fediverse comment on their own post — directly as the
1499// site, no "your server" detour (mirrors /fedi-reply).
1500router.post('/posts/:slug/fedi-react', requireSiteManager, async (req, res) => {
1501 const site = res.locals.site;
1502 if (!site) return res.status(404).send('Site required');
1503 const post = db.prepare('SELECT id, slug FROM posts WHERE site_id = ? AND slug = ?').get(site.id, req.params.slug);
1504 if (!post) return res.status(404).send('Not found');
1505 const parent = ActivityPubService.getInteractionById(req.body.interaction_id);
1506 const kind = req.body.kind === 'boost' ? 'boost' : 'like';
1507 if (parent && parent.post_id === post.id && parent.object_uri) {
1508 if (kind === 'boost') {
1509 // Toggle: boost an unboosted comment, or retract it (Undo Announce) if already boosted.
1510 const on = !parent.acted_boost;
1511 ActivityPubService.sendInteraction(site, on ? 'boost' : 'unboost', parent.object_uri, parent.actor_uri)
1512 .catch((e) => console.warn('[AP] reaction failed:', e.message));
1513 ActivityPubService.setInteractionBoosted(parent.id, on);
1514 } else {
1515 // Toggle: like an unliked comment, or un-favourite (Undo Like) if already liked.
1516 const on = !parent.acted_like;
1517 ActivityPubService.sendInteraction(site, on ? 'like' : 'unlike', parent.object_uri, parent.actor_uri)
1518 .catch((e) => console.warn('[AP] reaction failed:', e.message));
1519 ActivityPubService.setInteractionLiked(parent.id, on);
1520 }
1521 }
1522 res.redirect(`${res.locals.siteUrlBase || ''}/${post.slug}#fediverse`);
1523});
1524
1525export default router;
1526export { postNeighbors };
Note: See TracBrowser for help on using the repository browser.