source: Klonkt/src/middleware/render.js@ 9910ba1

main
Last change on this file since 9910ba1 was cca2e89, checked in by Robin Genis <roboburr@…>, 2 months ago

feat(identity): one image — the site photo is the only avatar input

Removed the separate account-avatar upload. A user's avatar everywhere (nav, account, profile
header, fediverse) is now their SITE photo, set in one place (site settings). The account page
shows it read-only with a link.

  • middleware/render.js — nav avatar = site photo always; drop the account-avatar cross-fallback
  • views/pages/account.ejs — remove the avatar upload; read-only site photo + hint to site settings
  • services/i18n.js — acct.photo_site_hint (nl/en/de)
  • Property mode set to 100644
File size: 11.8 KB
RevLine 
[7bc636b]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
[83faa57]12import fs from 'fs';
[7bc636b]13import path from 'path';
14import { fileURLToPath } from 'url';
15import ejs from 'ejs';
[8cb1dc7]16import db from '../config/database.js';
[7bc636b]17import PermissionsService from '../services/PermissionsService.js';
[8afbdd6]18import { isViewer } from './auth.js';
[283f618]19import { getSetting, apEnabled } from '../services/SettingsService.js';
[8aa85d0]20import { isPremium as isPremiumInstance, premiumEnabled, premiumUnlocked } from '../services/PatreonService.js';
[e951b7c]21import ActivityPubService from '../services/ActivityPubService.js';
[cb01666]22import { audioEnabled as audioFeatureEnabled } from '../config/features.js';
[7bc636b]23import { PLATFORMS as PLATFORMS_CATALOG } from '../services/PlatformIcons.js';
[03fa548]24import { t as i18nT, resolveLang, SUPPORTED as LANGS, LANG_NAMES } from '../services/i18n.js';
[7bc636b]25
26const __dirname = path.dirname(fileURLToPath(import.meta.url));
27const VIEWS_DIR = path.join(__dirname, '..', 'views');
28
[834bcc3]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.
[83faa57]32let APP_VERSION = '';
33try {
34 APP_VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8')).version || '';
[3bb8719]35 try {
36 const sha = fs.readFileSync(path.join(__dirname, '..', '..', '.klonkt-version'), 'utf8').trim().slice(0, 7);
37 if (sha) APP_VERSION += ' · ' + sha;
[834bcc3]38 } catch { /* no .klonkt-version (local dev) */ }
39} catch { /* no version available */ }
[83faa57]40
[834bcc3]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.
[421c2d4]43const siteTimezone = () => getSetting('timezone') || undefined;
44
[7bc636b]45const formatDate = (iso) => {
46 if (!iso) return '';
[421c2d4]47 return new Date(iso).toLocaleDateString('nl-NL', { timeZone: siteTimezone(), day: 'numeric', month: 'long', year: 'numeric' });
[7bc636b]48};
49
50const formatDateTime = (iso) => {
51 if (!iso) return '';
[421c2d4]52 return new Date(iso).toLocaleString('nl-NL', { timeZone: siteTimezone(), dateStyle: 'medium', timeStyle: 'short' });
[7bc636b]53};
54
55export 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
[834bcc3]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.)
[d5e78f7]64 res.setHeader('Vary', 'HX-Request');
65 if (isPartial) res.setHeader('Cache-Control', 'no-store');
66
[834bcc3]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).
[1ee967d]69 let _u = req.session?.user || null;
[834bcc3]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.
[1ee967d]72 if (_u && _u.id) {
[cca2e89]73 const _fresh = db.prepare('SELECT role, lang FROM users WHERE id = ?').get(_u.id);
74 if (_fresh) _u = { ..._u, role: _fresh.role, lang: _fresh.lang };
75 // ONE image: a user's avatar everywhere (nav, account, comments) is simply their SITE
76 // photo — there is no separate account avatar. Falls back to the initial-letter
77 // placeholder when the site has no photo yet.
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 _u = { ..._u, avatar_url: (_sp && _sp.profile_photo) || null };
[1ee967d]80 }
[8cb1dc7]81 const userOwnsSite = !!(_u && _u.role !== 'god' &&
82 db.prepare('SELECT 1 FROM sites WHERE owner_id = ? LIMIT 1').get(_u.id));
83
[ab544fd]84 const _site = data.site || res.locals.site || null;
[cca2e89]85 // The site header uses the SITE photo (site.profile_photo) — the one and only image,
86 // set in site settings. (No separate account-avatar fallback anymore.)
87 const siteOwnerAvatar = null;
[ab544fd]88
[834bcc3]89 // Viewer mode: may view everything, change nothing. Views use canMutate
90 // to hide/disable write buttons (post, save, delete).
[8afbdd6]91 const _isViewer = isViewer(_u);
92
[07de464]93 // Embeds are framed broadly (frame-src https: globally), EXCEPT on authorize_interaction:
94 // that page renders untrusted remote content next to the interact buttons, so lock its
95 // frame-src down to 'self' (no embeds → no clickjacking/overlay over the buttons).
96 if (viewName === 'pages/authorize-interaction') {
97 try {
98 const csp = res.getHeader('Content-Security-Policy');
99 if (csp) res.setHeader('Content-Security-Policy', String(csp).replace(/frame-src [^;]*/i, "frame-src 'self'"));
100 } catch { /* best-effort */ }
101 }
[5421ce1]102
[834bcc3]103 // Who sees the "Admin" link? god/admin, a site owner (artist self-manage),
104 // and a viewer (may view Admin read-only). One source of truth,
105 // mirrored in topnav/hub-nav/profile sheet — otherwise the link gets hidden
106 // for those who should see it (viewer didn't see it anywhere before).
[a3169f5]107 const _role = _u ? _u.role : null;
108 const canSeeBeheer = !!(_u && (_role === 'god' || _role === 'admin' || _role === 'kijker' || userOwnsSite));
[f5c3870]109 // Who may use the fediverse client (timeline/notifications/blocking) — actual
110 // site managers only (these routes are requireSiteManager; viewers are excluded).
111 const canManageFedi = !!(_u && (_role === 'god' || _role === 'admin' || userOwnsSite));
[a3169f5]112
[834bcc3]113 // Interface language: session choice (this session) → logged-in user's own preference
114 // (users.lang) → admin-set default (Admin → Settings) → env → browser → nl.
[5e61b17]115 const _lang = resolveLang(req, {
116 userLang: _u && _u.lang,
117 defaultLang: getSetting('default_lang'),
118 });
[03fa548]119
[7bc636b]120 // Common locals
121 const locals = {
[8cb1dc7]122 user: _u,
[03fa548]123 lang: _lang,
124 t: (key, vars) => i18nT(_lang, key, vars),
125 langs: LANGS.map((c) => ({ code: c, name: LANG_NAMES[c], active: c === _lang })),
[421c2d4]126 timezone: getSetting('timezone') || '',
[e951b7c]127 notifUnread: (canManageFedi && _site) ? ActivityPubService.countUnseenNotifications(_site.slug) : 0,
[8cb1dc7]128 userOwnsSite,
[a3169f5]129 canSeeBeheer,
[f5c3870]130 canManageFedi,
[283f618]131 apEnabled: apEnabled(),
[2c22bb5]132 // Cirkel = the artists you feature (auto-boost). Shown when AP is on and you
133 // auto-boost ≥1 account, or (legacy) on a circle-tenancy site.
[5045c30]134 hasCirkel: !!(_site && apEnabled() && (ActivityPubService.autoBoostCount(_site.slug) > 0 || ActivityPubService.boostedCount(_site.slug) > 0)),
[8afbdd6]135 isViewer: _isViewer,
136 canMutate: !_isViewer,
[1b4d5dd]137 isPremium: isPremiumInstance(),
138 premiumEnabled: premiumEnabled(),
[8aa85d0]139 premiumUnlocked: premiumUnlocked(),
[ab544fd]140 siteOwnerAvatar,
141 site: _site,
[cb01666]142 audioEnabled: audioFeatureEnabled(),
[7bc636b]143 audioTracks: data.audioTracks || res.locals.audioTracks || [],
144 siteUrlBase: res.locals.siteUrlBase || '',
[2cc887b]145 tenancy: res.locals.tenancy || 'solo',
[42081fb]146 hubTitle: getSetting('hub_title') || '',
[834bcc3]147 footerNewsletter: getSetting('footer_newsletter') === '1', // newsletter sign-up in footer (premium)
148 agendaEnabled: getSetting('agenda_enabled') === '1', // show agenda/events in the pill (premium, opt-in)
[7bc636b]149 platforms_catalog: PLATFORMS_CATALOG,
150 permissions: PermissionsService,
151 formatDate,
152 formatDateTime,
[4fdbbe6]153 pageTitle: data.pageTitle || (data.site && data.site.title) || 'Klonkt',
[83faa57]154 appVersion: APP_VERSION,
[7bc636b]155 bodyClass: data.bodyClass || 'on-home',
156 socialDescr: data.socialDescr || '',
157 socialImage: data.socialImage || '',
158 cspNonce: () => '',
159 currentPath: req.path,
[69815b2]160 // Absolute origin (for building absolute URLs like the generated og:image).
161 ogOrigin: (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host') || ''}`).replace(/\/+$/, ''),
[7bc636b]162 ...data,
163 };
164
165 try {
166 // Step 1: Render the page view to HTML
167 const viewPath = path.join(VIEWS_DIR, viewName + '.ejs');
168 const pageContent = await ejs.renderFile(viewPath, locals, { async: false });
169
170 if (isPartial) {
[00d54bc]171 // HTMX: just send the content. Set HX-Trigger for body class swap.
172 // HTTP-header values are Latin-1 only — a title with an em-dash, smart
173 // quote or emoji (e.g. "Welkom — gebouwd met Klonkt") would make
174 // setHeader throw ERR_INVALID_CHAR and 500 the partial, so the card
175 // looks "unclickable". Escape any non-ASCII to \uXXXX: the header stays
176 // ASCII-safe and remains valid JSON that htmx parses back unchanged.
[834bcc3]177 // Per-site accent + palette live in the shell <head> (style#pcms-site-accent
178 // + html[data-palette]) and are NOT swapped during htmx navigation. Send them along
179 // so the client updates them — otherwise an artist inherits the previous page's
180 // colours (e.g. hub-purple instead of their own green). Same derivation as shell.ejs.
[a3e2f17]181 const _navAccent = (_site && _site.accent && /^#[0-9a-fA-F]{6}$/.test(_site.accent))
[9b851e7]182 ? _site.accent : '#e8b04b';
[dd7e2a2]183 const _navPalette = (_site && _site.palette) ? _site.palette : 'klonkt';
[00d54bc]184 const triggerJson = JSON.stringify({
[a3e2f17]185 pcmsNav: { bodyClass: locals.bodyClass, accent: _navAccent, palette: _navPalette },
[7bc636b]186 pcmsPostSwap: data.post ? {
187 title: data.post.title,
188 slug: data.post.slug,
189 pageTitle: locals.pageTitle,
190 } : null,
[00d54bc]191 }).replace(/[€-￿]/g, (ch) => '\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0'));
192 res.setHeader('HX-Trigger-After-Settle', triggerJson);
[834bcc3]193 // Render the site chrome out-of-band so the header (topnav/profile header/
194 // view-switcher) ALWAYS matches the new page/artist on navigation —
195 // while the audio player (separate in document.body) keeps playing (no
196 // interruption). htmx replaces #pcms-chrome via hx-swap-oob. Non-critical:
197 // if it fails, the old chrome remains (no crash).
[3cd1aaa]198 let oobChrome = '';
199 try {
200 oobChrome = await ejs.renderFile(
201 path.join(VIEWS_DIR, 'partials', 'chrome.ejs'),
202 { ...locals, oob: true },
203 { async: false },
204 );
[834bcc3]205 } catch (e) { /* skip chrome OOB */ }
[3cd1aaa]206 return res.send(pageContent + oobChrome);
[7bc636b]207 }
208
209 // Full: wrap content in shell
210 locals.pageContent = pageContent;
211 res.render('shell', locals);
212 } catch (err) {
213 console.error('[renderPage] Error rendering', viewName, err);
214 if (process.env.NODE_ENV === 'production') {
215 return res.status(500).send('Internal Server Error');
216 }
217 // Dev: surface the underlying cause prominently. EJS rewrites err.message
218 // to include the file/line/code-context, so we also surface name+stack
219 // separately in case the message was truncated or empty.
220 const escape = (s) => String(s == null ? '' : s)
221 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
222 res.status(500).send(`<!doctype html>
223<meta charset="utf-8">
224<title>Render error: ${escape(viewName)}</title>
225<style>
226 body { font: 14px/1.5 ui-monospace, monospace; max-width: 1100px; margin: 2rem auto; padding: 0 1rem; background:#1a1a1a; color:#eee; }
227 h1 { color:#dc2626; font-family: ui-sans-serif, system-ui; }
228 h2 { color:#fb923c; font-size:1rem; margin-top:1.5rem; }
229 pre { background:#0a0a0a; border:1px solid #333; border-radius:6px; padding:1rem; overflow:auto; white-space:pre-wrap; word-break:break-word; }
230 .cause { background:#3d0a0a; border-color:#7a1a1a; color:#fca5a5; font-weight:600; }
231</style>
232<h1>Render error in ${escape(viewName)}</h1>
233<h2>Cause</h2>
234<pre class="cause">${escape(err.name || 'Error')}: ${escape(err.message || '(no message)')}</pre>
235<h2>Stack</h2>
236<pre>${escape(err.stack || '(no stack)')}</pre>
237${err.path ? `<h2>File</h2><pre>${escape(err.path)}</pre>` : ''}
238`);
239 }
240}
Note: See TracBrowser for help on using the repository browser.