source: Klonkt/src/routes/posts.js@ 9cc0f9f

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

feat(fediverse-client): block/defederate accounts & domains

Block an @handle or a whole domain (/blokkeren + ๐Ÿšซ on timeline items): their
inbound activities are silently dropped (202) and their stored content is purged.
New ap_blocks table + isBlockedAny gate in the inbox. Top-bar bell now points to
the fediverse /meldingen (gated to site managers via canManageFedi) instead of the
dead native notifications.

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

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