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