source: Klonkt/src/routes/posts.js@ 2279f80

main
Last change on this file since 2279f80 was 0aa23cf, checked in by Robin Genis <roboburr@…>, 3 months ago

fix(fediverse): ⭐ star now actually likes (was landing on the reply page)

The interaction page was reply-only, so clicking ⭐ (which bounces to
/authorize_interaction) dumped you on the reply composer. Added a ⭐ Like button
(+ POST /authorize_interaction/like → sendInteraction) and a 'liked' confirmation,
so the star flow completes with a real Like. Reply stays as a secondary action.

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

  • Property mode set to 100644
File size: 38.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 } 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: 'Interacteer via de fediverse',
525 bodyClass: 'on-special',
526 uri,
527 target,
528 sent,
529 liked: !!req.query.liked,
530 siteTitle: site ? site.title : '',
531 });
532});
533
534// ⭐ Like a remote post from your own site (the star flow lands here).
535router.post('/authorize_interaction/like', requireSiteManager, (req, res) => {
536 const site = res.locals.site;
537 const uri = (req.body.uri || '').toString();
538 if (site && uri) {
539 ActivityPubService.resolveRemoteNote(uri)
540 .then((note) => note && ActivityPubService.sendInteraction(site, 'like', note.object_uri || uri, note.actor_uri))
541 .catch((e) => console.warn('[AP] remote like failed:', e.message));
542 }
543 res.redirect('/authorize_interaction?liked=1&uri=' + encodeURIComponent(uri));
544});
545
546router.post('/authorize_interaction', requireSiteManager, (req, res) => {
547 const site = res.locals.site;
548 const uri = (req.body.uri || '').toString();
549 const text = (req.body.text || '').toString();
550 if (site && uri && text.trim()) {
551 // Resolve + deliver in the background so Send responds instantly.
552 ActivityPubService.resolveRemoteNote(uri)
553 .then((parent) => parent && ActivityPubService.deliverReply(site, { postId: parent.localPostId || '', postSlug: null, parent, text }))
554 .catch((e) => console.warn('[AP] remote reply failed:', e.message));
555 }
556 res.redirect('/authorize_interaction?sent=1&uri=' + encodeURIComponent(uri));
557});
558
559// Manage / delete your own outbound fediverse replies (site owner only).
560router.get('/fediverse', requireSiteManager, (req, res) => {
561 const site = res.locals.site;
562 const items = site ? ActivityPubService.listOutbox(site.slug) : [];
563 renderPage(req, res, 'pages/authorize-interaction', {
564 pageTitle: 'Mijn fediverse-reacties', bodyClass: 'on-special',
565 manage: items, uri: '', target: null, sent: false, siteTitle: site ? site.title : '',
566 });
567});
568
569router.post('/fediverse/:id/delete', requireSiteManager, async (req, res) => {
570 const site = res.locals.site;
571 if (site) {
572 try { await ActivityPubService.deliverOutboxDelete(site, req.params.id); }
573 catch (e) { console.warn('[AP] outbox delete failed:', e.message); }
574 }
575 res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/fediverse`);
576});
577
578// ==================== FEDIVERSE CLIENT: home timeline + following ====================
579router.get('/tijdlijn', requireSiteManager, (req, res) => {
580 const site = res.locals.site;
581 const following = site ? ActivityPubService.listFollowing(site.slug) : [];
582 const timeline = site ? ActivityPubService.getTimeline(site.slug, 60) : [];
583 renderPage(req, res, 'pages/timeline', {
584 pageTitle: 'Tijdlijn', bodyClass: 'on-special',
585 following, timeline,
586 success: req.query.success || null, error: req.query.error || null,
587 });
588});
589
590router.post('/tijdlijn/follow', requireSiteManager, async (req, res) => {
591 const site = res.locals.site;
592 const handle = (req.body.handle || '').toString();
593 let q = 'success=' + encodeURIComponent('Volgverzoek verstuurd');
594 if (site && handle.trim()) {
595 try {
596 const r = await ActivityPubService.followActor(site, handle);
597 if (r && r.error) q = 'error=' + encodeURIComponent(r.error === 'not_found' ? 'Account niet gevonden' : (r.error === 'unreachable' ? 'Server onbereikbaar' : 'Volgen mislukt'));
598 else q = 'success=' + encodeURIComponent('Je volgt nu ' + ((r && r.name) || handle));
599 } catch (e) { q = 'error=' + encodeURIComponent('Volgen mislukt'); }
600 }
601 res.redirect('/tijdlijn?' + q);
602});
603
604router.post('/tijdlijn/unfollow', requireSiteManager, async (req, res) => {
605 const site = res.locals.site;
606 const actorUri = (req.body.actor_uri || '').toString();
607 if (site && actorUri) { try { await ActivityPubService.unfollowActor(site, actorUri); } catch (e) { /* ignore */ } }
608 res.redirect('/tijdlijn?success=' + encodeURIComponent('Ontvolgd'));
609});
610
611router.post('/tijdlijn/like', requireSiteManager, async (req, res) => {
612 const site = res.locals.site;
613 if (site) { try { await ActivityPubService.sendInteraction(site, 'like', (req.body.note || '').toString(), (req.body.author || '').toString()); } catch (e) { /* ignore */ } }
614 res.redirect('/tijdlijn?success=' + encodeURIComponent('Geliket ⭐'));
615});
616
617router.post('/tijdlijn/boost', requireSiteManager, async (req, res) => {
618 const site = res.locals.site;
619 if (site) { try { await ActivityPubService.sendInteraction(site, 'boost', (req.body.note || '').toString(), (req.body.author || '').toString()); } catch (e) { /* ignore */ } }
620 res.redirect('/tijdlijn?success=' + encodeURIComponent('Geboost 🔁'));
621});
622
623// Notifications inbox (new followers + replies/likes/boosts on your posts).
624router.get('/meldingen', requireSiteManager, (req, res) => {
625 const site = res.locals.site;
626 const items = site ? ActivityPubService.getNotifications(site.slug, 80) : [];
627 renderPage(req, res, 'pages/fedi-notifications', { pageTitle: 'Meldingen', bodyClass: 'on-special', items });
628});
629
630// Blocking / defederation (owner-only).
631router.get('/blokkeren', requireSiteManager, (req, res) => {
632 const site = res.locals.site;
633 const blocks = site ? ActivityPubService.listBlocks(site.slug) : [];
634 renderPage(req, res, 'pages/blocks', { pageTitle: 'Blokkeren', bodyClass: 'on-special', blocks, success: req.query.success || null, error: req.query.error || null });
635});
636
637router.post('/blokkeren/add', requireSiteManager, async (req, res) => {
638 const site = res.locals.site;
639 let q = 'success=' + encodeURIComponent('Geblokkeerd');
640 if (site) {
641 try {
642 const r = await ActivityPubService.blockTarget(site, (req.body.target || '').toString());
643 if (r && r.error) q = 'error=' + encodeURIComponent(r.error === 'not_found' ? 'Account niet gevonden' : 'Voer een @handle of domein in');
644 else q = 'success=' + encodeURIComponent(((r && r.label) || '') + ' geblokkeerd');
645 } catch (e) { q = 'error=' + encodeURIComponent('Blokkeren mislukt'); }
646 }
647 const ref = req.get('Referer') || '';
648 res.redirect((ref.includes('/tijdlijn') ? '/tijdlijn?' : '/blokkeren?') + q);
649});
650
651router.post('/blokkeren/remove', requireSiteManager, (req, res) => {
652 const site = res.locals.site;
653 if (site) { try { ActivityPubService.unblock(site, (req.body.target || '').toString()); } catch (e) { /* ignore */ } }
654 res.redirect('/blokkeren?success=' + encodeURIComponent('Deblokkeerd'));
655});
656
657// ==================== VIEW POST (last route — catches /:slug) ====================
658router.get('/:slug', (req, res, next) => {
659 if (RESERVED_SLUGS.has(req.params.slug)) return next();
660
661 const site = res.locals.site;
662 if (!site) return next(); // -> nette 404 catch-all
663
664 const post = db.prepare(`
665 SELECT p.*, u.username as author_username, u.avatar_url as author_avatar
666 FROM posts p JOIN users u ON p.author_id = u.id
667 WHERE p.site_id = ? AND p.slug = ?
668 `).get(site.id, req.params.slug);
669
670 if (!post) return next(); // unknown slug -> clean 404 catch-all
671
672 // Permission to view: published OR (logged in + can edit)
673 if (post.status !== 'published') {
674 const canEdit = req.session?.user && PermissionsService.canEditPost(req.session.user, post, site);
675 if (!canEdit) return res.status(403).send('Not published');
676 }
677
678 // Fan-only preview (premium #3): full content only for logged-in fans.
679 // Anonymous visitors get a clean login gate instead of the content (the title/
680 // teaser may still appear elsewhere as a teaser).
681 if (post.fan_only && !(req.session && req.session.user)) {
682 // Same Newer/Older navigation as on a normal post, so the visitor doesn't get
683 // stuck on the fan gate but can keep browsing.
684 const { newerPost, olderPost } = postNeighbors(site, post, res.locals.tenancy === 'hub');
685 return renderPage(req, res, 'pages/fan-gate', {
686 pageTitle: post.title || 'Alleen voor fans',
687 bodyClass: 'on-special',
688 fgTitle: post.title || '',
689 fgNext: (res.locals.siteUrlBase || '') + '/' + post.slug,
690 newerPost,
691 olderPost,
692 });
693 }
694
695 // Statistics: count the view (skips admins + unpublished own-preview).
696 if (post.status === 'published') recordPostView(post, req);
697
698 // Render content. Content is now user-authored HTML (already sanitized on
699 // save). The pipeline still adds autoembed iframes and shortcode embeds:
700 // stored HTML → autoembed → [[track]]/[[album]]/[[playlist]] → response
701 let html = post.content || '';
702 if (audioEnabled()) {
703 if (site.enable_audio_player !== 0) {
704 html = AudioEmbedService.autoembed(html);
705 html = AudioEmbedService.embedMediaShortcodes(html);
706 html = AudioEmbedService.embedExternalLinkShortcodes(html);
707
708 // Fetch any tracks referenced by [[track:id]] in this post.
709 // Cheap to do unconditionally — only matches if the post actually has shortcodes.
710 const trackIds = [...html.matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)].map(m => m[1]);
711 if (trackIds.length) {
712 const placeholders = trackIds.map(() => '?').join(',');
713 const rows = db.prepare(`
714 SELECT t.id, t.title, t.artist, t.cover_url, t.credit, t.license,
715 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
716 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
717 WHERE t.site_id = ? AND t.id IN (${placeholders})
718 `).all(site.id, ...trackIds);
719 const byId = new Map(rows.map(r => [r.id, r]));
720 html = AudioEmbedService.embedTrackShortcodes(html, (id) => {
721 const r = byId.get(id);
722 if (!r) return null;
723 return {
724 id: r.id,
725 title: r.title,
726 artist: r.artist,
727 cover: r.cover_url,
728 credit: r.credit || '',
729 license: r.license || '',
730 link_spotify: r.link_spotify || '',
731 link_youtube: r.link_youtube || '',
732 link_soundcloud: r.link_soundcloud || '',
733 url: r.filename ? audioUrl(r.filename) : '', // '' = link-only track
734 };
735 });
736 }
737
738 // Album shortcodes: [[album:Some Album Name]]
739 const albumNames = [...html.matchAll(/\[\[album:([^\]]+)\]\]/g)].map(m => m[1].trim());
740 if (albumNames.length) {
741 const placeholders = albumNames.map(() => '?').join(',');
742 const albumRows = db.prepare(`
743 SELECT t.id, t.title, t.artist, t.album, t.cover_url, t.position,
744 t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
745 FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
746 WHERE t.site_id = ? AND t.album IN (${placeholders})
747 ORDER BY t.position ASC, t.created_at ASC
748 `).all(site.id, ...albumNames);
749 const byAlbum = new Map();
750 for (const r of albumRows) {
751 // Link-only tracks (no file) remain in the album overview (url '').
752 if (!byAlbum.has(r.album)) byAlbum.set(r.album, []);
753 byAlbum.get(r.album).push({
754 id: r.id,
755 url: r.filename ? audioUrl(r.filename) : '',
756 title: r.title || 'Untitled',
757 artist: r.artist || '',
758 cover: r.cover_url || '',
759 link_spotify: r.link_spotify || '',
760 link_youtube: r.link_youtube || '',
761 link_soundcloud: r.link_soundcloud || '',
762 });
763 }
764 html = AudioEmbedService.embedAlbumShortcodes(html, (name) => {
765 const tracks = byAlbum.get(name);
766 if (!tracks || !tracks.length) return null;
767 return {
768 title: name,
769 artist: tracks[0].artist || '',
770 cover: tracks[0].cover || '',
771 tracks,
772 };
773 });
774 }
775
776 // Playlist shortcodes: [[playlist:some-slug-id]] — first-class entity.
777 // Editing the playlist propagates to every post that embeds it.
778 const playlistIds = [...html.matchAll(/\[\[playlist:([a-z0-9][a-z0-9-]*)\]\]/gi)]
779 .map(m => m[1].toLowerCase());
780 if (playlistIds.length) {
781 const isAdmin = req.session?.user?.role === 'god';
782 html = AudioEmbedService.embedPlaylistShortcodes(html, (id) => {
783 return PlaylistService.get(site.id, id, audioUrl);
784 }, { isAdmin });
785 }
786 }
787 } else {
788 // LITE mode (KLONKT_AUDIO=off): no own audio (no ffmpeg/stream route).
789 // External embeds (YouTube/SoundCloud/Spotify) remain; the own-audio
790 // shortcodes ([[track]]/[[album]]/[[playlist]]) are cleanly stripped.
791 html = AudioEmbedService.autoembed(html);
792 html = AudioEmbedService.embedMediaShortcodes(html);
793 html = AudioEmbedService.embedExternalLinkShortcodes(html);
794 html = html.replace(/\[\[(track|album|playlist):[^\]]+\]\]/gi, '');
795 }
796 post.content_html = html;
797
798 if (post.tags) {
799 try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
800 } else {
801 post.tags = [];
802 }
803
804 // Native comments removed: social interaction is fediverse-only (see the
805 // "From the fediverse" section below).
806
807 // Prev / next chronological (kept for back-compat — "post-nav" feature
808 // below the article still uses these as a simple linear navigation).
809 // Hub mode: Related posts + Newer/Older pull from ALL users (all sites),
810 // newest first. Solo mode: within the current site (old behaviour).
811 const isHub = res.locals.tenancy === 'hub';
812 // Per-post URL base: in hub a link points to /user/<site-slug>/<post-slug>.
813 const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
814
815 // Newer/Older across ALL posts (shared helper — also used by the fan gate).
816 const { newerPost, olderPost } = postNeighbors(site, post, isHub);
817
818 // ── Related posts: same-tag matching with recency fallback ─────
819 // Fetch ~50 candidates, score by tag overlap, take top 3.
820 // Excluding self via `id != ?`.
821 const candidates = isHub
822 ? db.prepare(`
823 SELECT p.id, p.slug, p.title, p.cover_image_url, p.published_at, p.tags, s.slug AS site_slug
824 FROM posts p JOIN sites s ON s.id = p.site_id
825 WHERE p.status = 'published' AND p.id != ?
826 ORDER BY p.published_at DESC LIMIT 50
827 `).all(post.id)
828 : db.prepare(`
829 SELECT id, slug, title, cover_image_url, published_at, tags
830 FROM posts
831 WHERE site_id = ? AND status = 'published' AND id != ?
832 ORDER BY published_at DESC LIMIT 50
833 `).all(site.id, post.id);
834
835 // Parse tags JSON safely; missing/malformed → empty array.
836 const parseTags = (raw) => {
837 if (!raw) return [];
838 try {
839 const v = JSON.parse(raw);
840 return Array.isArray(v) ? v.map(String) : [];
841 } catch { return []; }
842 };
843
844 const myTags = new Set(parseTags(post.tags));
845 let relatedPosts;
846 if (myTags.size > 0) {
847 // Score = number of overlapping tags. Posts with zero overlap are
848 // included only if we don't have 3 with-overlap candidates.
849 const scored = candidates.map(p => {
850 const theirTags = parseTags(p.tags);
851 const overlap = theirTags.reduce((n, t) => n + (myTags.has(t) ? 1 : 0), 0);
852 return { ...p, _overlap: overlap };
853 });
854 const withOverlap = scored.filter(p => p._overlap > 0)
855 .sort((a, b) => b._overlap - a._overlap || new Date(b.published_at) - new Date(a.published_at));
856 if (withOverlap.length >= 3) {
857 relatedPosts = withOverlap.slice(0, 3);
858 } else {
859 // Pad with most-recent non-overlap posts so the section is never empty
860 const overlapIds = new Set(withOverlap.map(p => p.id));
861 const filler = candidates.filter(p => !overlapIds.has(p.id));
862 relatedPosts = [...withOverlap, ...filler].slice(0, 3);
863 }
864 } else {
865 // No tags on current post → just show 3 most-recent
866 relatedPosts = candidates.slice(0, 3);
867 }
868 // Strip the internal _overlap field before sending to view
869 relatedPosts = relatedPosts.map(({ _overlap, tags, ...rest }) => ({ ...rest, _urlBase: urlBaseFor(rest) }));
870
871 // Likes / favourites: count + whether the logged-in user liked this post.
872 const likeCount = db.prepare('SELECT COUNT(*) AS c FROM post_likes WHERE post_id = ?').get(post.id).c;
873 const likedByMe = !!(req.session?.user &&
874 db.prepare('SELECT 1 FROM post_likes WHERE post_id = ? AND user_id = ?').get(post.id, req.session.user.id));
875
876 // Inbound fediverse activity (threaded) for this post.
877 let fediverse = { thread: [], likeCount: 0, announceCount: 0, total: 0 };
878 try {
879 const _apBase = (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
880 fediverse = ActivityPubService.getInteractions(post.id, _apBase, site);
881 } catch { /* non-fatal */ }
882 // Owner/admin of this site may reply back to a fediverse interaction.
883 const canManageSite = !!(req.session?.user && PermissionsService.canAdminSite(req.session.user, site));
884 // Avatar for our own (outbound) fediverse replies = the site's profile photo.
885 const siteAvatar = (site && site.profile_photo) ? site.profile_photo : null;
886
887 renderPage(req, res, 'pages/post', {
888 post,
889 newerPost,
890 olderPost,
891 relatedPosts,
892 fediverse,
893 canManageSite,
894 siteAvatar,
895 likeCount,
896 likedByMe,
897 pageTitle: post.title + ' - ' + site.title,
898 socialDescr: post.excerpt || '',
899 socialImage: post.cover_image_url || '',
900 bodyClass: 'on-post',
901 });
902});
903
904// ── Reply back to a fediverse interaction (site owner/admin only) ──
905router.post('/posts/:slug/fedi-reply', requireSiteManager, async (req, res) => {
906 const site = res.locals.site;
907 if (!site) return res.status(404).send('Site required');
908 const post = db.prepare('SELECT id, slug FROM posts WHERE site_id = ? AND slug = ?').get(site.id, req.params.slug);
909 if (!post) return res.status(404).send('Not found');
910 const parent = ActivityPubService.getInteractionById(req.body.interaction_id);
911 const text = (req.body.text || '').toString();
912 if (parent && parent.post_id === post.id && text.trim()) {
913 try {
914 await ActivityPubService.deliverReply(site, { postId: post.id, postSlug: post.slug, parent, text });
915 } catch (e) { console.warn('[AP] reply send failed:', e.message); }
916 }
917 res.redirect(`${res.locals.siteUrlBase || ''}/${post.slug}#fediverse`);
918});
919
920export default router;
921export { postNeighbors };
Note: See TracBrowser for help on using the repository browser.