Files
crosscode-platform/apps/events/backend/src/utils/logoCopy.js
T

138 lines
5.2 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 when the
// profile arrives or the first PDF needs it; older copies are removed).
//
// PNG and JPEG are drawn as pictures; SVG (the demo churches' logos, and many churches') is drawn
// as shapes with svg-to-pdfkit (`drawLogo`). Anything else (WebP, GIF) isn't copied, and the PDFs
// show the church's name without a logo.
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const SVGtoPDF = require('svg-to-pdfkit');
const { UPLOADS_DIR, uploadsDir } = require('./uploads');
const MAX_BYTES = 2 * 1024 * 1024;
const TIMEOUT_MS = 5000;
const EXT = { png: 'png', jpeg: 'jpg', svg: 'svg' };
/** PNG, JPEG or SVG by the file's own bytes (never by what a server says it is), else null. */
function logoKind(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';
const head = buf.subarray(0, 4096).toString('utf8').replace(/^/, '').trimStart();
if (head.startsWith('<') && /<svg[\s>]/i.test(head)) return 'svg';
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(EXT)) {
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 = logoKind(buf);
if (!kind) return null; // WebP, GIF…: not drawable in a PDF
const dir = uploadsDir('accounts');
const base = nameFor(url);
const file = path.join(dir, `${base}.${EXT[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 (`drawLogo`), 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(/^\//, ''));
try {
return fs.existsSync(p) && logoKind(fs.readFileSync(p)) ? p : null;
} catch {
return 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);
}
/**
* Draws the logo `file` (from pdfLogoPath) at x, y within `fit` [w, h], as doc.image does; centred
* in that box with `align: 'center'`. True when drawn. Never throws.
*/
function drawLogo(doc, file, x, y, { fit, align } = {}) {
if (!file) return false;
try {
if (file.toLowerCase().endsWith('.svg')) {
const [width, height] = fit || [100, 50];
SVGtoPDF(doc, fs.readFileSync(file, 'utf8'), x, y, {
width,
height,
preserveAspectRatio: align === 'center' ? 'xMidYMid meet' : 'xMinYMid meet',
// Only pictures inside the SVG itself: never a file or address it names.
imageCallback: (link) => (/^data:image\/(png|jpe?g);base64,/i.test(String(link).trim()) ? String(link).replace(/\s+/g, '') : ''),
warningCallback: () => {},
});
} else {
doc.image(file, x, y, { fit, ...(align ? { align } : {}) });
}
return true;
} catch {
return false;
}
}
/** Tests: forget the addresses that gave nothing. */
function resetLogoCopies() {
misses.clear();
}
module.exports = { pdfLogoPath, drawLogo, resetLogoCopies, logoKind };