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