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