events 3.9.0, website 1.9.0, accounts 1.10.0: the church's details from Accounts everywhere
- Events: the Accounts profile's name, logo, icon, colours and contact details win over Events' own settings while Accounts is connected (pages, emails, WhatsApp, PDFs); Settings shows them read-only with a link to Accounts. The Accounts logo is copied for PDFs (PNG and JPEG). Fixes Events keeping its old church after a demo scenario load. - Website: a background per homepage section in the church's colours; "More info" instead of "Register" for events without registration; the shared colour field. - Accounts: the shared colour field in Church profile. - @crosscode/ui 0.4.0: ColourField and isHexColour. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
// The logo for PDFs (tickets, invoices, receipts, certificates, privacy exports). PDFs need a file
|
||||
// on disk. A logo uploaded here already is one; the church's logo from its Accounts profile is an
|
||||
// address on another site, so a copy is kept in uploads/accounts (one per address, made the first
|
||||
// time it's needed and when Accounts says the church changed; older copies are removed).
|
||||
//
|
||||
// Only PNG and JPEG can be drawn into a PDF, so another kind of logo (SVG, WebP) isn't copied and
|
||||
// the PDFs show the church's name without it, as before.
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { UPLOADS_DIR, uploadsDir } = require('./uploads');
|
||||
|
||||
const MAX_BYTES = 2 * 1024 * 1024;
|
||||
const TIMEOUT_MS = 5000;
|
||||
const KINDS = { png: 'png', jpeg: 'jpg' };
|
||||
|
||||
/** PNG or JPEG by its first bytes (never by what the server says it is), else null. */
|
||||
function rasterKind(buf) {
|
||||
if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
|
||||
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'jpeg';
|
||||
return null;
|
||||
}
|
||||
|
||||
const nameFor = (url) => `logo-${crypto.createHash('sha256').update(url).digest('hex').slice(0, 16)}`;
|
||||
|
||||
/** An outside address the site may fetch the logo from: https, or http while developing. */
|
||||
function fetchable(url) {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
return u.protocol === 'https:' || (u.protocol === 'http:' && process.env.NODE_ENV !== 'production');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function existingCopy(url) {
|
||||
const base = nameFor(url);
|
||||
for (const ext of Object.values(KINDS)) {
|
||||
const p = path.join(UPLOADS_DIR, 'accounts', `${base}.${ext}`);
|
||||
if (fs.existsSync(p)) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Addresses tried lately that gave no usable logo: not fetched again for 10 minutes.
|
||||
const misses = new Map();
|
||||
const MISS_MS = 10 * 60e3;
|
||||
const pending = new Map();
|
||||
|
||||
async function download(url) {
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS), redirect: 'follow' });
|
||||
if (!res.ok) throw new Error(`answered ${res.status}`);
|
||||
if (Number(res.headers.get('content-length') || 0) > MAX_BYTES) throw new Error('is larger than 2 MB');
|
||||
const buf = Buffer.from(await res.arrayBuffer());
|
||||
if (buf.length > MAX_BYTES) throw new Error('is larger than 2 MB');
|
||||
const kind = rasterKind(buf);
|
||||
if (!kind) return null; // SVG, WebP…: not drawable in a PDF
|
||||
const dir = uploadsDir('accounts');
|
||||
const base = nameFor(url);
|
||||
const file = path.join(dir, `${base}.${KINDS[kind]}`);
|
||||
fs.writeFileSync(file, buf);
|
||||
// The church changed its logo: the copies of the old ones go.
|
||||
for (const f of fs.readdirSync(dir)) if (f.startsWith('logo-') && !f.startsWith(`${base}.`)) fs.rmSync(path.join(dir, f), { force: true });
|
||||
return file;
|
||||
}
|
||||
|
||||
/**
|
||||
* The logo as a file a PDF can draw, or null. `logoUrl` is the logo_url setting: a path on this
|
||||
* site (/uploads/…) or the church's logo address from Accounts. Never throws.
|
||||
*/
|
||||
async function pdfLogoPath(logoUrl) {
|
||||
const url = String(logoUrl || '').trim();
|
||||
if (!url) return null;
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
const p = path.join(UPLOADS_DIR, '..', url.replace(/^\//, ''));
|
||||
return fs.existsSync(p) && rasterKind(fs.readFileSync(p).subarray(0, 8)) ? p : null;
|
||||
}
|
||||
if (!fetchable(url)) return null;
|
||||
const have = existingCopy(url);
|
||||
if (have) return have;
|
||||
const missed = misses.get(url);
|
||||
if (missed && Date.now() - missed < MISS_MS) return null;
|
||||
if (!pending.has(url)) {
|
||||
pending.set(url, download(url)
|
||||
.catch((e) => {
|
||||
console.warn(`[logo] the church's logo couldn't be copied for PDFs: ${url} ${e.message}`);
|
||||
return null;
|
||||
})
|
||||
.then((file) => {
|
||||
if (!file) misses.set(url, Date.now());
|
||||
return file;
|
||||
})
|
||||
.finally(() => pending.delete(url)));
|
||||
}
|
||||
return pending.get(url);
|
||||
}
|
||||
|
||||
/** Tests: forget the addresses that gave nothing. */
|
||||
function resetLogoCopies() {
|
||||
misses.clear();
|
||||
}
|
||||
|
||||
module.exports = { pdfLogoPath, resetLogoCopies, rasterKind };
|
||||
@@ -55,11 +55,8 @@ async function getBranding() {
|
||||
getSetting('logo_url', ''),
|
||||
]);
|
||||
const url = (process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, '');
|
||||
let logoPath = null;
|
||||
if (logoUrl) {
|
||||
const p = path.join(__dirname, '..', '..', 'public', logoUrl.replace(/^\//, ''));
|
||||
if (fs.existsSync(p)) logoPath = p;
|
||||
}
|
||||
// An uploaded logo, or a copy of the church's logo from Accounts (utils/logoCopy.js).
|
||||
const logoPath = await require('./logoCopy').pdfLogoPath(logoUrl);
|
||||
return { name, address, email, phone, brandColor: primary || accent || '#1e3a5f', url, logoPath };
|
||||
}
|
||||
|
||||
|
||||
@@ -17,9 +17,37 @@ let _cache = {};
|
||||
let _lastFetch = 0;
|
||||
const TTL_MS = 60 * 1000;
|
||||
|
||||
/**
|
||||
* The church's own details from its Accounts profile (src/accounts/church.ts): name, logo, icon,
|
||||
* colours and contact details. Accounts owns them, so while it's connected they win over this
|
||||
* site's own settings everywhere (pages, emails, PDFs). Empty without Accounts.
|
||||
*/
|
||||
let _fromAccounts = {};
|
||||
|
||||
/** Set by src/accounts/church.ts whenever it has (or loses) the church profile. */
|
||||
function setAccountsOverrides(map) {
|
||||
_fromAccounts = { ...(map || {}) };
|
||||
}
|
||||
|
||||
/** The keys Accounts sets right now, with their values. */
|
||||
function accountsOverrides() {
|
||||
return { ..._fromAccounts };
|
||||
}
|
||||
|
||||
/** The church profile is kept fresh as the settings are (it caches itself for 10 minutes). */
|
||||
function refreshChurchProfile() {
|
||||
try {
|
||||
const p = require('../accounts/church').churchProfile();
|
||||
if (p && typeof p.catch === 'function') p.catch(() => {});
|
||||
} catch {
|
||||
// No Accounts code in this context (some tests): the site's own settings stand.
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshIfStale() {
|
||||
const now = Date.now();
|
||||
if (now - _lastFetch < TTL_MS && _lastFetch > 0) return;
|
||||
refreshChurchProfile();
|
||||
try {
|
||||
const rows = await prisma.appSetting.findMany();
|
||||
const fresh = {};
|
||||
@@ -38,6 +66,13 @@ async function refreshIfStale() {
|
||||
* @returns {string}
|
||||
*/
|
||||
function _getSync(key, envFallback = '') {
|
||||
const a = _fromAccounts[key];
|
||||
if (typeof a === 'string' && a !== '') return a;
|
||||
return _getStoredSync(key, envFallback);
|
||||
}
|
||||
|
||||
/** This site's own value, ignoring Accounts (for sending this site's look to Accounts, src/accounts/look.ts). */
|
||||
function _getStoredSync(key, envFallback = '') {
|
||||
const v = _cache[key];
|
||||
const raw = (v !== undefined && v !== null && v !== '') ? v : (envFallback || '');
|
||||
if (ENCRYPTED_KEYS.has(key) && isEncrypted(raw)) {
|
||||
@@ -76,4 +111,10 @@ function invalidate() {
|
||||
refreshIfStale().catch(() => {});
|
||||
}
|
||||
|
||||
module.exports = { getSetting, getSettingSync, warmCache, invalidate, ENCRYPTED_KEYS };
|
||||
/** As getSetting, but this site's own value even when Accounts sets the key. */
|
||||
async function getStoredSetting(key, envFallback = '') {
|
||||
await refreshIfStale();
|
||||
return _getStoredSync(key, envFallback);
|
||||
}
|
||||
|
||||
module.exports = { getSetting, getSettingSync, getStoredSetting, warmCache, invalidate, setAccountsOverrides, accountsOverrides, ENCRYPTED_KEYS };
|
||||
Reference in New Issue
Block a user