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