source: Klonkt/src/middleware/render.js@ 108fd5f

main
Last change on this file since 108fd5f was 8aa85d0, checked in by roboburr <roboburr@…>, 3 months ago

Prutter = premium Hub feature: Hub-only + behind premium gate

Prutter (DMs) is now hard-scoped to Hub mode (route 404s outside hub) and
locked behind the premium gate via the new premiumUnlocked() (= premium off
→ freely available, demos keep working; premium on → Patreon required).
UI entry points (topnav/bottom-tab/Send DM) follow the same condition.
Added to the premium description in Admin → Settings.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@…>

  • Property mode set to 100644
File size: 6.6 KB
Line 
1/**
2 * Render helper — THE pattern for the entire app.
3 *
4 * Two modes:
5 * 1. HTMX request → render just the page content (no shell)
6 * 2. Full page request → render content, then embed in shell
7 *
8 * Usage:
9 * renderPage(req, res, 'pages/home', { posts, ...data })
10 */
11
12import fs from 'fs';
13import path from 'path';
14import { fileURLToPath } from 'url';
15import ejs from 'ejs';
16import db from '../config/database.js';
17import PermissionsService from '../services/PermissionsService.js';
18import { isViewer } from './auth.js';
19import { getSetting } from '../services/SettingsService.js';
20import { isPremium as isPremiumInstance, premiumEnabled, premiumUnlocked } from '../services/PatreonService.js';
21import { PLATFORMS as PLATFORMS_CATALOG } from '../services/PlatformIcons.js';
22
23const __dirname = path.dirname(fileURLToPath(import.meta.url));
24const VIEWS_DIR = path.join(__dirname, '..', 'views');
25
26// App-versie (uit package.json) — getoond in de footer naast "Klonkt Beta".
27let APP_VERSION = '';
28try {
29 APP_VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8')).version || '';
30} catch { /* geen versie beschikbaar */ }
31
32const formatDate = (iso) => {
33 if (!iso) return '';
34 const d = new Date(iso);
35 const months = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'];
36 return `${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}`;
37};
38
39const formatDateTime = (iso) => {
40 if (!iso) return '';
41 const d = new Date(iso);
42 return d.toLocaleString('nl-NL', { dateStyle: 'medium', timeStyle: 'short' });
43};
44
45export async function renderPage(req, res, viewName, data = {}) {
46 // Decide: partial (HTMX) or full?
47 const isPartial = req.headers['hx-request'] === 'true' || req.query.partial === '1';
48
49 // Bezit deze (niet-god) user een eigen site? Bepaalt of 'ie een "Beheer"-
50 // ingang ziet (artiest-zelfbeheer). god ziet beheer sowieso (op rol).
51 const _u = req.session?.user || null;
52 const userOwnsSite = !!(_u && _u.role !== 'god' &&
53 db.prepare('SELECT 1 FROM sites WHERE owner_id = ? LIMIT 1').get(_u.id));
54
55 // De avatar van de SITE-EIGENAAR (niet de kijker!) — voor de Klonkt-site-kop,
56 // zodat de artiest z'n eigen account-foto als sitefoto kan gebruiken.
57 const _site = data.site || res.locals.site || null;
58 const siteOwnerAvatar = (_site && _site.owner_id)
59 ? (db.prepare('SELECT avatar_url FROM users WHERE id = ?').get(_site.owner_id)?.avatar_url || null)
60 : null;
61
62 // Kijker-modus: alles bekijken mag, niets wijzigen. Views gebruiken canMutate
63 // om schrijf-knoppen (posten, opslaan, verwijderen) te verbergen/uit te zetten.
64 const _isViewer = isViewer(_u);
65
66 // Wie ziet de "Beheer"-link? god/admin, een site-eigenaar (artiest-zelfbeheer),
67 // én een kijker (mag het Beheer alleen-lezen inzien). Eén bron van waarheid,
68 // gespiegeld in topnav/hub-nav/profielsheet — anders raakt de link verborgen
69 // voor wie 'm wél mag zien (kijker zag 'm eerst nergens).
70 const _role = _u ? _u.role : null;
71 const canSeeBeheer = !!(_u && (_role === 'god' || _role === 'admin' || _role === 'kijker' || userOwnsSite));
72
73 // Common locals
74 const locals = {
75 user: _u,
76 userOwnsSite,
77 canSeeBeheer,
78 isViewer: _isViewer,
79 canMutate: !_isViewer,
80 isPremium: isPremiumInstance(),
81 premiumEnabled: premiumEnabled(),
82 premiumUnlocked: premiumUnlocked(),
83 siteOwnerAvatar,
84 site: _site,
85 audioTracks: data.audioTracks || res.locals.audioTracks || [],
86 siteUrlBase: res.locals.siteUrlBase || '',
87 tenancy: res.locals.tenancy || 'solo',
88 hubTitle: getSetting('hub_title') || '',
89 platforms_catalog: PLATFORMS_CATALOG,
90 permissions: PermissionsService,
91 formatDate,
92 formatDateTime,
93 pageTitle: data.pageTitle || (data.site && data.site.title) || 'Klonkt Beta',
94 appVersion: APP_VERSION,
95 bodyClass: data.bodyClass || 'on-home',
96 socialDescr: data.socialDescr || '',
97 socialImage: data.socialImage || '',
98 cspNonce: () => '',
99 currentPath: req.path,
100 ...data,
101 };
102
103 try {
104 // Step 1: Render the page view to HTML
105 const viewPath = path.join(VIEWS_DIR, viewName + '.ejs');
106 const pageContent = await ejs.renderFile(viewPath, locals, { async: false });
107
108 if (isPartial) {
109 // HTMX: just send the content. Set HX-Trigger for body class swap.
110 // HTTP-header values are Latin-1 only — a title with an em-dash, smart
111 // quote or emoji (e.g. "Welkom — gebouwd met Klonkt") would make
112 // setHeader throw ERR_INVALID_CHAR and 500 the partial, so the card
113 // looks "unclickable". Escape any non-ASCII to \uXXXX: the header stays
114 // ASCII-safe and remains valid JSON that htmx parses back unchanged.
115 const triggerJson = JSON.stringify({
116 pcmsNav: { bodyClass: locals.bodyClass },
117 pcmsPostSwap: data.post ? {
118 title: data.post.title,
119 slug: data.post.slug,
120 pageTitle: locals.pageTitle,
121 } : null,
122 }).replace(/[€-￿]/g, (ch) => '\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0'));
123 res.setHeader('HX-Trigger-After-Settle', triggerJson);
124 return res.send(pageContent);
125 }
126
127 // Full: wrap content in shell
128 locals.pageContent = pageContent;
129 res.render('shell', locals);
130 } catch (err) {
131 console.error('[renderPage] Error rendering', viewName, err);
132 if (process.env.NODE_ENV === 'production') {
133 return res.status(500).send('Internal Server Error');
134 }
135 // Dev: surface the underlying cause prominently. EJS rewrites err.message
136 // to include the file/line/code-context, so we also surface name+stack
137 // separately in case the message was truncated or empty.
138 const escape = (s) => String(s == null ? '' : s)
139 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
140 res.status(500).send(`<!doctype html>
141<meta charset="utf-8">
142<title>Render error: ${escape(viewName)}</title>
143<style>
144 body { font: 14px/1.5 ui-monospace, monospace; max-width: 1100px; margin: 2rem auto; padding: 0 1rem; background:#1a1a1a; color:#eee; }
145 h1 { color:#dc2626; font-family: ui-sans-serif, system-ui; }
146 h2 { color:#fb923c; font-size:1rem; margin-top:1.5rem; }
147 pre { background:#0a0a0a; border:1px solid #333; border-radius:6px; padding:1rem; overflow:auto; white-space:pre-wrap; word-break:break-word; }
148 .cause { background:#3d0a0a; border-color:#7a1a1a; color:#fca5a5; font-weight:600; }
149</style>
150<h1>Render error in ${escape(viewName)}</h1>
151<h2>Cause</h2>
152<pre class="cause">${escape(err.name || 'Error')}: ${escape(err.message || '(no message)')}</pre>
153<h2>Stack</h2>
154<pre>${escape(err.stack || '(no stack)')}</pre>
155${err.path ? `<h2>File</h2><pre>${escape(err.path)}</pre>` : ''}
156`);
157 }
158}
Note: See TracBrowser for help on using the repository browser.