| 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 |
|
|---|
| 12 | import fs from 'fs';
|
|---|
| 13 | import path from 'path';
|
|---|
| 14 | import { fileURLToPath } from 'url';
|
|---|
| 15 | import ejs from 'ejs';
|
|---|
| 16 | import db from '../config/database.js';
|
|---|
| 17 | import PermissionsService from '../services/PermissionsService.js';
|
|---|
| 18 | import { isViewer } from './auth.js';
|
|---|
| 19 | import { getSetting } from '../services/SettingsService.js';
|
|---|
| 20 | import { isPremium as isPremiumInstance, premiumEnabled, premiumUnlocked } from '../services/PatreonService.js';
|
|---|
| 21 | import ActivityPubService from '../services/ActivityPubService.js';
|
|---|
| 22 | import { audioEnabled as audioFeatureEnabled } from '../config/features.js';
|
|---|
| 23 | import { PLATFORMS as PLATFORMS_CATALOG } from '../services/PlatformIcons.js';
|
|---|
| 24 | import { t as i18nT, resolveLang, SUPPORTED as LANGS, LANG_NAMES } from '../services/i18n.js';
|
|---|
| 25 |
|
|---|
| 26 | const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|---|
| 27 | const VIEWS_DIR = path.join(__dirname, '..', 'views');
|
|---|
| 28 |
|
|---|
| 29 | // App version (from package.json) + short commit hash (from .klonkt-version, written by
|
|---|
| 30 | // the deploy script) — shown in the footer next to "Klonkt Beta". The hash is updated
|
|---|
| 31 | // automatically on every deploy, so the displayed version is never stale.
|
|---|
| 32 | let APP_VERSION = '';
|
|---|
| 33 | try {
|
|---|
| 34 | APP_VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8')).version || '';
|
|---|
| 35 | try {
|
|---|
| 36 | const sha = fs.readFileSync(path.join(__dirname, '..', '..', '.klonkt-version'), 'utf8').trim().slice(0, 7);
|
|---|
| 37 | if (sha) APP_VERSION += ' · ' + sha;
|
|---|
| 38 | } catch { /* no .klonkt-version (local dev) */ }
|
|---|
| 39 | } catch { /* no version available */ }
|
|---|
| 40 |
|
|---|
| 41 | // Site timezone (Admin → Settings). Empty = server default (UTC). Applied to
|
|---|
| 42 | // all server-side formatted dates so they display in the site's timezone instead of UTC.
|
|---|
| 43 | const siteTimezone = () => getSetting('timezone') || undefined;
|
|---|
| 44 |
|
|---|
| 45 | const formatDate = (iso) => {
|
|---|
| 46 | if (!iso) return '';
|
|---|
| 47 | return new Date(iso).toLocaleDateString('nl-NL', { timeZone: siteTimezone(), day: 'numeric', month: 'long', year: 'numeric' });
|
|---|
| 48 | };
|
|---|
| 49 |
|
|---|
| 50 | const formatDateTime = (iso) => {
|
|---|
| 51 | if (!iso) return '';
|
|---|
| 52 | return new Date(iso).toLocaleString('nl-NL', { timeZone: siteTimezone(), dateStyle: 'medium', timeStyle: 'short' });
|
|---|
| 53 | };
|
|---|
| 54 |
|
|---|
| 55 | export async function renderPage(req, res, viewName, data = {}) {
|
|---|
| 56 | // Decide: partial (HTMX) or full?
|
|---|
| 57 | const isPartial = req.headers['hx-request'] === 'true' || req.query.partial === '1';
|
|---|
| 58 |
|
|---|
| 59 | // Prevent the browser from caching an htmx PARTIAL (only #pcms-main, without <head>/CSS)
|
|---|
| 60 | // under the same URL and serving it as a full page on "back" → unstyled HTML.
|
|---|
| 61 | // Vary: HX-Request separates partial and full responses in the cache;
|
|---|
| 62 | // no-store on the partial forces "back" to always re-fetch the full page.
|
|---|
| 63 | // (Vary also applies to intermediate caches / Cloudflare.)
|
|---|
| 64 | res.setHeader('Vary', 'HX-Request');
|
|---|
| 65 | if (isPartial) res.setHeader('Cache-Control', 'no-store');
|
|---|
| 66 |
|
|---|
| 67 | // Does this (non-god) user own a site? Determines whether they see an "Admin"
|
|---|
| 68 | // entry (artist self-manage). god always sees admin (by role).
|
|---|
| 69 | let _u = req.session?.user || null;
|
|---|
| 70 | // Refresh avatar + role from the DB so a stale session (e.g. after an
|
|---|
| 71 | // avatar change or role switch) heals itself without a new login.
|
|---|
| 72 | if (_u && _u.id) {
|
|---|
| 73 | const _fresh = db.prepare('SELECT avatar_url, role, lang FROM users WHERE id = ?').get(_u.id);
|
|---|
| 74 | if (_fresh) _u = { ..._u, avatar_url: _fresh.avatar_url, role: _fresh.role, lang: _fresh.lang };
|
|---|
| 75 | // One identity: no own account avatar → fall back to the user's site photo,
|
|---|
| 76 | // so the same picture shows everywhere (nav, account, comments).
|
|---|
| 77 | if (_u && !_u.avatar_url) {
|
|---|
| 78 | const _sp = db.prepare("SELECT profile_photo FROM sites WHERE owner_id = ? AND profile_photo IS NOT NULL ORDER BY is_primary DESC, created_at ASC LIMIT 1").get(_u.id);
|
|---|
| 79 | if (_sp && _sp.profile_photo) _u = { ..._u, avatar_url: _sp.profile_photo };
|
|---|
| 80 | }
|
|---|
| 81 | }
|
|---|
| 82 | const userOwnsSite = !!(_u && _u.role !== 'god' &&
|
|---|
| 83 | db.prepare('SELECT 1 FROM sites WHERE owner_id = ? LIMIT 1').get(_u.id));
|
|---|
| 84 |
|
|---|
| 85 | // The avatar of the SITE OWNER (not the viewer!) — for the Klonkt site header,
|
|---|
| 86 | // so the artist can use their own account photo as the site photo.
|
|---|
| 87 | const _site = data.site || res.locals.site || null;
|
|---|
| 88 | const siteOwnerAvatar = (_site && _site.owner_id)
|
|---|
| 89 | ? (db.prepare('SELECT avatar_url FROM users WHERE id = ?').get(_site.owner_id)?.avatar_url || null)
|
|---|
| 90 | : null;
|
|---|
| 91 |
|
|---|
| 92 | // Viewer mode: may view everything, change nothing. Views use canMutate
|
|---|
| 93 | // to hide/disable write buttons (post, save, delete).
|
|---|
| 94 | const _isViewer = isViewer(_u);
|
|---|
| 95 |
|
|---|
| 96 | // Who sees the "Admin" link? god/admin, a site owner (artist self-manage),
|
|---|
| 97 | // and a viewer (may view Admin read-only). One source of truth,
|
|---|
| 98 | // mirrored in topnav/hub-nav/profile sheet — otherwise the link gets hidden
|
|---|
| 99 | // for those who should see it (viewer didn't see it anywhere before).
|
|---|
| 100 | const _role = _u ? _u.role : null;
|
|---|
| 101 | const canSeeBeheer = !!(_u && (_role === 'god' || _role === 'admin' || _role === 'kijker' || userOwnsSite));
|
|---|
| 102 | // Who may use the fediverse client (timeline/notifications/blocking) — actual
|
|---|
| 103 | // site managers only (these routes are requireSiteManager; viewers are excluded).
|
|---|
| 104 | const canManageFedi = !!(_u && (_role === 'god' || _role === 'admin' || userOwnsSite));
|
|---|
| 105 |
|
|---|
| 106 | // Interface language: session choice (this session) → logged-in user's own preference
|
|---|
| 107 | // (users.lang) → admin-set default (Admin → Settings) → env → browser → nl.
|
|---|
| 108 | const _lang = resolveLang(req, {
|
|---|
| 109 | userLang: _u && _u.lang,
|
|---|
| 110 | defaultLang: getSetting('default_lang'),
|
|---|
| 111 | });
|
|---|
| 112 |
|
|---|
| 113 | // Common locals
|
|---|
| 114 | const locals = {
|
|---|
| 115 | user: _u,
|
|---|
| 116 | lang: _lang,
|
|---|
| 117 | t: (key, vars) => i18nT(_lang, key, vars),
|
|---|
| 118 | langs: LANGS.map((c) => ({ code: c, name: LANG_NAMES[c], active: c === _lang })),
|
|---|
| 119 | timezone: getSetting('timezone') || '',
|
|---|
| 120 | notifUnread: (canManageFedi && _site) ? ActivityPubService.countUnseenNotifications(_site.slug) : 0,
|
|---|
| 121 | userOwnsSite,
|
|---|
| 122 | canSeeBeheer,
|
|---|
| 123 | canManageFedi,
|
|---|
| 124 | isViewer: _isViewer,
|
|---|
| 125 | canMutate: !_isViewer,
|
|---|
| 126 | isPremium: isPremiumInstance(),
|
|---|
| 127 | premiumEnabled: premiumEnabled(),
|
|---|
| 128 | premiumUnlocked: premiumUnlocked(),
|
|---|
| 129 | siteOwnerAvatar,
|
|---|
| 130 | site: _site,
|
|---|
| 131 | audioEnabled: audioFeatureEnabled(),
|
|---|
| 132 | audioTracks: data.audioTracks || res.locals.audioTracks || [],
|
|---|
| 133 | siteUrlBase: res.locals.siteUrlBase || '',
|
|---|
| 134 | tenancy: res.locals.tenancy || 'solo',
|
|---|
| 135 | hubTitle: getSetting('hub_title') || '',
|
|---|
| 136 | footerNewsletter: getSetting('footer_newsletter') === '1', // newsletter sign-up in footer (premium)
|
|---|
| 137 | agendaEnabled: getSetting('agenda_enabled') === '1', // show agenda/events in the pill (premium, opt-in)
|
|---|
| 138 | platforms_catalog: PLATFORMS_CATALOG,
|
|---|
| 139 | permissions: PermissionsService,
|
|---|
| 140 | formatDate,
|
|---|
| 141 | formatDateTime,
|
|---|
| 142 | pageTitle: data.pageTitle || (data.site && data.site.title) || 'Klonkt Beta',
|
|---|
| 143 | appVersion: APP_VERSION,
|
|---|
| 144 | bodyClass: data.bodyClass || 'on-home',
|
|---|
| 145 | socialDescr: data.socialDescr || '',
|
|---|
| 146 | socialImage: data.socialImage || '',
|
|---|
| 147 | cspNonce: () => '',
|
|---|
| 148 | currentPath: req.path,
|
|---|
| 149 | // Absolute origin (for building absolute URLs like the generated og:image).
|
|---|
| 150 | ogOrigin: (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host') || ''}`).replace(/\/+$/, ''),
|
|---|
| 151 | ...data,
|
|---|
| 152 | };
|
|---|
| 153 |
|
|---|
| 154 | try {
|
|---|
| 155 | // Step 1: Render the page view to HTML
|
|---|
| 156 | const viewPath = path.join(VIEWS_DIR, viewName + '.ejs');
|
|---|
| 157 | const pageContent = await ejs.renderFile(viewPath, locals, { async: false });
|
|---|
| 158 |
|
|---|
| 159 | if (isPartial) {
|
|---|
| 160 | // HTMX: just send the content. Set HX-Trigger for body class swap.
|
|---|
| 161 | // HTTP-header values are Latin-1 only — a title with an em-dash, smart
|
|---|
| 162 | // quote or emoji (e.g. "Welkom — gebouwd met Klonkt") would make
|
|---|
| 163 | // setHeader throw ERR_INVALID_CHAR and 500 the partial, so the card
|
|---|
| 164 | // looks "unclickable". Escape any non-ASCII to \uXXXX: the header stays
|
|---|
| 165 | // ASCII-safe and remains valid JSON that htmx parses back unchanged.
|
|---|
| 166 | // Per-site accent + palette live in the shell <head> (style#pcms-site-accent
|
|---|
| 167 | // + html[data-palette]) and are NOT swapped during htmx navigation. Send them along
|
|---|
| 168 | // so the client updates them — otherwise an artist inherits the previous page's
|
|---|
| 169 | // colours (e.g. hub-purple instead of their own green). Same derivation as shell.ejs.
|
|---|
| 170 | const _navAccent = (_site && _site.accent && /^#[0-9a-fA-F]{6}$/.test(_site.accent))
|
|---|
| 171 | ? _site.accent : '#e8b04b';
|
|---|
| 172 | const _navPalette = (_site && _site.palette) ? _site.palette : 'klonkt';
|
|---|
| 173 | const triggerJson = JSON.stringify({
|
|---|
| 174 | pcmsNav: { bodyClass: locals.bodyClass, accent: _navAccent, palette: _navPalette },
|
|---|
| 175 | pcmsPostSwap: data.post ? {
|
|---|
| 176 | title: data.post.title,
|
|---|
| 177 | slug: data.post.slug,
|
|---|
| 178 | pageTitle: locals.pageTitle,
|
|---|
| 179 | } : null,
|
|---|
| 180 | }).replace(/[-]/g, (ch) => '\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0'));
|
|---|
| 181 | res.setHeader('HX-Trigger-After-Settle', triggerJson);
|
|---|
| 182 | // Render the site chrome out-of-band so the header (topnav/profile header/
|
|---|
| 183 | // view-switcher) ALWAYS matches the new page/artist on navigation —
|
|---|
| 184 | // while the audio player (separate in document.body) keeps playing (no
|
|---|
| 185 | // interruption). htmx replaces #pcms-chrome via hx-swap-oob. Non-critical:
|
|---|
| 186 | // if it fails, the old chrome remains (no crash).
|
|---|
| 187 | let oobChrome = '';
|
|---|
| 188 | try {
|
|---|
| 189 | oobChrome = await ejs.renderFile(
|
|---|
| 190 | path.join(VIEWS_DIR, 'partials', 'chrome.ejs'),
|
|---|
| 191 | { ...locals, oob: true },
|
|---|
| 192 | { async: false },
|
|---|
| 193 | );
|
|---|
| 194 | } catch (e) { /* skip chrome OOB */ }
|
|---|
| 195 | return res.send(pageContent + oobChrome);
|
|---|
| 196 | }
|
|---|
| 197 |
|
|---|
| 198 | // Full: wrap content in shell
|
|---|
| 199 | locals.pageContent = pageContent;
|
|---|
| 200 | res.render('shell', locals);
|
|---|
| 201 | } catch (err) {
|
|---|
| 202 | console.error('[renderPage] Error rendering', viewName, err);
|
|---|
| 203 | if (process.env.NODE_ENV === 'production') {
|
|---|
| 204 | return res.status(500).send('Internal Server Error');
|
|---|
| 205 | }
|
|---|
| 206 | // Dev: surface the underlying cause prominently. EJS rewrites err.message
|
|---|
| 207 | // to include the file/line/code-context, so we also surface name+stack
|
|---|
| 208 | // separately in case the message was truncated or empty.
|
|---|
| 209 | const escape = (s) => String(s == null ? '' : s)
|
|---|
| 210 | .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|---|
| 211 | res.status(500).send(`<!doctype html>
|
|---|
| 212 | <meta charset="utf-8">
|
|---|
| 213 | <title>Render error: ${escape(viewName)}</title>
|
|---|
| 214 | <style>
|
|---|
| 215 | body { font: 14px/1.5 ui-monospace, monospace; max-width: 1100px; margin: 2rem auto; padding: 0 1rem; background:#1a1a1a; color:#eee; }
|
|---|
| 216 | h1 { color:#dc2626; font-family: ui-sans-serif, system-ui; }
|
|---|
| 217 | h2 { color:#fb923c; font-size:1rem; margin-top:1.5rem; }
|
|---|
| 218 | pre { background:#0a0a0a; border:1px solid #333; border-radius:6px; padding:1rem; overflow:auto; white-space:pre-wrap; word-break:break-word; }
|
|---|
| 219 | .cause { background:#3d0a0a; border-color:#7a1a1a; color:#fca5a5; font-weight:600; }
|
|---|
| 220 | </style>
|
|---|
| 221 | <h1>Render error in ${escape(viewName)}</h1>
|
|---|
| 222 | <h2>Cause</h2>
|
|---|
| 223 | <pre class="cause">${escape(err.name || 'Error')}: ${escape(err.message || '(no message)')}</pre>
|
|---|
| 224 | <h2>Stack</h2>
|
|---|
| 225 | <pre>${escape(err.stack || '(no stack)')}</pre>
|
|---|
| 226 | ${err.path ? `<h2>File</h2><pre>${escape(err.path)}</pre>` : ''}
|
|---|
| 227 | `);
|
|---|
| 228 | }
|
|---|
| 229 | }
|
|---|