source: Klonkt/src/routes/posts.js@ 5a6a457

main
Last change on this file since 5a6a457 was 5a6a457, checked in by Robin Genis <roboburr@โ€ฆ>, 3 months ago

feat(fediverse): federate on save+scheduler, delivery retry-queue, music as listen-link

#1 Posts now federate to followers not only on create, but also when a draft/

scheduled post becomes published (editor save) and when the Scheduler flips a
scheduled post live โ€” previously those silently didn't reach followers.

#2 Delivery retry-queue (ap_delivery): a failed delivery (down server/timeout) is

queued and retried with backoff (1/5/15/60/180/360 min, 6 tries) by a worker,
instead of fire-and-forget. Signing key re-derived from the slug, never stored.

#3 Music posts: audio shortcodes federate as a '๐ŸŽต listen on the site' link to the

post (protected player) instead of the raw mp3 โ€” keeps Klonkt's audio friction
intact (no downloadable file handed to Mastodon).

Co-Authored-By: Claude <noreply@โ€ฆ>

  • Property mode set to 100644
File size: 35.6 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 } 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 ActivityPubService from '../services/ActivityPubService.js';
21
22const __dirname = path.dirname(fileURLToPath(import.meta.url));
23const POST_IMAGES_DIR = path.resolve(
24 process.env.POST_IMAGES_PATH ||
25 path.join(__dirname, '..', '..', 'storage', 'media', 'post-images')
26);
27fs.mkdirSync(POST_IMAGES_DIR, { recursive: true });
28
29const ALLOWED_IMAGE_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
30const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
31
32const imageStorage = multer.diskStorage({
33 destination: (req, file, cb) => cb(null, POST_IMAGES_DIR),
34 filename: (req, file, cb) => {
35 const ext = path.extname(file.originalname).toLowerCase();
36 cb(null, `${uuid()}${ext}`);
37 },
38});
39const imageUpload = multer({
40 storage: imageStorage,
41 limits: { fileSize: MAX_IMAGE_BYTES },
42 fileFilter: (req, file, cb) => {
43 const ext = path.extname(file.originalname).toLowerCase();
44 if (!ALLOWED_IMAGE_EXT.has(ext)) {
45 return cb(new Error('Image must be jpg/png/webp/gif'));
46 }
47 cb(null, true);
48 },
49});
50
51// Generates a unique slug within the site: 'title', 'title-2', 'title-3', โ€ฆ
52// A second post with the same title is NOT rejected ("already exists"),
53// but automatically gets a free suffix. exceptId = the post being updated
54// (allowed to keep its own slug).
55function uniqueSlug(siteId, base, exceptId = null) {
56 let candidate = base;
57 let n = 2;
58 for (;;) {
59 const row = exceptId
60 ? db.prepare('SELECT id FROM posts WHERE site_id = ? AND slug = ? AND id != ?').get(siteId, candidate, exceptId)
61 : db.prepare('SELECT id FROM posts WHERE site_id = ? AND slug = ?').get(siteId, candidate);
62 if (!row) return candidate;
63 candidate = `${base}-${n++}`;
64 }
65}
66
67const router = express.Router();
68
69// ==================== UPLOAD IMAGE (cover or content) ====================
70// Returns JSON {url} so the editor can stick it into the cover field or
71// insert a markdown ![](url) into content.
72router.post('/posts/upload-image', requireAuth, (req, res) => {
73 imageUpload.single('image')(req, res, (err) => {
74 if (err) return res.status(400).json({ error: err.message });
75 if (!req.file) return res.status(400).json({ error: 'No file' });
76 const url = '/media/post-images/' + toWebp(req.file);
77 res.json({ url, size: req.file.size, mime: req.file.mimetype });
78 });
79});
80
81const RESERVED_SLUGS = new Set([
82 'auth', 'admin', 'login', 'register', 'logout',
83 'archive', 'search', 'account', 'sites', 'comments',
84 'posts', 'media', 'audio', 'forum',
85 'tag', 'type', 'user', 'users', 'artiesten', 'leden', 'favorieten', 'feed.xml', 'atom.xml', 'sitemap.xml',
86 'manifest.webmanifest', 'sw.js', 'favicon.ico', 'favicon.svg', 'assets',
87 'authorize_interaction', 'fediverse', 'tijdlijn', 'meldingen', 'blokkeren',
88]);
89
90/**
91 * Parse the form's `pinned` field into a non-negative integer rank.
92 * Empty / undefined / NaN / negative โ†’ 0 (= not pinned).
93 * Otherwise: integer rank (1 = top of pinned stack, 2 = below, ...).
94 *
95 * Multiple posts CAN share the same rank โ€” UI shows them tiebroken by
96 * published_at DESC. Saying #2 twice doesn't error, it just duplicates.
97 * (We don't enforce uniqueness at this layer because race conditions and
98 * "swap two ranks" workflows are easier without a UNIQUE constraint.)
99 */
100function parsePinnedRank(raw) {
101 const n = parseInt(raw, 10);
102 if (!Number.isFinite(n) || n < 0) return 0;
103 return n;
104}
105
106// ==================== HOME (Posts list) ====================
107router.get('/', (req, res) => {
108 const site = res.locals.site;
109
110 if (!site) {
111 return renderPage(req, res, 'pages/welcome', {
112 pageTitle: 'Welcome',
113 bodyClass: 'on-special',
114 });
115 }
116
117 // Pinned first โ€” ordered by their rank (1 = top, 2 = below, etc).
118 // pinned column is now an integer rank: 0 = not pinned, 1+ = pinned at
119 // that position. Older boolean usage where pinned was always 1 still
120 // works because integer ranks 1, 2, 3 sort the same as a flat 1.
121 const pinnedPosts = db.prepare(`
122 SELECT p.*, u.username as author_username
123 FROM posts p JOIN users u ON p.author_id = u.id
124 WHERE p.site_id = ? AND p.status = 'published' AND p.pinned > 0
125 ORDER BY p.pinned ASC, p.published_at DESC
126 `).all(site.id);
127
128 // Regular posts: anything with pinned = 0
129 const posts = db.prepare(`
130 SELECT p.*, u.username as author_username
131 FROM posts p JOIN users u ON p.author_id = u.id
132 WHERE p.site_id = ? AND p.status = 'published' AND p.pinned = 0
133 ORDER BY p.published_at DESC
134 LIMIT 30
135 `).all(site.id);
136
137 recordPageview(site.id, req);
138
139 renderPage(req, res, 'pages/home', {
140 pinnedPosts,
141 posts,
142 pageTitle: site.title,
143 socialDescr: site.description || site.tagline || '',
144 bodyClass: 'on-home',
145 });
146});
147
148// ==================== NEW POST FORM ====================
149router.get('/posts/new', requireAuth, (req, res) => {
150 const site = res.locals.site;
151 if (!site) return res.status(404).send('Site required');
152 if (!PermissionsService.canCreatePost(req.session.user, site)) {
153 return res.status(403).send('No permission');
154 }
155
156 renderPage(req, res, 'pages/post-edit', {
157 post: {
158 id: uuid(),
159 title: '', slug: '', content: '', excerpt: '',
160 status: 'draft', pinned: 0, tags: [],
161 cover_image_url: '',
162 },
163 isNew: true,
164 pageTitle: 'New post',
165 bodyClass: 'on-special',
166 });
167});
168
169// ==================== CREATE POST ====================
170router.post('/posts/create', requireAuth, (req, res) => {
171 const site = res.locals.site;
172 if (!site || !PermissionsService.canCreatePost(req.session.user, site)) {
173 return res.status(403).send('No permission');
174 }
175
176 const { title, slug, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
177 const fanOnly = req.body.fan_only ? 1 : 0;
178
179 // Content arrives as user-authored HTML from the WYSIWYG editor โ€” sanitize
180 // before storage. Shortcode text tokens like [[track:UUID]] live in text
181 // nodes and pass through untouched.
182 const cleanContent = HtmlSanitizerService.sanitize(content || '');
183
184 // Generate slug from title if empty
185 let finalSlug = (slug || title || '')
186 .toLowerCase()
187 .replace(/[^a-z0-9]+/g, '-')
188 .replace(/^-|-$/g, '');
189
190 if (!finalSlug) return res.status(400).send('Title or slug required');
191 if (RESERVED_SLUGS.has(finalSlug)) finalSlug = `${finalSlug}-post`;
192
193 // Duplicate title/slug? Make it unique automatically (title-2, title-3, โ€ฆ) instead of rejecting.
194 finalSlug = uniqueSlug(site.id, finalSlug);
195
196 const validTypes = new Set(['post', 'foto', 'video', 'audio']);
197 const finalType = validTypes.has(type) ? type : 'post';
198 const postId = uuid();
199 const now = new Date().toISOString();
200 let finalStatus = status || 'draft';
201 let publishedAt = finalStatus === 'published' ? now : null;
202 // Release planning: published + a future publish_at -> 'scheduled'
203 // (the Scheduler makes it live at that moment). Past/empty -> live immediately.
204 let publishAt = null;
205 const pa = Date.parse(req.body.publish_at || '');
206 if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
207 finalStatus = 'scheduled';
208 publishAt = new Date(pa).toISOString();
209 publishedAt = null;
210 }
211
212 db.prepare(`
213 INSERT INTO posts (
214 id, site_id, slug, author_id, title, content, excerpt,
215 status, cover_image_url, pinned, tags, type, noindex, fan_only, publish_at,
216 created_at, updated_at, published_at
217 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
218 `).run(
219 postId, site.id, finalSlug, req.session.user.id,
220 title || finalSlug, cleanContent, excerpt || '',
221 finalStatus, cover_image_url || null, parsePinnedRank(pinned),
222 JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
223 finalType, noindex ? 1 : 0, fanOnly, publishAt,
224 now, now, publishedAt
225 );
226
227 if (finalStatus === 'published') {
228 try {
229 db.prepare(
230 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
231 ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, postId);
232 } catch (e) { /* FTS index issues are non-fatal */ }
233
234 // ActivityPub: federate a freshly published public post to followers.
235 if (!fanOnly) {
236 ActivityPubService.deliverCreate(site, {
237 id: postId, slug: finalSlug, title: title || finalSlug,
238 content: cleanContent, cover_image_url: cover_image_url || null,
239 published_at: publishedAt, created_at: now,
240 }).catch(() => { /* best-effort */ });
241 }
242 }
243
244 // HTMX request -> return redirect header
245 if (req.headers['hx-request']) {
246 res.setHeader('HX-Redirect', `${res.locals.siteUrlBase || ''}/${finalSlug}`);
247 return res.send('OK');
248 }
249
250 res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
251});
252
253// ==================== EDIT POST FORM ====================
254router.get('/posts/:slug/edit', requireAuth, (req, res) => {
255 const site = res.locals.site;
256 if (!site) return res.status(404).send('Site required');
257
258 const post = db.prepare(
259 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
260 ).get(site.id, req.params.slug);
261
262 if (!post) return res.status(404).send('Post not found');
263 if (!PermissionsService.canEditPost(req.session.user, post, site)) {
264 return res.status(403).send('No permission');
265 }
266
267 if (post.tags) {
268 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
269 } else {
270 post.tags = [];
271 }
272
273 renderPage(req, res, 'pages/post-edit', {
274 post,
275 isNew: false,
276 pageTitle: 'Edit: ' + (post.title || 'Untitled'),
277 bodyClass: 'on-special',
278 });
279});
280
281// ==================== SAVE POST ====================
282router.post('/posts/:slug/save', requireAuth, (req, res) => {
283 const site = res.locals.site;
284 if (!site) return res.status(404).send('Site required');
285
286 const post = db.prepare(
287 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
288 ).get(site.id, req.params.slug);
289
290 if (!post) return res.status(404).send('Post not found');
291 if (!PermissionsService.canEditPost(req.session.user, post, site)) {
292 return res.status(403).send('No permission');
293 }
294
295 const { title, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
296 const fanOnly = req.body.fan_only ? 1 : 0;
297 const newSlug = req.body.slug;
298 const action = req.body.action || 'save';
299 const validTypes = new Set(['post', 'foto', 'video', 'audio']);
300 const finalType = validTypes.has(type) ? type : (post.type || 'post');
301
302 // Sanitize before storage โ€” same pipeline as create.
303 const cleanContent = HtmlSanitizerService.sanitize(content || '');
304
305 let finalSlug = post.slug;
306 if (newSlug && newSlug !== post.slug) {
307 const cleaned = newSlug.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
308 const safe = RESERVED_SLUGS.has(cleaned) ? `${cleaned}-post` : cleaned;
309 // Duplicate slug? Make it unique automatically instead of rejecting (own post may keep its slug).
310 finalSlug = uniqueSlug(site.id, safe, post.id);
311 }
312
313 const now = new Date().toISOString();
314 let finalStatus = status || post.status;
315 let publishedAt = post.published_at;
316
317 if (action === 'publish') {
318 finalStatus = 'published';
319 if (!publishedAt) publishedAt = now;
320 }
321
322 // Release planning: published + future publish_at -> 'scheduled'.
323 let publishAt = null;
324 const pa = Date.parse(req.body.publish_at || '');
325 if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
326 finalStatus = 'scheduled';
327 publishAt = new Date(pa).toISOString();
328 publishedAt = null;
329 }
330
331 db.prepare(`
332 UPDATE posts SET
333 title = ?, content = ?, excerpt = ?, status = ?,
334 cover_image_url = ?, pinned = ?, tags = ?,
335 type = ?, noindex = ?, fan_only = ?, publish_at = ?,
336 slug = ?, published_at = ?, updated_at = ?
337 WHERE id = ?
338 `).run(
339 title, cleanContent, excerpt, finalStatus,
340 cover_image_url || null, parsePinnedRank(pinned),
341 JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
342 finalType, noindex ? 1 : 0, fanOnly, publishAt,
343 finalSlug, publishedAt, now, post.id
344 );
345
346 // Update FTS
347 try {
348 db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id);
349 if (finalStatus === 'published') {
350 db.prepare(
351 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
352 ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, post.id);
353 }
354 } catch (e) { /* FTS issues non-fatal */ }
355
356 // ActivityPub: federate when a post BECOMES published (draft/scheduled โ†’ published
357 // via the editor). A brand-new published post is handled in the create route.
358 if (finalStatus === 'published' && post.status !== 'published' && !fanOnly) {
359 ActivityPubService.deliverCreate(site, {
360 id: post.id, slug: finalSlug, title: title || finalSlug,
361 content: cleanContent, cover_image_url: cover_image_url || null,
362 published_at: publishedAt, created_at: post.created_at,
363 }).catch(() => { /* best-effort */ });
364 }
365
366 res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
367});
368
369// ==================== DELETE POST ====================
370router.post('/posts/:slug/delete', requireAuth, (req, res) => {
371 const site = res.locals.site;
372 if (!site) return res.status(404).send('Site required');
373
374 const post = db.prepare(
375 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
376 ).get(site.id, req.params.slug);
377
378 if (!post) return res.status(404).send('Not found');
379 if (!PermissionsService.canDeletePost(req.session.user, post, site)) {
380 return res.status(403).send('No permission');
381 }
382
383 // ActivityPub: tell followers the post is gone (Delete + Tombstone), but only
384 // if it was actually federated (published + not fan-only). Fire before the row
385 // is removed โ€” we still have post.id (= the Note id).
386 if (post.status === 'published' && !post.fan_only) {
387 ActivityPubService.deliverDelete(site, post).catch(() => { /* best-effort */ });
388 }
389
390 // Cascade: comments + FTS row, THEN the post itself.
391 // FK constraints are ON (config/database.js), so a bare DELETE on posts
392 // fails when comments still reference it.
393 const cascade = db.transaction(() => {
394 db.prepare('DELETE FROM comments WHERE post_id = ?').run(post.id);
395 try { db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id); } catch {}
396 db.prepare('DELETE FROM posts WHERE id = ?').run(post.id);
397 });
398 cascade();
399
400 if (req.headers['hx-request']) {
401 res.setHeader('HX-Redirect', res.locals.siteUrlBase || '/');
402 return res.send('OK');
403 }
404 res.redirect(res.locals.siteUrlBase || '/');
405});
406
407// ==================== ARCHIVE ====================
408router.get('/archive', (req, res) => {
409 const site = res.locals.site;
410 if (!site) return res.status(404).send('No site');
411
412 const posts = db.prepare(`
413 SELECT p.*, u.username as author_username
414 FROM posts p JOIN users u ON p.author_id = u.id
415 WHERE p.site_id = ? AND p.status = 'published'
416 ORDER BY p.published_at DESC
417 `).all(site.id);
418
419 // Group by year/month
420 const grouped = {};
421 for (const post of posts) {
422 if (!post.published_at) continue;
423 const d = new Date(post.published_at);
424 const year = d.getFullYear();
425 const month = d.getMonth();
426 const monthName = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'][month];
427
428 if (!grouped[year]) grouped[year] = {};
429 if (!grouped[year][monthName]) grouped[year][monthName] = [];
430 grouped[year][monthName].push(post);
431 }
432
433 renderPage(req, res, 'pages/archive', {
434 grouped,
435 totalPosts: posts.length,
436 pageTitle: 'Archive - ' + site.title,
437 bodyClass: 'on-archive',
438 });
439});
440
441// Local likes/favourites are removed โ€” engagement is fediverse-only now
442// (the โญ on a post likes via the fediverse). No post_likes, no /favorieten.
443
444// Newer/Older neighbours across ALL posts in feed order. Shared by the full
445// post render and the fan gate (premium fan_only) so navigation is consistent
446// everywhere. Solo: within the site (pinned first, then date). Hub: globally by date.
447function postNeighbors(site, post, isHub) {
448 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
449 const ordered = isHub
450 ? db.prepare(`
451 SELECT p.id, p.slug, p.title, p.pinned, s.slug AS site_slug
452 FROM posts p JOIN sites s ON s.id = p.site_id
453 WHERE p.status = 'published'
454 ORDER BY p.published_at DESC
455 `).all()
456 : db.prepare(`
457 SELECT id, slug, title, pinned FROM posts
458 WHERE site_id = ? AND status = 'published'
459 ORDER BY (pinned = 0) ASC, pinned ASC, published_at DESC
460 `).all(site.id);
461 const idx = ordered.findIndex((p) => p.id === post.id);
462 const newerPost = idx > 0 ? ordered[idx - 1] : null;
463 const olderPost = (idx >= 0 && idx < ordered.length - 1) ? ordered[idx + 1] : null;
464 if (newerPost) newerPost._urlBase = urlBaseFor(newerPost);
465 if (olderPost) olderPost._urlBase = urlBaseFor(olderPost);
466 return { newerPost, olderPost };
467}
468
469// ==================== REMOTE INTERACTION (reply to a fediverse post as your site) ====================
470// Standard fediverse "reply from your own server" landing endpoint. A post page
471// elsewhere bounces the visitor here with ?uri=<remote post>; the site owner
472// composes a reply that federates back to that post.
473router.get('/authorize_interaction', requireSiteManager, async (req, res) => {
474 const site = res.locals.site;
475 const uri = (req.query.uri || '').toString();
476 const sent = !!req.query.sent;
477 let target = null;
478 if (!sent) { try { target = await ActivityPubService.resolveRemoteNote(uri); } catch { /* ignore */ } }
479 renderPage(req, res, 'pages/authorize-interaction', {
480 pageTitle: 'Interacteer via de fediverse',
481 bodyClass: 'on-special',
482 uri,
483 target,
484 sent,
485 liked: !!req.query.liked,
486 siteTitle: site ? site.title : '',
487 });
488});
489
490// โญ Like a remote post from your own site (the star flow lands here).
491router.post('/authorize_interaction/like', requireSiteManager, (req, res) => {
492 const site = res.locals.site;
493 const uri = (req.body.uri || '').toString();
494 if (site && uri) {
495 ActivityPubService.resolveRemoteNote(uri)
496 .then((note) => note && ActivityPubService.sendInteraction(site, 'like', note.object_uri || uri, note.actor_uri))
497 .catch((e) => console.warn('[AP] remote like failed:', e.message));
498 }
499 res.redirect('/authorize_interaction?liked=1&uri=' + encodeURIComponent(uri));
500});
501
502router.post('/authorize_interaction', requireSiteManager, (req, res) => {
503 const site = res.locals.site;
504 const uri = (req.body.uri || '').toString();
505 const text = (req.body.text || '').toString();
506 if (site && uri && text.trim()) {
507 // Resolve + deliver in the background so Send responds instantly.
508 ActivityPubService.resolveRemoteNote(uri)
509 .then((parent) => parent && ActivityPubService.deliverReply(site, { postId: parent.localPostId || '', postSlug: null, parent, text }))
510 .catch((e) => console.warn('[AP] remote reply failed:', e.message));
511 }
512 res.redirect('/authorize_interaction?sent=1&uri=' + encodeURIComponent(uri));
513});
514
515// Manage / delete your own outbound fediverse replies (site owner only).
516router.get('/fediverse', requireSiteManager, (req, res) => {
517 const site = res.locals.site;
518 const items = site ? ActivityPubService.listOutbox(site.slug) : [];
519 renderPage(req, res, 'pages/authorize-interaction', {
520 pageTitle: 'Mijn fediverse-reacties', bodyClass: 'on-special',
521 manage: items, uri: '', target: null, sent: false, siteTitle: site ? site.title : '',
522 });
523});
524
525router.post('/fediverse/:id/delete', requireSiteManager, async (req, res) => {
526 const site = res.locals.site;
527 if (site) {
528 try { await ActivityPubService.deliverOutboxDelete(site, req.params.id); }
529 catch (e) { console.warn('[AP] outbox delete failed:', e.message); }
530 }
531 res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/fediverse`);
532});
533
534// ==================== FEDIVERSE CLIENT: home timeline + following ====================
535router.get('/tijdlijn', requireSiteManager, (req, res) => {
536 const site = res.locals.site;
537 const following = site ? ActivityPubService.listFollowing(site.slug) : [];
538 const timeline = site ? ActivityPubService.getTimeline(site.slug, 60) : [];
539 renderPage(req, res, 'pages/timeline', {
540 pageTitle: 'Tijdlijn', bodyClass: 'on-special',
541 following, timeline,
542 success: req.query.success || null, error: req.query.error || null,
543 });
544});
545
546router.post('/tijdlijn/follow', requireSiteManager, async (req, res) => {
547 const site = res.locals.site;
548 const handle = (req.body.handle || '').toString();
549 let q = 'success=' + encodeURIComponent('Volgverzoek verstuurd');
550 if (site && handle.trim()) {
551 try {
552 const r = await ActivityPubService.followActor(site, handle);
553 if (r && r.error) q = 'error=' + encodeURIComponent(r.error === 'not_found' ? 'Account niet gevonden' : (r.error === 'unreachable' ? 'Server onbereikbaar' : 'Volgen mislukt'));
554 else q = 'success=' + encodeURIComponent('Je volgt nu ' + ((r && r.name) || handle));
555 } catch (e) { q = 'error=' + encodeURIComponent('Volgen mislukt'); }
556 }
557 res.redirect('/tijdlijn?' + q);
558});
559
560router.post('/tijdlijn/unfollow', requireSiteManager, async (req, res) => {
561 const site = res.locals.site;
562 const actorUri = (req.body.actor_uri || '').toString();
563 if (site && actorUri) { try { await ActivityPubService.unfollowActor(site, actorUri); } catch (e) { /* ignore */ } }
564 res.redirect('/tijdlijn?success=' + encodeURIComponent('Ontvolgd'));
565});
566
567router.post('/tijdlijn/like', requireSiteManager, async (req, res) => {
568 const site = res.locals.site;
569 if (site) { try { await ActivityPubService.sendInteraction(site, 'like', (req.body.note || '').toString(), (req.body.author || '').toString()); } catch (e) { /* ignore */ } }
570 res.redirect('/tijdlijn?success=' + encodeURIComponent('Geliket โญ'));
571});
572
573router.post('/tijdlijn/boost', requireSiteManager, async (req, res) => {
574 const site = res.locals.site;
575 if (site) { try { await ActivityPubService.sendInteraction(site, 'boost', (req.body.note || '').toString(), (req.body.author || '').toString()); } catch (e) { /* ignore */ } }
576 res.redirect('/tijdlijn?success=' + encodeURIComponent('Geboost ๐Ÿ”'));
577});
578
579// Notifications inbox (new followers + replies/likes/boosts on your posts).
580router.get('/meldingen', requireSiteManager, (req, res) => {
581 const site = res.locals.site;
582 const items = site ? ActivityPubService.getNotifications(site.slug, 80) : [];
583 renderPage(req, res, 'pages/fedi-notifications', { pageTitle: 'Meldingen', bodyClass: 'on-special', items });
584});
585
586// Blocking / defederation (owner-only).
587router.get('/blokkeren', requireSiteManager, (req, res) => {
588 const site = res.locals.site;
589 const blocks = site ? ActivityPubService.listBlocks(site.slug) : [];
590 renderPage(req, res, 'pages/blocks', { pageTitle: 'Blokkeren', bodyClass: 'on-special', blocks, success: req.query.success || null, error: req.query.error || null });
591});
592
593router.post('/blokkeren/add', requireSiteManager, async (req, res) => {
594 const site = res.locals.site;
595 let q = 'success=' + encodeURIComponent('Geblokkeerd');
596 if (site) {
597 try {
598 const r = await ActivityPubService.blockTarget(site, (req.body.target || '').toString());
599 if (r && r.error) q = 'error=' + encodeURIComponent(r.error === 'not_found' ? 'Account niet gevonden' : 'Voer een @handle of domein in');
600 else q = 'success=' + encodeURIComponent(((r && r.label) || '') + ' geblokkeerd');
601 } catch (e) { q = 'error=' + encodeURIComponent('Blokkeren mislukt'); }
602 }
603 const ref = req.get('Referer') || '';
604 res.redirect((ref.includes('/tijdlijn') ? '/tijdlijn?' : '/blokkeren?') + q);
605});
606
607router.post('/blokkeren/remove', requireSiteManager, (req, res) => {
608 const site = res.locals.site;
609 if (site) { try { ActivityPubService.unblock(site, (req.body.target || '').toString()); } catch (e) { /* ignore */ } }
610 res.redirect('/blokkeren?success=' + encodeURIComponent('Deblokkeerd'));
611});
612
613// ==================== VIEW POST (last route รขโ‚ฌโ€ catches /:slug) ====================
614router.get('/:slug', (req, res, next) => {
615 if (RESERVED_SLUGS.has(req.params.slug)) return next();
616
617 const site = res.locals.site;
618 if (!site) return next(); // -> nette 404 catch-all
619
620 const post = db.prepare(`
621 SELECT p.*, u.username as author_username, u.avatar_url as author_avatar
622 FROM posts p JOIN users u ON p.author_id = u.id
623 WHERE p.site_id = ? AND p.slug = ?
624 `).get(site.id, req.params.slug);
625
626 if (!post) return next(); // unknown slug -> clean 404 catch-all
627
628 // Permission to view: published OR (logged in + can edit)
629 if (post.status !== 'published') {
630 const canEdit = req.session?.user && PermissionsService.canEditPost(req.session.user, post, site);
631 if (!canEdit) return res.status(403).send('Not published');
632 }
633
634 // Fan-only preview (premium #3): full content only for logged-in fans.
635 // Anonymous visitors get a clean login gate instead of the content (the title/
636 // teaser may still appear elsewhere as a teaser).
637 if (post.fan_only && !(req.session && req.session.user)) {
638 // Same Newer/Older navigation as on a normal post, so the visitor doesn't get
639 // stuck on the fan gate but can keep browsing.
640 const { newerPost, olderPost } = postNeighbors(site, post, res.locals.tenancy === 'hub');
641 return renderPage(req, res, 'pages/fan-gate', {
642 pageTitle: post.title || 'Alleen voor fans',
643 bodyClass: 'on-special',
644 fgTitle: post.title || '',
645 fgNext: (res.locals.siteUrlBase || '') + '/' + post.slug,
646 newerPost,
647 olderPost,
648 });
649 }
650
651 // Statistics: count the view (skips admins + unpublished own-preview).
652 if (post.status === 'published') recordPostView(post, req);
653
654 // Render content. Content is now user-authored HTML (already sanitized on
655 // save). The pipeline still adds autoembed iframes and shortcode embeds:
656 // stored HTML โ†’ autoembed โ†’ [[track]]/[[album]]/[[playlist]] โ†’ response
657 let html = post.content || '';
658 if (audioEnabled()) {
659 if (site.enable_audio_player !== 0) {
660 html = AudioEmbedService.autoembed(html);
661 html = AudioEmbedService.embedMediaShortcodes(html);
662 html = AudioEmbedService.embedExternalLinkShortcodes(html);
663
664 // Fetch any tracks referenced by [[track:id]] in this post.
665 // Cheap to do unconditionally โ€” only matches if the post actually has shortcodes.
666 const trackIds = [...html.matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)].map(m => m[1]);
667 if (trackIds.length) {
668 const placeholders = trackIds.map(() => '?').join(',');
669 const rows = db.prepare(`
670 SELECT t.id, t.title, t.artist, t.cover_url, t.credit, t.license,
671 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
672 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
673 WHERE t.site_id = ? AND t.id IN (${placeholders})
674 `).all(site.id, ...trackIds);
675 const byId = new Map(rows.map(r => [r.id, r]));
676 html = AudioEmbedService.embedTrackShortcodes(html, (id) => {
677 const r = byId.get(id);
678 if (!r) return null;
679 return {
680 id: r.id,
681 title: r.title,
682 artist: r.artist,
683 cover: r.cover_url,
684 credit: r.credit || '',
685 license: r.license || '',
686 link_spotify: r.link_spotify || '',
687 link_youtube: r.link_youtube || '',
688 link_soundcloud: r.link_soundcloud || '',
689 url: r.filename ? audioUrl(r.filename) : '', // '' = link-only track
690 };
691 });
692 }
693
694 // Album shortcodes: [[album:Some Album Name]]
695 const albumNames = [...html.matchAll(/\[\[album:([^\]]+)\]\]/g)].map(m => m[1].trim());
696 if (albumNames.length) {
697 const placeholders = albumNames.map(() => '?').join(',');
698 const albumRows = db.prepare(`
699 SELECT t.id, t.title, t.artist, t.album, t.cover_url, t.position,
700 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
701 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
702 WHERE t.site_id = ? AND t.album IN (${placeholders})
703 ORDER BY t.position ASC, t.created_at ASC
704 `).all(site.id, ...albumNames);
705 const byAlbum = new Map();
706 for (const r of albumRows) {
707 // Link-only tracks (no file) remain in the album overview (url '').
708 if (!byAlbum.has(r.album)) byAlbum.set(r.album, []);
709 byAlbum.get(r.album).push({
710 id: r.id,
711 url: r.filename ? audioUrl(r.filename) : '',
712 title: r.title || 'Untitled',
713 artist: r.artist || '',
714 cover: r.cover_url || '',
715 link_spotify: r.link_spotify || '',
716 link_youtube: r.link_youtube || '',
717 link_soundcloud: r.link_soundcloud || '',
718 });
719 }
720 html = AudioEmbedService.embedAlbumShortcodes(html, (name) => {
721 const tracks = byAlbum.get(name);
722 if (!tracks || !tracks.length) return null;
723 return {
724 title: name,
725 artist: tracks[0].artist || '',
726 cover: tracks[0].cover || '',
727 tracks,
728 };
729 });
730 }
731
732 // Playlist shortcodes: [[playlist:some-slug-id]] โ€” first-class entity.
733 // Editing the playlist propagates to every post that embeds it.
734 const playlistIds = [...html.matchAll(/\[\[playlist:([a-z0-9][a-z0-9-]*)\]\]/gi)]
735 .map(m => m[1].toLowerCase());
736 if (playlistIds.length) {
737 const isAdmin = req.session?.user?.role === 'god';
738 html = AudioEmbedService.embedPlaylistShortcodes(html, (id) => {
739 return PlaylistService.get(site.id, id, audioUrl);
740 }, { isAdmin });
741 }
742 }
743 } else {
744 // LITE mode (KLONKT_AUDIO=off): no own audio (no ffmpeg/stream route).
745 // External embeds (YouTube/SoundCloud/Spotify) remain; the own-audio
746 // shortcodes ([[track]]/[[album]]/[[playlist]]) are cleanly stripped.
747 html = AudioEmbedService.autoembed(html);
748 html = AudioEmbedService.embedMediaShortcodes(html);
749 html = AudioEmbedService.embedExternalLinkShortcodes(html);
750 html = html.replace(/\[\[(track|album|playlist):[^\]]+\]\]/gi, '');
751 }
752 post.content_html = html;
753
754 if (post.tags) {
755 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
756 } else {
757 post.tags = [];
758 }
759
760 // Native comments removed: social interaction is fediverse-only (see the
761 // "From the fediverse" section below).
762
763 // Prev / next chronological (kept for back-compat โ€” "post-nav" feature
764 // below the article still uses these as a simple linear navigation).
765 // Hub mode: Related posts + Newer/Older pull from ALL users (all sites),
766 // newest first. Solo mode: within the current site (old behaviour).
767 const isHub = res.locals.tenancy === 'hub';
768 // Per-post URL base: in hub a link points to /user/<site-slug>/<post-slug>.
769 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
770
771 // Newer/Older across ALL posts (shared helper โ€” also used by the fan gate).
772 const { newerPost, olderPost } = postNeighbors(site, post, isHub);
773
774 // โ”€โ”€ Related posts: same-tag matching with recency fallback โ”€โ”€โ”€โ”€โ”€
775 // Fetch ~50 candidates, score by tag overlap, take top 3.
776 // Excluding self via `id != ?`.
777 const candidates = isHub
778 ? db.prepare(`
779 SELECT p.id, p.slug, p.title, p.cover_image_url, p.published_at, p.tags, s.slug AS site_slug
780 FROM posts p JOIN sites s ON s.id = p.site_id
781 WHERE p.status = 'published' AND p.id != ?
782 ORDER BY p.published_at DESC LIMIT 50
783 `).all(post.id)
784 : db.prepare(`
785 SELECT id, slug, title, cover_image_url, published_at, tags
786 FROM posts
787 WHERE site_id = ? AND status = 'published' AND id != ?
788 ORDER BY published_at DESC LIMIT 50
789 `).all(site.id, post.id);
790
791 // Parse tags JSON safely; missing/malformed โ†’ empty array.
792 const parseTags = (raw) => {
793 if (!raw) return [];
794 try {
795 const v = JSON.parse(raw);
796 return Array.isArray(v) ? v.map(String) : [];
797 } catch { return []; }
798 };
799
800 const myTags = new Set(parseTags(post.tags));
801 let relatedPosts;
802 if (myTags.size > 0) {
803 // Score = number of overlapping tags. Posts with zero overlap are
804 // included only if we don't have 3 with-overlap candidates.
805 const scored = candidates.map(p => {
806 const theirTags = parseTags(p.tags);
807 const overlap = theirTags.reduce((n, t) => n + (myTags.has(t) ? 1 : 0), 0);
808 return { ...p, _overlap: overlap };
809 });
810 const withOverlap = scored.filter(p => p._overlap > 0)
811 .sort((a, b) => b._overlap - a._overlap || new Date(b.published_at) - new Date(a.published_at));
812 if (withOverlap.length >= 3) {
813 relatedPosts = withOverlap.slice(0, 3);
814 } else {
815 // Pad with most-recent non-overlap posts so the section is never empty
816 const overlapIds = new Set(withOverlap.map(p => p.id));
817 const filler = candidates.filter(p => !overlapIds.has(p.id));
818 relatedPosts = [...withOverlap, ...filler].slice(0, 3);
819 }
820 } else {
821 // No tags on current post โ†’ just show 3 most-recent
822 relatedPosts = candidates.slice(0, 3);
823 }
824 // Strip the internal _overlap field before sending to view
825 relatedPosts = relatedPosts.map(({ _overlap, tags, ...rest }) => ({ ...rest, _urlBase: urlBaseFor(rest) }));
826
827 // Inbound fediverse activity (threaded) for this post.
828 let fediverse = { thread: [], likeCount: 0, announceCount: 0, total: 0 };
829 try {
830 const _apBase = (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
831 fediverse = ActivityPubService.getInteractions(post.id, _apBase, site);
832 } catch { /* non-fatal */ }
833 // Owner/admin of this site may reply back to a fediverse interaction.
834 const canManageSite = !!(req.session?.user && PermissionsService.canAdminSite(req.session.user, site));
835 // Avatar for our own (outbound) fediverse replies = the site's profile photo.
836 const siteAvatar = (site && site.profile_photo) ? site.profile_photo : null;
837
838 renderPage(req, res, 'pages/post', {
839 post,
840 newerPost,
841 olderPost,
842 relatedPosts,
843 fediverse,
844 canManageSite,
845 siteAvatar,
846 pageTitle: post.title + ' - ' + site.title,
847 socialDescr: post.excerpt || '',
848 socialImage: post.cover_image_url || '',
849 bodyClass: 'on-post',
850 });
851});
852
853// โ”€โ”€ Reply back to a fediverse interaction (site owner/admin only) โ”€โ”€
854router.post('/posts/:slug/fedi-reply', requireSiteManager, async (req, res) => {
855 const site = res.locals.site;
856 if (!site) return res.status(404).send('Site required');
857 const post = db.prepare('SELECT id, slug FROM posts WHERE site_id = ? AND slug = ?').get(site.id, req.params.slug);
858 if (!post) return res.status(404).send('Not found');
859 const parent = ActivityPubService.getInteractionById(req.body.interaction_id);
860 const text = (req.body.text || '').toString();
861 if (parent && parent.post_id === post.id && text.trim()) {
862 try {
863 await ActivityPubService.deliverReply(site, { postId: post.id, postSlug: post.slug, parent, text });
864 } catch (e) { console.warn('[AP] reply send failed:', e.message); }
865 }
866 res.redirect(`${res.locals.siteUrlBase || ''}/${post.slug}#fediverse`);
867});
868
869export default router;
870export { postNeighbors };
Note: See TracBrowser for help on using the repository browser.