| 1 | import express from 'express';
|
|---|
| 2 | import { v4 as uuid } from 'uuid';
|
|---|
| 3 | import path from 'path';
|
|---|
| 4 | import fs from 'fs';
|
|---|
| 5 | import { fileURLToPath } from 'url';
|
|---|
| 6 | import multer from 'multer';
|
|---|
| 7 | import ejs from 'ejs';
|
|---|
| 8 | import db from '../config/database.js';
|
|---|
| 9 | import { requireAuth, requireSiteManager, isViewer } from '../middleware/auth.js';
|
|---|
| 10 | import { renderPage } from '../middleware/render.js';
|
|---|
| 11 | import { recordPageview, recordPostView } from '../services/StatsService.js';
|
|---|
| 12 | import PermissionsService from '../services/PermissionsService.js';
|
|---|
| 13 | import MarkdownService from '../services/MarkdownService.js';
|
|---|
| 14 | import HtmlSanitizerService from '../services/HtmlSanitizerService.js';
|
|---|
| 15 | import AudioEmbedService from '../services/AudioEmbedService.js';
|
|---|
| 16 | import PlaylistService from '../services/PlaylistService.js';
|
|---|
| 17 | import { audioEnabled } from '../config/features.js';
|
|---|
| 18 | import { audioUrl } from '../services/AudioStreamService.js';
|
|---|
| 19 | import { toWebp } from '../services/ImageWebpService.js';
|
|---|
| 20 | import ActivityPubService from '../services/ActivityPubService.js';
|
|---|
| 21 |
|
|---|
| 22 | const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|---|
| 23 | const POST_IMAGES_DIR = path.resolve(
|
|---|
| 24 | process.env.POST_IMAGES_PATH ||
|
|---|
| 25 | path.join(__dirname, '..', '..', 'storage', 'media', 'post-images')
|
|---|
| 26 | );
|
|---|
| 27 | fs.mkdirSync(POST_IMAGES_DIR, { recursive: true });
|
|---|
| 28 |
|
|---|
| 29 | const ALLOWED_IMAGE_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
|
|---|
| 30 | const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|---|
| 31 |
|
|---|
| 32 | const 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 | });
|
|---|
| 39 | const 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).
|
|---|
| 55 | function 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 |
|
|---|
| 67 | const 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  into content.
|
|---|
| 72 | router.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 |
|
|---|
| 81 | const 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', 'news', 'following', 'notifications', 'blocking',
|
|---|
| 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 | */
|
|---|
| 100 | function 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) ====================
|
|---|
| 107 | router.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 ====================
|
|---|
| 149 | router.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 ====================
|
|---|
| 170 | router.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 | const nsfw = req.body.nsfw ? 1 : 0;
|
|---|
| 179 | const cw = (req.body.content_warning || '').trim().slice(0, 200);
|
|---|
| 180 |
|
|---|
| 181 | // Content arrives as user-authored HTML from the WYSIWYG editor — sanitize
|
|---|
| 182 | // before storage. Shortcode text tokens like [[track:UUID]] live in text
|
|---|
| 183 | // nodes and pass through untouched.
|
|---|
| 184 | const cleanContent = HtmlSanitizerService.sanitize(content || '');
|
|---|
| 185 |
|
|---|
| 186 | // Generate slug from title if empty
|
|---|
| 187 | let finalSlug = (slug || title || '')
|
|---|
| 188 | .toLowerCase()
|
|---|
| 189 | .replace(/[^a-z0-9]+/g, '-')
|
|---|
| 190 | .replace(/^-|-$/g, '');
|
|---|
| 191 |
|
|---|
| 192 | if (!finalSlug) return res.status(400).send('Title or slug required');
|
|---|
| 193 | if (RESERVED_SLUGS.has(finalSlug)) finalSlug = `${finalSlug}-post`;
|
|---|
| 194 |
|
|---|
| 195 | // Duplicate title/slug? Make it unique automatically (title-2, title-3, …) instead of rejecting.
|
|---|
| 196 | finalSlug = uniqueSlug(site.id, finalSlug);
|
|---|
| 197 |
|
|---|
| 198 | const validTypes = new Set(['post', 'foto', 'video', 'audio']);
|
|---|
| 199 | const finalType = validTypes.has(type) ? type : 'post';
|
|---|
| 200 | const postId = uuid();
|
|---|
| 201 | const now = new Date().toISOString();
|
|---|
| 202 | let finalStatus = status || 'draft';
|
|---|
| 203 | let publishedAt = finalStatus === 'published' ? now : null;
|
|---|
| 204 | // Release planning: published + a future publish_at -> 'scheduled'
|
|---|
| 205 | // (the Scheduler makes it live at that moment). Past/empty -> live immediately.
|
|---|
| 206 | let publishAt = null;
|
|---|
| 207 | const pa = Date.parse(req.body.publish_at || '');
|
|---|
| 208 | if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
|
|---|
| 209 | finalStatus = 'scheduled';
|
|---|
| 210 | publishAt = new Date(pa).toISOString();
|
|---|
| 211 | publishedAt = null;
|
|---|
| 212 | }
|
|---|
| 213 |
|
|---|
| 214 | db.prepare(`
|
|---|
| 215 | INSERT INTO posts (
|
|---|
| 216 | id, site_id, slug, author_id, title, content, excerpt,
|
|---|
| 217 | status, cover_image_url, pinned, tags, type, noindex, fan_only, nsfw, content_warning, publish_at,
|
|---|
| 218 | created_at, updated_at, published_at
|
|---|
| 219 | ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|---|
| 220 | `).run(
|
|---|
| 221 | postId, site.id, finalSlug, req.session.user.id,
|
|---|
| 222 | title || finalSlug, cleanContent, excerpt || '',
|
|---|
| 223 | finalStatus, cover_image_url || null, parsePinnedRank(pinned),
|
|---|
| 224 | JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
|
|---|
| 225 | finalType, noindex ? 1 : 0, fanOnly, nsfw, cw, publishAt,
|
|---|
| 226 | now, now, publishedAt
|
|---|
| 227 | );
|
|---|
| 228 |
|
|---|
| 229 | if (finalStatus === 'published') {
|
|---|
| 230 | try {
|
|---|
| 231 | db.prepare(
|
|---|
| 232 | 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
|
|---|
| 233 | ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, postId);
|
|---|
| 234 | } catch (e) { /* FTS index issues are non-fatal */ }
|
|---|
| 235 |
|
|---|
| 236 | // ActivityPub: federate a freshly published post to followers. fan_only → delivered
|
|---|
| 237 | // to followers but addressed followers-only (option A: "fans" = your fedi followers).
|
|---|
| 238 | if (status === 'published') {
|
|---|
| 239 | ActivityPubService.deliverCreate(site, {
|
|---|
| 240 | id: postId, slug: finalSlug, title: title || finalSlug,
|
|---|
| 241 | content: cleanContent, cover_image_url: cover_image_url || null,
|
|---|
| 242 | published_at: publishedAt, created_at: now, fan_only: fanOnly, nsfw, content_warning: cw,
|
|---|
| 243 | }).catch(() => { /* best-effort */ });
|
|---|
| 244 | }
|
|---|
| 245 | }
|
|---|
| 246 |
|
|---|
| 247 | // HTMX request -> return redirect header
|
|---|
| 248 | if (req.headers['hx-request']) {
|
|---|
| 249 | res.setHeader('HX-Redirect', `${res.locals.siteUrlBase || ''}/${finalSlug}`);
|
|---|
| 250 | return res.send('OK');
|
|---|
| 251 | }
|
|---|
| 252 |
|
|---|
| 253 | res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
|
|---|
| 254 | });
|
|---|
| 255 |
|
|---|
| 256 | // ==================== EDIT POST FORM ====================
|
|---|
| 257 | router.get('/posts/:slug/edit', requireAuth, (req, res) => {
|
|---|
| 258 | const site = res.locals.site;
|
|---|
| 259 | if (!site) return res.status(404).send('Site required');
|
|---|
| 260 |
|
|---|
| 261 | const post = db.prepare(
|
|---|
| 262 | 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
|
|---|
| 263 | ).get(site.id, req.params.slug);
|
|---|
| 264 |
|
|---|
| 265 | if (!post) return res.status(404).send('Post not found');
|
|---|
| 266 | if (!PermissionsService.canEditPost(req.session.user, post, site)) {
|
|---|
| 267 | return res.status(403).send('No permission');
|
|---|
| 268 | }
|
|---|
| 269 |
|
|---|
| 270 | if (post.tags) {
|
|---|
| 271 | try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
|
|---|
| 272 | } else {
|
|---|
| 273 | post.tags = [];
|
|---|
| 274 | }
|
|---|
| 275 |
|
|---|
| 276 | renderPage(req, res, 'pages/post-edit', {
|
|---|
| 277 | post,
|
|---|
| 278 | isNew: false,
|
|---|
| 279 | pageTitle: 'Edit: ' + (post.title || 'Untitled'),
|
|---|
| 280 | bodyClass: 'on-special',
|
|---|
| 281 | });
|
|---|
| 282 | });
|
|---|
| 283 |
|
|---|
| 284 | // ==================== SAVE POST ====================
|
|---|
| 285 | router.post('/posts/:slug/save', requireAuth, (req, res) => {
|
|---|
| 286 | const site = res.locals.site;
|
|---|
| 287 | if (!site) return res.status(404).send('Site required');
|
|---|
| 288 |
|
|---|
| 289 | const post = db.prepare(
|
|---|
| 290 | 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
|
|---|
| 291 | ).get(site.id, req.params.slug);
|
|---|
| 292 |
|
|---|
| 293 | if (!post) return res.status(404).send('Post not found');
|
|---|
| 294 | if (!PermissionsService.canEditPost(req.session.user, post, site)) {
|
|---|
| 295 | return res.status(403).send('No permission');
|
|---|
| 296 | }
|
|---|
| 297 |
|
|---|
| 298 | const { title, content, excerpt, status, pinned, cover_image_url, tags, noindex, type } = req.body;
|
|---|
| 299 | const fanOnly = req.body.fan_only ? 1 : 0;
|
|---|
| 300 | const nsfw = req.body.nsfw ? 1 : 0;
|
|---|
| 301 | const cw = (req.body.content_warning || '').trim().slice(0, 200);
|
|---|
| 302 | const newSlug = req.body.slug;
|
|---|
| 303 | const action = req.body.action || 'save';
|
|---|
| 304 | const validTypes = new Set(['post', 'foto', 'video', 'audio']);
|
|---|
| 305 | const finalType = validTypes.has(type) ? type : (post.type || 'post');
|
|---|
| 306 |
|
|---|
| 307 | // Sanitize before storage — same pipeline as create.
|
|---|
| 308 | const cleanContent = HtmlSanitizerService.sanitize(content || '');
|
|---|
| 309 |
|
|---|
| 310 | let finalSlug = post.slug;
|
|---|
| 311 | if (newSlug && newSlug !== post.slug) {
|
|---|
| 312 | const cleaned = newSlug.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
|---|
| 313 | const safe = RESERVED_SLUGS.has(cleaned) ? `${cleaned}-post` : cleaned;
|
|---|
| 314 | // Duplicate slug? Make it unique automatically instead of rejecting (own post may keep its slug).
|
|---|
| 315 | finalSlug = uniqueSlug(site.id, safe, post.id);
|
|---|
| 316 | }
|
|---|
| 317 |
|
|---|
| 318 | const now = new Date().toISOString();
|
|---|
| 319 | let finalStatus = status || post.status;
|
|---|
| 320 | let publishedAt = post.published_at;
|
|---|
| 321 |
|
|---|
| 322 | if (action === 'publish') {
|
|---|
| 323 | finalStatus = 'published';
|
|---|
| 324 | if (!publishedAt) publishedAt = now;
|
|---|
| 325 | }
|
|---|
| 326 |
|
|---|
| 327 | // Release planning: published + future publish_at -> 'scheduled'.
|
|---|
| 328 | let publishAt = null;
|
|---|
| 329 | const pa = Date.parse(req.body.publish_at || '');
|
|---|
| 330 | if (req.body.schedule_enabled && finalStatus === 'published' && Number.isFinite(pa) && pa > Date.now()) {
|
|---|
| 331 | finalStatus = 'scheduled';
|
|---|
| 332 | publishAt = new Date(pa).toISOString();
|
|---|
| 333 | publishedAt = null;
|
|---|
| 334 | }
|
|---|
| 335 |
|
|---|
| 336 | db.prepare(`
|
|---|
| 337 | UPDATE posts SET
|
|---|
| 338 | title = ?, content = ?, excerpt = ?, status = ?,
|
|---|
| 339 | cover_image_url = ?, pinned = ?, tags = ?,
|
|---|
| 340 | type = ?, noindex = ?, fan_only = ?, nsfw = ?, content_warning = ?, publish_at = ?,
|
|---|
| 341 | slug = ?, published_at = ?, updated_at = ?
|
|---|
| 342 | WHERE id = ?
|
|---|
| 343 | `).run(
|
|---|
| 344 | title, cleanContent, excerpt, finalStatus,
|
|---|
| 345 | cover_image_url || null, parsePinnedRank(pinned),
|
|---|
| 346 | JSON.stringify((tags || '').split(',').map(t => t.trim()).filter(Boolean)),
|
|---|
| 347 | finalType, noindex ? 1 : 0, fanOnly, nsfw, cw, publishAt,
|
|---|
| 348 | finalSlug, publishedAt, now, post.id
|
|---|
| 349 | );
|
|---|
| 350 |
|
|---|
| 351 | // Update FTS
|
|---|
| 352 | try {
|
|---|
| 353 | db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id);
|
|---|
| 354 | if (finalStatus === 'published') {
|
|---|
| 355 | db.prepare(
|
|---|
| 356 | 'INSERT INTO posts_fts(content, title, author, post_id) VALUES (?, ?, ?, ?)'
|
|---|
| 357 | ).run(HtmlSanitizerService.toPlainText(cleanContent), title || '', req.session.user.username, post.id);
|
|---|
| 358 | }
|
|---|
| 359 | } catch (e) { /* FTS issues non-fatal */ }
|
|---|
| 360 |
|
|---|
| 361 | // ActivityPub: federate edits to followers. A post that BECOMES published →
|
|---|
| 362 | // Create (new post); an already-published post that's edited → Update (so
|
|---|
| 363 | // Mastodon refreshes its cached copy). fan_only → followers-only (option A).
|
|---|
| 364 | if (finalStatus === 'published') {
|
|---|
| 365 | const apPost = {
|
|---|
| 366 | id: post.id, slug: finalSlug, title: title || finalSlug,
|
|---|
| 367 | content: cleanContent, cover_image_url: cover_image_url || null,
|
|---|
| 368 | published_at: publishedAt, created_at: post.created_at, fan_only: fanOnly, nsfw, content_warning: cw,
|
|---|
| 369 | };
|
|---|
| 370 | if (post.status !== 'published') ActivityPubService.deliverCreate(site, apPost).catch(() => { /* best-effort */ });
|
|---|
| 371 | else ActivityPubService.deliverUpdate(site, apPost).catch(() => { /* best-effort */ });
|
|---|
| 372 | }
|
|---|
| 373 |
|
|---|
| 374 | // Pin/unpin/reorder → push Add/Remove activities so followers' instances update the
|
|---|
| 375 | // pinned order immediately (reliable, unlike re-fetching the cached featured collection).
|
|---|
| 376 | if ((post.pinned || 0) !== parsePinnedRank(pinned)) {
|
|---|
| 377 | const unpinned = (post.pinned || 0) > 0 && parsePinnedRank(pinned) === 0 ? [post.id] : [];
|
|---|
| 378 | ActivityPubService.resyncFeaturedPins(site, unpinned).catch(() => { /* best-effort */ });
|
|---|
| 379 | }
|
|---|
| 380 |
|
|---|
| 381 | res.redirect(`${res.locals.siteUrlBase || ''}/${finalSlug}`);
|
|---|
| 382 | });
|
|---|
| 383 |
|
|---|
| 384 | // ==================== DELETE POST ====================
|
|---|
| 385 | router.post('/posts/:slug/delete', requireAuth, (req, res) => {
|
|---|
| 386 | const site = res.locals.site;
|
|---|
| 387 | if (!site) return res.status(404).send('Site required');
|
|---|
| 388 |
|
|---|
| 389 | const post = db.prepare(
|
|---|
| 390 | 'SELECT * FROM posts WHERE site_id = ? AND slug = ?'
|
|---|
| 391 | ).get(site.id, req.params.slug);
|
|---|
| 392 |
|
|---|
| 393 | if (!post) return res.status(404).send('Not found');
|
|---|
| 394 | if (!PermissionsService.canDeletePost(req.session.user, post, site)) {
|
|---|
| 395 | return res.status(403).send('No permission');
|
|---|
| 396 | }
|
|---|
| 397 |
|
|---|
| 398 | // ActivityPub: tell followers the post is gone (Delete + Tombstone) if it was
|
|---|
| 399 | // federated (any published post now federates — fan_only goes followers-only).
|
|---|
| 400 | // Fire before the row is removed — we still have post.id (= the Note id).
|
|---|
| 401 | if (post.status === 'published') {
|
|---|
| 402 | ActivityPubService.deliverDelete(site, post).catch(() => { /* best-effort */ });
|
|---|
| 403 | }
|
|---|
| 404 |
|
|---|
| 405 | // Cascade: comments + FTS row, THEN the post itself.
|
|---|
| 406 | // FK constraints are ON (config/database.js), so a bare DELETE on posts
|
|---|
| 407 | // fails when comments still reference it.
|
|---|
| 408 | const cascade = db.transaction(() => {
|
|---|
| 409 | db.prepare('DELETE FROM comments WHERE post_id = ?').run(post.id);
|
|---|
| 410 | try { db.prepare('DELETE FROM posts_fts WHERE post_id = ?').run(post.id); } catch {}
|
|---|
| 411 | db.prepare('DELETE FROM posts WHERE id = ?').run(post.id);
|
|---|
| 412 | });
|
|---|
| 413 | cascade();
|
|---|
| 414 |
|
|---|
| 415 | if (req.headers['hx-request']) {
|
|---|
| 416 | res.setHeader('HX-Redirect', res.locals.siteUrlBase || '/');
|
|---|
| 417 | return res.send('OK');
|
|---|
| 418 | }
|
|---|
| 419 | res.redirect(res.locals.siteUrlBase || '/');
|
|---|
| 420 | });
|
|---|
| 421 |
|
|---|
| 422 | // ==================== ARCHIVE ====================
|
|---|
| 423 | router.get('/archive', (req, res) => {
|
|---|
| 424 | const site = res.locals.site;
|
|---|
| 425 | if (!site) return res.status(404).send('No site');
|
|---|
| 426 |
|
|---|
| 427 | const posts = db.prepare(`
|
|---|
| 428 | SELECT p.*, u.username as author_username
|
|---|
| 429 | FROM posts p JOIN users u ON p.author_id = u.id
|
|---|
| 430 | WHERE p.site_id = ? AND p.status = 'published'
|
|---|
| 431 | ORDER BY p.published_at DESC
|
|---|
| 432 | `).all(site.id);
|
|---|
| 433 |
|
|---|
| 434 | // Group by year/month
|
|---|
| 435 | const grouped = {};
|
|---|
| 436 | for (const post of posts) {
|
|---|
| 437 | if (!post.published_at) continue;
|
|---|
| 438 | const d = new Date(post.published_at);
|
|---|
| 439 | const year = d.getFullYear();
|
|---|
| 440 | const month = d.getMonth();
|
|---|
| 441 | const monthName = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'][month];
|
|---|
| 442 |
|
|---|
| 443 | if (!grouped[year]) grouped[year] = {};
|
|---|
| 444 | if (!grouped[year][monthName]) grouped[year][monthName] = [];
|
|---|
| 445 | grouped[year][monthName].push(post);
|
|---|
| 446 | }
|
|---|
| 447 |
|
|---|
| 448 | renderPage(req, res, 'pages/archive', {
|
|---|
| 449 | grouped,
|
|---|
| 450 | totalPosts: posts.length,
|
|---|
| 451 | pageTitle: 'Archive - ' + site.title,
|
|---|
| 452 | bodyClass: 'on-archive',
|
|---|
| 453 | });
|
|---|
| 454 | });
|
|---|
| 455 |
|
|---|
| 456 | // Local likes/favourites are removed — engagement is fediverse-only now
|
|---|
| 457 | // (the ⭐ on a post likes via the fediverse). No post_likes, no /favorieten.
|
|---|
| 458 |
|
|---|
| 459 | // Newer/Older neighbours across ALL posts in feed order. Shared by the full
|
|---|
| 460 | // post render and the fan gate (premium fan_only) so navigation is consistent
|
|---|
| 461 | // everywhere. Solo: within the site (pinned first, then date). Hub: globally by date.
|
|---|
| 462 | function postNeighbors(site, post, isHub) {
|
|---|
| 463 | const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
|
|---|
| 464 | const ordered = isHub
|
|---|
| 465 | ? db.prepare(`
|
|---|
| 466 | SELECT p.id, p.slug, p.title, p.pinned, s.slug AS site_slug
|
|---|
| 467 | FROM posts p JOIN sites s ON s.id = p.site_id
|
|---|
| 468 | WHERE p.status = 'published'
|
|---|
| 469 | ORDER BY p.published_at DESC
|
|---|
| 470 | `).all()
|
|---|
| 471 | : db.prepare(`
|
|---|
| 472 | SELECT id, slug, title, pinned FROM posts
|
|---|
| 473 | WHERE site_id = ? AND status = 'published'
|
|---|
| 474 | ORDER BY (pinned = 0) ASC, pinned ASC, published_at DESC
|
|---|
| 475 | `).all(site.id);
|
|---|
| 476 | const idx = ordered.findIndex((p) => p.id === post.id);
|
|---|
| 477 | const newerPost = idx > 0 ? ordered[idx - 1] : null;
|
|---|
| 478 | const olderPost = (idx >= 0 && idx < ordered.length - 1) ? ordered[idx + 1] : null;
|
|---|
| 479 | if (newerPost) newerPost._urlBase = urlBaseFor(newerPost);
|
|---|
| 480 | if (olderPost) olderPost._urlBase = urlBaseFor(olderPost);
|
|---|
| 481 | return { newerPost, olderPost };
|
|---|
| 482 | }
|
|---|
| 483 |
|
|---|
| 484 | // ==================== REMOTE INTERACTION (reply to a fediverse post as your site) ====================
|
|---|
| 485 | // Standard fediverse "reply from your own server" landing endpoint. A post page
|
|---|
| 486 | // elsewhere bounces the visitor here with ?uri=<remote post>; the site owner
|
|---|
| 487 | // composes a reply that federates back to that post.
|
|---|
| 488 | router.get('/authorize_interaction', requireSiteManager, async (req, res) => {
|
|---|
| 489 | const site = res.locals.site;
|
|---|
| 490 | const uri = (req.query.uri || '').toString();
|
|---|
| 491 | const sent = !!req.query.sent;
|
|---|
| 492 | const followed = !!req.query.followed;
|
|---|
| 493 | let target = null, followTarget = null;
|
|---|
| 494 | if (!sent && !followed && uri) {
|
|---|
| 495 | try { target = await ActivityPubService.resolveRemoteNote(uri); } catch { /* ignore */ }
|
|---|
| 496 | // Not a post? Maybe the URI is a profile/actor → offer Follow, not reply.
|
|---|
| 497 | if (!target) { try { followTarget = await ActivityPubService.resolveRemoteActor(uri); } catch { /* ignore */ } }
|
|---|
| 498 | }
|
|---|
| 499 | renderPage(req, res, 'pages/authorize-interaction', {
|
|---|
| 500 | pageTitle: 'Interacteer via de fediverse',
|
|---|
| 501 | bodyClass: 'on-special',
|
|---|
| 502 | uri,
|
|---|
| 503 | target,
|
|---|
| 504 | followTarget,
|
|---|
| 505 | sent,
|
|---|
| 506 | followed,
|
|---|
| 507 | liked: !!req.query.liked,
|
|---|
| 508 | boosted: !!req.query.boosted,
|
|---|
| 509 | reacted: (site && uri) ? ActivityPubService.getMyReactions(site.slug, uri) : { liked: false, boosted: false },
|
|---|
| 510 | siteTitle: site ? site.title : '',
|
|---|
| 511 | });
|
|---|
| 512 | });
|
|---|
| 513 |
|
|---|
| 514 | // ⭐ Like / unlike a remote post from your own site (toggle on the interact page).
|
|---|
| 515 | router.post('/authorize_interaction/like', requireSiteManager, (req, res) => {
|
|---|
| 516 | const site = res.locals.site;
|
|---|
| 517 | const uri = (req.body.uri || '').toString();
|
|---|
| 518 | let on = false;
|
|---|
| 519 | if (site && uri) {
|
|---|
| 520 | on = !ActivityPubService.getMyReactions(site.slug, uri).liked;
|
|---|
| 521 | ActivityPubService.resolveRemoteNote(uri)
|
|---|
| 522 | .then((note) => note && ActivityPubService.sendInteraction(site, on ? 'like' : 'unlike', note.object_uri || uri, note.actor_uri))
|
|---|
| 523 | .catch((e) => console.warn('[AP] remote like failed:', e.message));
|
|---|
| 524 | ActivityPubService.setMyReaction(site.slug, uri, 'like', on);
|
|---|
| 525 | }
|
|---|
| 526 | if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
|
|---|
| 527 | res.redirect('/authorize_interaction?uri=' + encodeURIComponent(uri));
|
|---|
| 528 | });
|
|---|
| 529 |
|
|---|
| 530 | // 🔁 Boost / unboost a remote post from your own site (toggle on the interact page).
|
|---|
| 531 | // Also flags it for the Cirkel (markBoosted is a no-op if the post isn't in your timeline).
|
|---|
| 532 | router.post('/authorize_interaction/boost', requireSiteManager, (req, res) => {
|
|---|
| 533 | const site = res.locals.site;
|
|---|
| 534 | const uri = (req.body.uri || '').toString();
|
|---|
| 535 | let on = false;
|
|---|
| 536 | if (site && uri) {
|
|---|
| 537 | on = !ActivityPubService.getMyReactions(site.slug, uri).boosted;
|
|---|
| 538 | ActivityPubService.resolveRemoteNote(uri)
|
|---|
| 539 | .then((note) => {
|
|---|
| 540 | if (!note) return;
|
|---|
| 541 | const id = note.object_uri || uri;
|
|---|
| 542 | return Promise.resolve(ActivityPubService.sendInteraction(site, on ? 'boost' : 'unboost', id, note.actor_uri))
|
|---|
| 543 | // Boost → store the post in the timeline (even if you don't follow the author) so it
|
|---|
| 544 | // surfaces in the Cirkel; unboost → just clear the flag.
|
|---|
| 545 | .then(() => on ? ActivityPubService.upsertBoostedNote(site.slug, note) : ActivityPubService.unmarkBoosted(site.slug, id));
|
|---|
| 546 | })
|
|---|
| 547 | .catch((e) => console.warn('[AP] remote boost failed:', e.message));
|
|---|
| 548 | ActivityPubService.setMyReaction(site.slug, uri, 'boost', on);
|
|---|
| 549 | }
|
|---|
| 550 | if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
|
|---|
| 551 | res.redirect('/authorize_interaction?uri=' + encodeURIComponent(uri));
|
|---|
| 552 | });
|
|---|
| 553 |
|
|---|
| 554 | // Follow a remote actor from your own site (when the target is a profile, not a post).
|
|---|
| 555 | router.post('/authorize_interaction/follow', requireSiteManager, (req, res) => {
|
|---|
| 556 | const site = res.locals.site;
|
|---|
| 557 | const uri = (req.body.uri || '').toString();
|
|---|
| 558 | if (site && uri) {
|
|---|
| 559 | ActivityPubService.followActor(site, uri)
|
|---|
| 560 | .catch((e) => console.warn('[AP] remote follow failed:', e.message));
|
|---|
| 561 | }
|
|---|
| 562 | res.redirect('/authorize_interaction?followed=1&uri=' + encodeURIComponent(uri));
|
|---|
| 563 | });
|
|---|
| 564 |
|
|---|
| 565 | router.post('/authorize_interaction', requireSiteManager, (req, res) => {
|
|---|
| 566 | const site = res.locals.site;
|
|---|
| 567 | const uri = (req.body.uri || '').toString();
|
|---|
| 568 | const text = (req.body.text || '').toString();
|
|---|
| 569 | if (site && uri && text.trim()) {
|
|---|
| 570 | // Resolve + deliver in the background so Send responds instantly.
|
|---|
| 571 | ActivityPubService.resolveRemoteNote(uri)
|
|---|
| 572 | .then((parent) => parent && ActivityPubService.deliverReply(site, { postId: parent.localPostId || '', postSlug: null, parent, text }))
|
|---|
| 573 | .catch((e) => console.warn('[AP] remote reply failed:', e.message));
|
|---|
| 574 | }
|
|---|
| 575 | res.redirect('/authorize_interaction?sent=1&uri=' + encodeURIComponent(uri));
|
|---|
| 576 | });
|
|---|
| 577 |
|
|---|
| 578 | // Manage / delete your own outbound fediverse replies (site owner only).
|
|---|
| 579 | router.get('/fediverse', requireSiteManager, (req, res) => {
|
|---|
| 580 | const site = res.locals.site;
|
|---|
| 581 | const items = site ? ActivityPubService.listOutbox(site.slug) : [];
|
|---|
| 582 | renderPage(req, res, 'pages/authorize-interaction', {
|
|---|
| 583 | pageTitle: 'Mijn fediverse-reacties', bodyClass: 'on-special',
|
|---|
| 584 | manage: items, uri: '', target: null, sent: false, siteTitle: site ? site.title : '',
|
|---|
| 585 | });
|
|---|
| 586 | });
|
|---|
| 587 |
|
|---|
| 588 | router.post('/fediverse/:id/delete', requireSiteManager, async (req, res) => {
|
|---|
| 589 | const site = res.locals.site;
|
|---|
| 590 | if (site) {
|
|---|
| 591 | try { await ActivityPubService.deliverOutboxDelete(site, req.params.id); }
|
|---|
| 592 | catch (e) { console.warn('[AP] outbox delete failed:', e.message); }
|
|---|
| 593 | }
|
|---|
| 594 | res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/fediverse`);
|
|---|
| 595 | });
|
|---|
| 596 |
|
|---|
| 597 | // Edit one of your own outbound fediverse replies (owner only) → sends an Update(Note).
|
|---|
| 598 | router.post('/fediverse/:id/edit', requireSiteManager, async (req, res) => {
|
|---|
| 599 | const site = res.locals.site;
|
|---|
| 600 | if (site && String(req.body.text || '').trim()) {
|
|---|
| 601 | try { await ActivityPubService.deliverOutboxUpdate(site, req.params.id, req.body.text); }
|
|---|
| 602 | catch (e) { console.warn('[AP] outbox edit failed:', e.message); }
|
|---|
| 603 | }
|
|---|
| 604 | res.redirect(req.get('Referer') || `${res.locals.siteUrlBase || ''}/fediverse`);
|
|---|
| 605 | });
|
|---|
| 606 |
|
|---|
| 607 | // ==================== FEDIVERSE CLIENT: home timeline + following ====================
|
|---|
| 608 | // Build a direct embed iframe for the first embeddable link (YouTube/Spotify/
|
|---|
| 609 | // SoundCloud/Vimeo) in a remote post's content, so others' media plays inline.
|
|---|
| 610 | function timelineEmbedHtml(html) {
|
|---|
| 611 | if (!html) return null;
|
|---|
| 612 | const re = /href=["']([^"']+)["']/gi; let m; const seen = new Set();
|
|---|
| 613 | while ((m = re.exec(html))) {
|
|---|
| 614 | const u = m[1]; if (seen.has(u)) continue; seen.add(u);
|
|---|
| 615 | let p; try { p = AudioEmbedService.detectProvider(u); } catch { p = null; }
|
|---|
| 616 | if (!p) continue;
|
|---|
| 617 | if (p.provider === 'youtube') return `<iframe class="tl-embed-frame" src="https://www.youtube-nocookie.com/embed/${p.id}" title="YouTube" loading="lazy" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
|
|---|
| 618 | if (p.provider === 'spotify') return `<iframe class="tl-embed-frame tl-embed-spotify" src="https://open.spotify.com/embed/${p.type}/${p.id}" title="Spotify" loading="lazy" frameborder="0" allow="encrypted-media"></iframe>`;
|
|---|
| 619 | if (p.provider === 'soundcloud') return `<iframe class="tl-embed-frame tl-embed-sc" src="https://w.soundcloud.com/player/?url=${encodeURIComponent(p.url)}&color=%23ff5500&visual=false" title="SoundCloud" loading="lazy" frameborder="0" allow="autoplay" scrolling="no"></iframe>`;
|
|---|
| 620 | if (p.provider === 'vimeo') return `<iframe class="tl-embed-frame" src="https://player.vimeo.com/video/${p.id}" title="Vimeo" loading="lazy" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>`;
|
|---|
| 621 | if (p.provider === 'bandcamp') return `<iframe class="tl-embed-frame tl-embed-bandcamp" src="https://bandcamp.com/EmbeddedPlayer/url=${encodeURIComponent(u)}/size=large/bgcol=faf8f3/linkcol=c2410c/tracklist=false/transparent=true/" title="Bandcamp" loading="lazy" frameborder="0" allow="encrypted-media"></iframe>`;
|
|---|
| 622 | if (p.provider === 'applemusic') { const am = u.match(/music\.apple\.com\/([a-z]{2}\/(?:album|playlist|song)\/[^/?#]+\/[0-9]+)/i); if (am) return `<iframe class="tl-embed-frame tl-embed-apple" src="https://embed.music.apple.com/${am[1]}" title="Apple Music" loading="lazy" frameborder="0" allow="autoplay; encrypted-media"></iframe>`; }
|
|---|
| 623 | }
|
|---|
| 624 | return null;
|
|---|
| 625 | }
|
|---|
| 626 |
|
|---|
| 627 | // A federated Klonkt audio post renders as "🎵 … listen on <link>". Embed the remote
|
|---|
| 628 | // Klonkt player (its /embed?post=<slug>). A single-segment path = a Klonkt post slug
|
|---|
| 629 | // (skips Mastodon /@user/123). The origin is whitelisted in the response CSP frame-src.
|
|---|
| 630 | function klonktAudioEmbed(html, url) {
|
|---|
| 631 | if (!html || !url || html.indexOf('🎵') < 0) return null;
|
|---|
| 632 | let u; try { u = new URL(url); } catch { return null; }
|
|---|
| 633 | if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;
|
|---|
| 634 | const slug = u.pathname.replace(/^\/+|\/+$/g, '');
|
|---|
| 635 | if (!slug || slug.indexOf('/') >= 0) return null; // single segment only
|
|---|
| 636 | const src = u.origin + '/embed?post=' + encodeURIComponent(slug);
|
|---|
| 637 | // Drop the now-redundant "🎵 … listen on <site>" line — the embedded player below shows it.
|
|---|
| 638 | const content = html.replace(/<p>🎵[\s\S]*?<\/p>\s*/i, '');
|
|---|
| 639 | return { origin: u.origin, embedUrl: src, content, html: `<iframe class="tl-embed-frame tl-embed-klonkt" src="${src}" title="Audio" loading="lazy" frameborder="0" allow="autoplay; encrypted-media"></iframe>` };
|
|---|
| 640 | }
|
|---|
| 641 |
|
|---|
| 642 | router.get('/news', requireSiteManager, (req, res) => {
|
|---|
| 643 | const site = res.locals.site;
|
|---|
| 644 | const cspOrigins = new Set();
|
|---|
| 645 | const timeline = (site ? ActivityPubService.getTimeline(site.slug, 60) : []).map((p) => {
|
|---|
| 646 | let embedHtml = timelineEmbedHtml(p.content);
|
|---|
| 647 | let content = p.content;
|
|---|
| 648 | let embedUrl = null;
|
|---|
| 649 | if (!embedHtml) {
|
|---|
| 650 | const k = klonktAudioEmbed(p.content, p.url);
|
|---|
| 651 | if (k) { embedHtml = k.html; content = k.content; embedUrl = k.embedUrl; cspOrigins.add(k.origin); }
|
|---|
| 652 | }
|
|---|
| 653 | // embedUrl = the player's direct /embed?post=… URL. Surfaced so the view can offer a
|
|---|
| 654 | // top-level "open the player" link that works even when a browser shield/CSP blocks
|
|---|
| 655 | // the cross-site iframe (a full-page navigation is not a cross-site frame).
|
|---|
| 656 | return { ...p, content, embedHtml, embedUrl };
|
|---|
| 657 | });
|
|---|
| 658 | // Option A: allow the followed Klonkt sites' player iframes (you follow them) by
|
|---|
| 659 | // extending ONLY this response's CSP frame-src. The global policy stays locked down.
|
|---|
| 660 | if (cspOrigins.size) {
|
|---|
| 661 | const csp = res.getHeader('Content-Security-Policy');
|
|---|
| 662 | if (csp) {
|
|---|
| 663 | const extra = [...cspOrigins].join(' ');
|
|---|
| 664 | res.setHeader('Content-Security-Policy', String(csp).replace(/frame-src ([^;]*)/i, (m, g) => `frame-src ${g} ${extra}`));
|
|---|
| 665 | }
|
|---|
| 666 | }
|
|---|
| 667 | renderPage(req, res, 'pages/news', {
|
|---|
| 668 | pageTitle: 'News', bodyClass: 'on-special',
|
|---|
| 669 | timeline,
|
|---|
| 670 | success: req.query.success || null, error: req.query.error || null,
|
|---|
| 671 | });
|
|---|
| 672 | });
|
|---|
| 673 |
|
|---|
| 674 | // Volgend — manage the accounts you follow (+ per-account auto-boost toggles).
|
|---|
| 675 | router.get('/following', requireSiteManager, (req, res) => {
|
|---|
| 676 | const site = res.locals.site;
|
|---|
| 677 | const following = site ? ActivityPubService.listFollowing(site.slug) : [];
|
|---|
| 678 | renderPage(req, res, 'pages/following', {
|
|---|
| 679 | pageTitle: 'Volgend', bodyClass: 'on-special',
|
|---|
| 680 | following,
|
|---|
| 681 | success: req.query.success || null, error: req.query.error || null,
|
|---|
| 682 | });
|
|---|
| 683 | });
|
|---|
| 684 |
|
|---|
| 685 | router.post('/news/follow', requireSiteManager, async (req, res) => {
|
|---|
| 686 | const site = res.locals.site;
|
|---|
| 687 | const handle = (req.body.handle || '').toString();
|
|---|
| 688 | let q = 'success=' + encodeURIComponent('Volgverzoek verstuurd');
|
|---|
| 689 | if (site && handle.trim()) {
|
|---|
| 690 | try {
|
|---|
| 691 | const r = await ActivityPubService.followActor(site, handle, !!req.body.auto_boost);
|
|---|
| 692 | if (r && r.error) q = 'error=' + encodeURIComponent(r.error === 'not_found' ? 'Account niet gevonden' : (r.error === 'unreachable' ? 'Server onbereikbaar' : 'Volgen mislukt'));
|
|---|
| 693 | else {
|
|---|
| 694 | q = 'success=' + encodeURIComponent('Je volgt nu ' + ((r && r.name) || handle));
|
|---|
| 695 | }
|
|---|
| 696 | } catch (e) { q = 'error=' + encodeURIComponent('Volgen mislukt'); }
|
|---|
| 697 | }
|
|---|
| 698 | res.redirect('/following?' + q);
|
|---|
| 699 | });
|
|---|
| 700 |
|
|---|
| 701 | router.post('/news/unfollow', requireSiteManager, async (req, res) => {
|
|---|
| 702 | const site = res.locals.site;
|
|---|
| 703 | const actorUri = (req.body.actor_uri || '').toString();
|
|---|
| 704 | if (site && actorUri) { try { await ActivityPubService.unfollowActor(site, actorUri); } catch (e) { /* ignore */ } }
|
|---|
| 705 | res.redirect('/following?success=' + encodeURIComponent('Ontvolgd'));
|
|---|
| 706 | });
|
|---|
| 707 |
|
|---|
| 708 | // Toggle "Featured" (show this account's posts in your Cirkel) on an account you follow.
|
|---|
| 709 | router.post('/news/autoboost', requireSiteManager, (req, res) => {
|
|---|
| 710 | const site = res.locals.site;
|
|---|
| 711 | const actorUri = (req.body.actor_uri || '').toString();
|
|---|
| 712 | if (site && actorUri) ActivityPubService.setAutoBoost(site.slug, actorUri, !!req.body.auto_boost);
|
|---|
| 713 | res.redirect('/following?success=' + encodeURIComponent(req.body.auto_boost ? 'Uitgelicht ✨' : 'Niet meer uitgelicht'));
|
|---|
| 714 | });
|
|---|
| 715 |
|
|---|
| 716 | // Like / unlike a feed post — a toggle. Fetch request → JSON {on} (stay on the page,
|
|---|
| 717 | // no banner); no-JS → redirect back.
|
|---|
| 718 | router.post('/news/like', requireSiteManager, async (req, res) => {
|
|---|
| 719 | const site = res.locals.site;
|
|---|
| 720 | const note = (req.body.note || '').toString();
|
|---|
| 721 | let on = false;
|
|---|
| 722 | if (site && note) {
|
|---|
| 723 | on = !ActivityPubService.getTimelineReaction(site.slug, note).liked;
|
|---|
| 724 | try { await ActivityPubService.sendInteraction(site, on ? 'like' : 'unlike', note, (req.body.author || '').toString()); } catch (e) { /* ignore */ }
|
|---|
| 725 | if (on) ActivityPubService.markLiked(site.slug, note); else ActivityPubService.unmarkLiked(site.slug, note);
|
|---|
| 726 | }
|
|---|
| 727 | if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
|
|---|
| 728 | res.redirect('/news');
|
|---|
| 729 | });
|
|---|
| 730 |
|
|---|
| 731 | // Boost / unboost a feed post — a toggle. markBoosted also surfaces it in the Cirkel.
|
|---|
| 732 | router.post('/news/boost', requireSiteManager, async (req, res) => {
|
|---|
| 733 | const site = res.locals.site;
|
|---|
| 734 | const note = (req.body.note || '').toString();
|
|---|
| 735 | let on = false;
|
|---|
| 736 | if (site && note) {
|
|---|
| 737 | on = !ActivityPubService.getTimelineReaction(site.slug, note).boosted;
|
|---|
| 738 | try { await ActivityPubService.sendInteraction(site, on ? 'boost' : 'unboost', note, (req.body.author || '').toString()); } catch (e) { /* ignore */ }
|
|---|
| 739 | if (on) ActivityPubService.markBoosted(site.slug, note); else ActivityPubService.unmarkBoosted(site.slug, note);
|
|---|
| 740 | }
|
|---|
| 741 | if (req.get('X-Requested-With') === 'fetch') return res.json({ ok: true, on });
|
|---|
| 742 | res.redirect('/news');
|
|---|
| 743 | });
|
|---|
| 744 |
|
|---|
| 745 | // Notifications inbox (new followers + replies/likes/boosts on your posts).
|
|---|
| 746 | router.get('/notifications', requireSiteManager, (req, res) => {
|
|---|
| 747 | const site = res.locals.site;
|
|---|
| 748 | const items = site ? ActivityPubService.getNotifications(site.slug, 80) : [];
|
|---|
| 749 | // viewing = seen → clears the bell badge. A viewer (kijker) may look but must not
|
|---|
| 750 | // mutate state (the global write-guard only catches non-GET, not this GET-side effect).
|
|---|
| 751 | if (site && !isViewer(req.session.user)) ActivityPubService.markNotificationsSeen(site.slug);
|
|---|
| 752 | renderPage(req, res, 'pages/fedi-notifications', { pageTitle: 'Meldingen', bodyClass: 'on-special', items });
|
|---|
| 753 | });
|
|---|
| 754 |
|
|---|
| 755 | // Blocking / defederation (owner-only).
|
|---|
| 756 | router.get('/blocking', requireSiteManager, (req, res) => {
|
|---|
| 757 | const site = res.locals.site;
|
|---|
| 758 | const blocks = site ? ActivityPubService.listBlocks(site.slug) : [];
|
|---|
| 759 | renderPage(req, res, 'pages/blocks', { pageTitle: 'Blokkeren', bodyClass: 'on-special', blocks, success: req.query.success || null, error: req.query.error || null });
|
|---|
| 760 | });
|
|---|
| 761 |
|
|---|
| 762 | router.post('/blocking/add', requireSiteManager, async (req, res) => {
|
|---|
| 763 | const site = res.locals.site;
|
|---|
| 764 | let q = 'success=' + encodeURIComponent('Geblokkeerd');
|
|---|
| 765 | if (site) {
|
|---|
| 766 | try {
|
|---|
| 767 | const r = await ActivityPubService.blockTarget(site, (req.body.target || '').toString());
|
|---|
| 768 | if (r && r.error) q = 'error=' + encodeURIComponent(r.error === 'not_found' ? 'Account niet gevonden' : 'Voer een @handle of domein in');
|
|---|
| 769 | else q = 'success=' + encodeURIComponent(((r && r.label) || '') + ' geblokkeerd');
|
|---|
| 770 | } catch (e) { q = 'error=' + encodeURIComponent('Blokkeren mislukt'); }
|
|---|
| 771 | }
|
|---|
| 772 | const ref = req.get('Referer') || '';
|
|---|
| 773 | res.redirect((ref.includes('/news') ? '/news?' : '/blocking?') + q);
|
|---|
| 774 | });
|
|---|
| 775 |
|
|---|
| 776 | router.post('/blocking/remove', requireSiteManager, (req, res) => {
|
|---|
| 777 | const site = res.locals.site;
|
|---|
| 778 | if (site) { try { ActivityPubService.unblock(site, (req.body.target || '').toString()); } catch (e) { /* ignore */ } }
|
|---|
| 779 | res.redirect('/blocking?success=' + encodeURIComponent('Deblokkeerd'));
|
|---|
| 780 | });
|
|---|
| 781 |
|
|---|
| 782 | // ==================== VIEW POST (last route — catches /:slug) ====================
|
|---|
| 783 | router.get('/:slug', (req, res, next) => {
|
|---|
| 784 | if (RESERVED_SLUGS.has(req.params.slug)) return next();
|
|---|
| 785 |
|
|---|
| 786 | const site = res.locals.site;
|
|---|
| 787 | if (!site) return next(); // -> nette 404 catch-all
|
|---|
| 788 |
|
|---|
| 789 | const post = db.prepare(`
|
|---|
| 790 | SELECT p.*, u.username as author_username, u.avatar_url as author_avatar
|
|---|
| 791 | FROM posts p JOIN users u ON p.author_id = u.id
|
|---|
| 792 | WHERE p.site_id = ? AND p.slug = ?
|
|---|
| 793 | `).get(site.id, req.params.slug);
|
|---|
| 794 |
|
|---|
| 795 | if (!post) return next(); // unknown slug -> clean 404 catch-all
|
|---|
| 796 |
|
|---|
| 797 | // Permission to view: published OR (logged in + can edit)
|
|---|
| 798 | if (post.status !== 'published') {
|
|---|
| 799 | const canEdit = req.session?.user && PermissionsService.canEditPost(req.session.user, post, site);
|
|---|
| 800 | if (!canEdit) return res.status(403).send('Not published');
|
|---|
| 801 | }
|
|---|
| 802 |
|
|---|
| 803 | // Fan-only preview (premium #3): full content only for logged-in fans.
|
|---|
| 804 | // Anonymous visitors get a clean login gate instead of the content (the title/
|
|---|
| 805 | // teaser may still appear elsewhere as a teaser).
|
|---|
| 806 | if (post.fan_only && !(req.session && req.session.user)) {
|
|---|
| 807 | // Same Newer/Older navigation as on a normal post, so the visitor doesn't get
|
|---|
| 808 | // stuck on the fan gate but can keep browsing.
|
|---|
| 809 | const { newerPost, olderPost } = postNeighbors(site, post, res.locals.tenancy === 'hub');
|
|---|
| 810 | return renderPage(req, res, 'pages/fan-gate', {
|
|---|
| 811 | pageTitle: post.title || 'Alleen voor fans',
|
|---|
| 812 | bodyClass: 'on-special',
|
|---|
| 813 | fgTitle: post.title || '',
|
|---|
| 814 | fgNext: (res.locals.siteUrlBase || '') + '/' + post.slug,
|
|---|
| 815 | newerPost,
|
|---|
| 816 | olderPost,
|
|---|
| 817 | });
|
|---|
| 818 | }
|
|---|
| 819 |
|
|---|
| 820 | // Statistics: count the view (skips admins + unpublished own-preview).
|
|---|
| 821 | if (post.status === 'published') recordPostView(post, req);
|
|---|
| 822 |
|
|---|
| 823 | // Render content. Content is now user-authored HTML (already sanitized on
|
|---|
| 824 | // save). The pipeline still adds autoembed iframes and shortcode embeds:
|
|---|
| 825 | // stored HTML → autoembed → [[track]]/[[album]]/[[playlist]] → response
|
|---|
| 826 | let html = post.content || '';
|
|---|
| 827 | if (audioEnabled()) {
|
|---|
| 828 | if (site.enable_audio_player !== 0) {
|
|---|
| 829 | html = AudioEmbedService.autoembed(html);
|
|---|
| 830 | html = AudioEmbedService.embedMediaShortcodes(html);
|
|---|
| 831 | html = AudioEmbedService.embedExternalLinkShortcodes(html);
|
|---|
| 832 |
|
|---|
| 833 | // Fetch any tracks referenced by [[track:id]] in this post.
|
|---|
| 834 | // Cheap to do unconditionally — only matches if the post actually has shortcodes.
|
|---|
| 835 | const trackIds = [...html.matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)].map(m => m[1]);
|
|---|
| 836 | if (trackIds.length) {
|
|---|
| 837 | const placeholders = trackIds.map(() => '?').join(',');
|
|---|
| 838 | const rows = db.prepare(`
|
|---|
| 839 | SELECT t.id, t.title, t.artist, t.cover_url, t.credit, t.license,
|
|---|
| 840 | t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
|
|---|
| 841 | FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
|
|---|
| 842 | WHERE t.site_id = ? AND t.id IN (${placeholders})
|
|---|
| 843 | `).all(site.id, ...trackIds);
|
|---|
| 844 | const byId = new Map(rows.map(r => [r.id, r]));
|
|---|
| 845 | html = AudioEmbedService.embedTrackShortcodes(html, (id) => {
|
|---|
| 846 | const r = byId.get(id);
|
|---|
| 847 | if (!r) return null;
|
|---|
| 848 | return {
|
|---|
| 849 | id: r.id,
|
|---|
| 850 | title: r.title,
|
|---|
| 851 | artist: r.artist,
|
|---|
| 852 | cover: r.cover_url,
|
|---|
| 853 | credit: r.credit || '',
|
|---|
| 854 | license: r.license || '',
|
|---|
| 855 | link_spotify: r.link_spotify || '',
|
|---|
| 856 | link_youtube: r.link_youtube || '',
|
|---|
| 857 | link_soundcloud: r.link_soundcloud || '',
|
|---|
| 858 | url: r.filename ? audioUrl(r.filename) : '', // '' = link-only track
|
|---|
| 859 | };
|
|---|
| 860 | });
|
|---|
| 861 | }
|
|---|
| 862 |
|
|---|
| 863 | // Album shortcodes: [[album:Some Album Name]]
|
|---|
| 864 | const albumNames = [...html.matchAll(/\[\[album:([^\]]+)\]\]/g)].map(m => m[1].trim());
|
|---|
| 865 | if (albumNames.length) {
|
|---|
| 866 | const placeholders = albumNames.map(() => '?').join(',');
|
|---|
| 867 | const albumRows = db.prepare(`
|
|---|
| 868 | SELECT t.id, t.title, t.artist, t.album, t.cover_url, t.position,
|
|---|
| 869 | t.link_spotify, t.link_youtube, t.link_soundcloud, m.filename
|
|---|
| 870 | FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id
|
|---|
| 871 | WHERE t.site_id = ? AND t.album IN (${placeholders})
|
|---|
| 872 | ORDER BY t.position ASC, t.created_at ASC
|
|---|
| 873 | `).all(site.id, ...albumNames);
|
|---|
| 874 | const byAlbum = new Map();
|
|---|
| 875 | for (const r of albumRows) {
|
|---|
| 876 | // Link-only tracks (no file) remain in the album overview (url '').
|
|---|
| 877 | if (!byAlbum.has(r.album)) byAlbum.set(r.album, []);
|
|---|
| 878 | byAlbum.get(r.album).push({
|
|---|
| 879 | id: r.id,
|
|---|
| 880 | url: r.filename ? audioUrl(r.filename) : '',
|
|---|
| 881 | title: r.title || 'Untitled',
|
|---|
| 882 | artist: r.artist || '',
|
|---|
| 883 | cover: r.cover_url || '',
|
|---|
| 884 | link_spotify: r.link_spotify || '',
|
|---|
| 885 | link_youtube: r.link_youtube || '',
|
|---|
| 886 | link_soundcloud: r.link_soundcloud || '',
|
|---|
| 887 | });
|
|---|
| 888 | }
|
|---|
| 889 | html = AudioEmbedService.embedAlbumShortcodes(html, (name) => {
|
|---|
| 890 | const tracks = byAlbum.get(name);
|
|---|
| 891 | if (!tracks || !tracks.length) return null;
|
|---|
| 892 | return {
|
|---|
| 893 | title: name,
|
|---|
| 894 | artist: tracks[0].artist || '',
|
|---|
| 895 | cover: tracks[0].cover || '',
|
|---|
| 896 | tracks,
|
|---|
| 897 | };
|
|---|
| 898 | });
|
|---|
| 899 | }
|
|---|
| 900 |
|
|---|
| 901 | // Playlist shortcodes: [[playlist:some-slug-id]] — first-class entity.
|
|---|
| 902 | // Editing the playlist propagates to every post that embeds it.
|
|---|
| 903 | const playlistIds = [...html.matchAll(/\[\[playlist:([a-z0-9][a-z0-9-]*)\]\]/gi)]
|
|---|
| 904 | .map(m => m[1].toLowerCase());
|
|---|
| 905 | if (playlistIds.length) {
|
|---|
| 906 | const isAdmin = req.session?.user?.role === 'god';
|
|---|
| 907 | html = AudioEmbedService.embedPlaylistShortcodes(html, (id) => {
|
|---|
| 908 | return PlaylistService.get(site.id, id, audioUrl);
|
|---|
| 909 | }, { isAdmin });
|
|---|
| 910 | }
|
|---|
| 911 | }
|
|---|
| 912 | } else {
|
|---|
| 913 | // LITE mode (KLONKT_AUDIO=off): no own audio (no ffmpeg/stream route).
|
|---|
| 914 | // External embeds (YouTube/SoundCloud/Spotify) remain; the own-audio
|
|---|
| 915 | // shortcodes ([[track]]/[[album]]/[[playlist]]) are cleanly stripped.
|
|---|
| 916 | html = AudioEmbedService.autoembed(html);
|
|---|
| 917 | html = AudioEmbedService.embedMediaShortcodes(html);
|
|---|
| 918 | html = AudioEmbedService.embedExternalLinkShortcodes(html);
|
|---|
| 919 | html = html.replace(/\[\[(track|album|playlist):[^\]]+\]\]/gi, '');
|
|---|
| 920 | }
|
|---|
| 921 | post.content_html = html;
|
|---|
| 922 |
|
|---|
| 923 | if (post.tags) {
|
|---|
| 924 | try { post.tags = JSON.parse(post.tags); } catch { post.tags = []; }
|
|---|
| 925 | } else {
|
|---|
| 926 | post.tags = [];
|
|---|
| 927 | }
|
|---|
| 928 |
|
|---|
| 929 | // Native comments removed: social interaction is fediverse-only (see the
|
|---|
| 930 | // "From the fediverse" section below).
|
|---|
| 931 |
|
|---|
| 932 | // Prev / next chronological (kept for back-compat — "post-nav" feature
|
|---|
| 933 | // below the article still uses these as a simple linear navigation).
|
|---|
| 934 | // Hub mode: Related posts + Newer/Older pull from ALL users (all sites),
|
|---|
| 935 | // newest first. Solo mode: within the current site (old behaviour).
|
|---|
| 936 | const isHub = res.locals.tenancy === 'hub';
|
|---|
| 937 | // Per-post URL base: in hub a link points to /user/<site-slug>/<post-slug>.
|
|---|
| 938 | const urlBaseFor = (p) => (isHub && p && p.site_slug) ? `/user/${p.site_slug}` : '';
|
|---|
| 939 |
|
|---|
| 940 | // Newer/Older across ALL posts (shared helper — also used by the fan gate).
|
|---|
| 941 | const { newerPost, olderPost } = postNeighbors(site, post, isHub);
|
|---|
| 942 |
|
|---|
| 943 | // ── Related posts: same-tag matching with recency fallback ─────
|
|---|
| 944 | // Fetch ~50 candidates, score by tag overlap, take top 3.
|
|---|
| 945 | // Excluding self via `id != ?`.
|
|---|
| 946 | const candidates = isHub
|
|---|
| 947 | ? db.prepare(`
|
|---|
| 948 | SELECT p.id, p.slug, p.title, p.cover_image_url, p.published_at, p.tags, s.slug AS site_slug
|
|---|
| 949 | FROM posts p JOIN sites s ON s.id = p.site_id
|
|---|
| 950 | WHERE p.status = 'published' AND p.id != ?
|
|---|
| 951 | ORDER BY p.published_at DESC LIMIT 50
|
|---|
| 952 | `).all(post.id)
|
|---|
| 953 | : db.prepare(`
|
|---|
| 954 | SELECT id, slug, title, cover_image_url, published_at, tags
|
|---|
| 955 | FROM posts
|
|---|
| 956 | WHERE site_id = ? AND status = 'published' AND id != ?
|
|---|
| 957 | ORDER BY published_at DESC LIMIT 50
|
|---|
| 958 | `).all(site.id, post.id);
|
|---|
| 959 |
|
|---|
| 960 | // Parse tags JSON safely; missing/malformed → empty array.
|
|---|
| 961 | const parseTags = (raw) => {
|
|---|
| 962 | if (!raw) return [];
|
|---|
| 963 | try {
|
|---|
| 964 | const v = JSON.parse(raw);
|
|---|
| 965 | return Array.isArray(v) ? v.map(String) : [];
|
|---|
| 966 | } catch { return []; }
|
|---|
| 967 | };
|
|---|
| 968 |
|
|---|
| 969 | const myTags = new Set(parseTags(post.tags));
|
|---|
| 970 | let relatedPosts;
|
|---|
| 971 | if (myTags.size > 0) {
|
|---|
| 972 | // Score = number of overlapping tags. Posts with zero overlap are
|
|---|
| 973 | // included only if we don't have 3 with-overlap candidates.
|
|---|
| 974 | const scored = candidates.map(p => {
|
|---|
| 975 | const theirTags = parseTags(p.tags);
|
|---|
| 976 | const overlap = theirTags.reduce((n, t) => n + (myTags.has(t) ? 1 : 0), 0);
|
|---|
| 977 | return { ...p, _overlap: overlap };
|
|---|
| 978 | });
|
|---|
| 979 | const withOverlap = scored.filter(p => p._overlap > 0)
|
|---|
| 980 | .sort((a, b) => b._overlap - a._overlap || new Date(b.published_at) - new Date(a.published_at));
|
|---|
| 981 | if (withOverlap.length >= 3) {
|
|---|
| 982 | relatedPosts = withOverlap.slice(0, 3);
|
|---|
| 983 | } else {
|
|---|
| 984 | // Pad with most-recent non-overlap posts so the section is never empty
|
|---|
| 985 | const overlapIds = new Set(withOverlap.map(p => p.id));
|
|---|
| 986 | const filler = candidates.filter(p => !overlapIds.has(p.id));
|
|---|
| 987 | relatedPosts = [...withOverlap, ...filler].slice(0, 3);
|
|---|
| 988 | }
|
|---|
| 989 | } else {
|
|---|
| 990 | // No tags on current post → just show 3 most-recent
|
|---|
| 991 | relatedPosts = candidates.slice(0, 3);
|
|---|
| 992 | }
|
|---|
| 993 | // Strip the internal _overlap field before sending to view
|
|---|
| 994 | relatedPosts = relatedPosts.map(({ _overlap, tags, ...rest }) => ({ ...rest, _urlBase: urlBaseFor(rest) }));
|
|---|
| 995 |
|
|---|
| 996 | // Inbound fediverse activity (threaded) for this post.
|
|---|
| 997 | let fediverse = { thread: [], likeCount: 0, announceCount: 0, total: 0 };
|
|---|
| 998 | try {
|
|---|
| 999 | const _apBase = (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
|
|---|
| 1000 | fediverse = ActivityPubService.getInteractions(post.id, _apBase, site);
|
|---|
| 1001 | } catch { /* non-fatal */ }
|
|---|
| 1002 | // Owner/admin of this site may reply back to a fediverse interaction.
|
|---|
| 1003 | const canManageSite = !!(req.session?.user && PermissionsService.canAdminSite(req.session.user, site));
|
|---|
| 1004 | // Avatar for our own (outbound) fediverse replies = the site's profile photo.
|
|---|
| 1005 | const siteAvatar = (site && site.profile_photo) ? site.profile_photo : null;
|
|---|
| 1006 |
|
|---|
| 1007 | renderPage(req, res, 'pages/post', {
|
|---|
| 1008 | post,
|
|---|
| 1009 | newerPost,
|
|---|
| 1010 | olderPost,
|
|---|
| 1011 | relatedPosts,
|
|---|
| 1012 | fediverse,
|
|---|
| 1013 | canManageSite,
|
|---|
| 1014 | siteAvatar,
|
|---|
| 1015 | postHasPlayableAudio: ActivityPubService.hasPlayableAudio(post.content || '', site.id),
|
|---|
| 1016 | pageTitle: post.title + ' - ' + site.title,
|
|---|
| 1017 | socialDescr: post.excerpt || '',
|
|---|
| 1018 | socialImage: post.cover_image_url || '',
|
|---|
| 1019 | bodyClass: 'on-post',
|
|---|
| 1020 | });
|
|---|
| 1021 | });
|
|---|
| 1022 |
|
|---|
| 1023 | // ── Reply back to a fediverse interaction (site owner/admin only) ──
|
|---|
| 1024 | router.post('/posts/:slug/fedi-reply', requireSiteManager, async (req, res) => {
|
|---|
| 1025 | const site = res.locals.site;
|
|---|
| 1026 | if (!site) return res.status(404).send('Site required');
|
|---|
| 1027 | const post = db.prepare('SELECT id, slug FROM posts WHERE site_id = ? AND slug = ?').get(site.id, req.params.slug);
|
|---|
| 1028 | if (!post) return res.status(404).send('Not found');
|
|---|
| 1029 | const parent = ActivityPubService.getInteractionById(req.body.interaction_id);
|
|---|
| 1030 | const text = (req.body.text || '').toString();
|
|---|
| 1031 | if (parent && parent.post_id === post.id && text.trim()) {
|
|---|
| 1032 | try {
|
|---|
| 1033 | await ActivityPubService.deliverReply(site, { postId: post.id, postSlug: post.slug, parent, text });
|
|---|
| 1034 | } catch (e) { console.warn('[AP] reply send failed:', e.message); }
|
|---|
| 1035 | }
|
|---|
| 1036 | res.redirect(`${res.locals.siteUrlBase || ''}/${post.slug}#fediverse`);
|
|---|
| 1037 | });
|
|---|
| 1038 |
|
|---|
| 1039 | // Owner likes/boosts a fediverse comment on their own post — directly as the
|
|---|
| 1040 | // site, no "your server" detour (mirrors /fedi-reply).
|
|---|
| 1041 | router.post('/posts/:slug/fedi-react', requireSiteManager, async (req, res) => {
|
|---|
| 1042 | const site = res.locals.site;
|
|---|
| 1043 | if (!site) return res.status(404).send('Site required');
|
|---|
| 1044 | const post = db.prepare('SELECT id, slug FROM posts WHERE site_id = ? AND slug = ?').get(site.id, req.params.slug);
|
|---|
| 1045 | if (!post) return res.status(404).send('Not found');
|
|---|
| 1046 | const parent = ActivityPubService.getInteractionById(req.body.interaction_id);
|
|---|
| 1047 | const kind = req.body.kind === 'boost' ? 'boost' : 'like';
|
|---|
| 1048 | if (parent && parent.post_id === post.id && parent.object_uri) {
|
|---|
| 1049 | if (kind === 'boost') {
|
|---|
| 1050 | // Toggle: boost an unboosted comment, or retract it (Undo Announce) if already boosted.
|
|---|
| 1051 | const on = !parent.acted_boost;
|
|---|
| 1052 | ActivityPubService.sendInteraction(site, on ? 'boost' : 'unboost', parent.object_uri, parent.actor_uri)
|
|---|
| 1053 | .catch((e) => console.warn('[AP] reaction failed:', e.message));
|
|---|
| 1054 | ActivityPubService.setInteractionBoosted(parent.id, on);
|
|---|
| 1055 | } else {
|
|---|
| 1056 | // Toggle: like an unliked comment, or un-favourite (Undo Like) if already liked.
|
|---|
| 1057 | const on = !parent.acted_like;
|
|---|
| 1058 | ActivityPubService.sendInteraction(site, on ? 'like' : 'unlike', parent.object_uri, parent.actor_uri)
|
|---|
| 1059 | .catch((e) => console.warn('[AP] reaction failed:', e.message));
|
|---|
| 1060 | ActivityPubService.setInteractionLiked(parent.id, on);
|
|---|
| 1061 | }
|
|---|
| 1062 | }
|
|---|
| 1063 | res.redirect(`${res.locals.siteUrlBase || ''}/${post.slug}#fediverse`);
|
|---|
| 1064 | });
|
|---|
| 1065 |
|
|---|
| 1066 | export default router;
|
|---|
| 1067 | export { postNeighbors };
|
|---|