f562cc50be
- Control Room rail: Training, Pipeline and Profile are first-class entries (phone bar keeps them behind More)
- /api/partner/registry: rows may carry profile {avatarUrl, bio, socials}; fills only empty fields on this side, member edits win after that
- Pages: uploaded images are stored as /u/pages/... paths (any host, local recordings included); the split hero frame keeps a 3:2 shape with a tinted ground when an image fails to load (was a thin white bar)
- Home page section + chatbot canned answer + FACTS: InstantAdPay = marketplace, LinkSpin = tool side, same line and wallet
- asset tags bumped to 20261011a
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
257 lines
27 KiB
JavaScript
257 lines
27 KiB
JavaScript
// LinkSpin Pages (2026-09-29): member pages (bridge, review, squeeze) built from a scan of the destination plus a
|
||
// one-line angle, rendered by pagerender.js, served at /p/<slug> on the app host and every link domain. Leads from
|
||
// our own capture form belong to the member (their list, exportable). Provider forms go through parse-or-refuse.
|
||
'use strict';
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
const crypto = require('crypto');
|
||
const https = require('https');
|
||
const http = require('http');
|
||
const dns = require('dns').promises;
|
||
const net = require('net');
|
||
const render = require('./pagerender');
|
||
const style = require('./pagestyle');
|
||
const formrestyle = require('./formrestyle');
|
||
|
||
let DATA_DIR = null, ownHosts = () => [], keyFn = () => '', imageBase = () => '';
|
||
const J = { db: null, FILE: () => path.join(DATA_DIR, 'pages.json'),
|
||
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, pages: [], leads: [], views: [], images: [] }; } for (const k of ['pages', 'leads', 'views', 'images']) if (!Array.isArray(this.db[k])) this.db[k] = []; },
|
||
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} } };
|
||
function init(opts) { DATA_DIR = opts.dataDir; ownHosts = opts.ownHosts || (() => []); keyFn = opts.openrouterKey || (() => ''); imageBase = opts.imageBase || (() => ''); J.load(); }
|
||
const norm = e => String(e || '').trim().toLowerCase();
|
||
const TYPES = ['bridge', 'review', 'squeeze'];
|
||
const cleanUrl = u => { const s = String(u || '').trim(); if (/^[/]u[/]pages[/][a-z0-9]+[/][a-z0-9]+[.](png|jpe?g|webp|gif)$/i.test(s)) return s; return /^https?:\/\/[^\s"'<>]+$/i.test(s) && s.length <= 700 ? s : ''; };
|
||
// people type bare domains ("cryptoteambuild.com"): give them the scheme before judging the address (Marty 2026-10-07)
|
||
const withScheme = u => { const s = String(u || '').trim(); return s && !/^[a-z][a-z0-9+.-]*:\/\//i.test(s) && /^[^\s\/]+\.[^\s]+/.test(s) ? 'https://' + s : s; };
|
||
const slugify = t => (String(t || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'page') + '-' + crypto.randomBytes(3).toString('hex');
|
||
const strs = (arr, n, len) => (Array.isArray(arr) ? arr : String(arr || '').split('\n')).map(x => String(x).trim()).filter(Boolean).slice(0, n).map(x => x.slice(0, len));
|
||
|
||
function pub(p) {
|
||
const views = J.db.views.filter(v => v.p === p.id); const leads = J.db.leads.filter(l => l.p === p.id).length;
|
||
return { id: p.id, slug: p.slug, type: p.type, title: p.title, status: p.status, design: p.design, content: p.content, scan: p.scan || null, angle: p.angle || '', created: p.created, updated: p.updated, views: views.length, uniques: new Set(views.map(v => v.v)).size, clicks: views.filter(v => v.k === 'cta').length, leads,
|
||
formProvider: p.type === 'squeeze' && p.content && p.content.formEmbed ? formrestyle.provider(p.content.formEmbed) : null };
|
||
}
|
||
async function list(owner) { return J.db.pages.filter(p => p.owner === norm(owner)).sort((a, b) => b.updated - a.updated).map(pub); }
|
||
async function get(owner, id) { const p = J.db.pages.find(p => p.id === String(id) && p.owner === norm(owner)); return p ? pub(p) : null; }
|
||
function bySlug(slug) { return J.db.pages.find(p => p.slug === String(slug || '').toLowerCase()) || null; }
|
||
function sanitizeContent(c, type) {
|
||
c = c || {}; const out = {};
|
||
out.eyebrow = String(c.eyebrow || '').slice(0, 80); out.headline = String(c.headline || '').slice(0, 160); out.sub = String(c.sub || '').slice(0, 300);
|
||
out.body = String(c.body || '').slice(0, 8000); out.bullets = strs(c.bullets, 8, 160);
|
||
out.cta = { text: String(c.cta && c.cta.text || '').slice(0, 60), url: cleanUrl(c.cta && c.cta.url) };
|
||
out.image = cleanUrl(c.image); out.imageAlt = String(c.imageAlt || '').slice(0, 120);
|
||
out.privacy = String(c.privacy || '').slice(0, 200); out.disclaimer = String(c.disclaimer || '').slice(0, 300);
|
||
out.price = String(c.price || '').slice(0, 24); // optional '$17' chip on the split visual
|
||
if (type === 'review') { out.rating = Math.max(0, Math.min(5, Number(c.rating) || 0)); out.pros = strs(c.pros, 6, 140); out.cons = strs(c.cons, 6, 140); out.verdict = String(c.verdict || '').slice(0, 400); }
|
||
if (type === 'bridge') { out.bonus = String(c.bonus || '').slice(0, 2000); out.bonusTitle = String(c.bonusTitle || '').slice(0, 100); }
|
||
if (type === 'squeeze') { out.formEmbed = String(c.formEmbed || '').slice(0, formrestyle.EMBED_MAX_CHARS); }
|
||
return out;
|
||
}
|
||
// the three knobs + niche; a niche preset sets design + palette unless the body overrides them (a preset is a start, not a lock)
|
||
function designFrom(body, cur) {
|
||
cur = cur || {}; const niche = body.niche != null ? style.nicheKey(body.niche) : (cur.niche || ''); const preset = niche ? style.NICHES[niche] : null;
|
||
const palette = body.palette != null ? style.paletteKey(body.palette) : (body.niche != null && preset ? preset.palette : style.paletteKey(cur.palette));
|
||
const design = body.design != null ? style.designKey(body.design) : (body.niche != null && preset ? preset.design : style.designKey(cur.design));
|
||
const layout = body.layout != null ? style.layoutKey(body.layout) : style.layoutKey(cur.layout || (body.niche != null && preset ? 'split' : 'stack'));
|
||
const hero = body.niche != null && body.niche !== cur.niche ? 0 : style.heroIndex(niche, body.hero != null ? body.hero : cur.hero);
|
||
return { palette, design, layout, niche, hero };
|
||
}
|
||
async function create(owner, body) {
|
||
if (J.db.pages.filter(p => p.owner === norm(owner)).length >= 200) return { error: 'That is a lot of pages. Remove some first.' };
|
||
const type = TYPES.includes(body.type) ? body.type : 'bridge';
|
||
const title = String(body.title || (body.content && body.content.headline) || 'Untitled page').trim().slice(0, 100);
|
||
const content = sanitizeContent(body.content, type);
|
||
if (type === 'squeeze' && content.formEmbed) { const why = formrestyle.problem(content.formEmbed); if (why) return { error: why }; }
|
||
const p = { id: crypto.randomBytes(5).toString('hex'), owner: norm(owner), slug: slugify(title), type, title, status: 'draft', design: designFrom(body, null), content, scan: body.scan && typeof body.scan === 'object' ? { url: cleanUrl(body.scan.url), title: String(body.scan.title || '').slice(0, 200), description: String(body.scan.description || '').slice(0, 300), h1: String(body.scan.h1 || '').slice(0, 200), image: cleanUrl(body.scan.image), headings: strs(body.scan.headings, 8, 120), bullets: strs(body.scan.bullets, 8, 140) } : null, angle: String(body.angle || '').slice(0, 160), created: Date.now(), updated: Date.now() };
|
||
J.db.pages.push(p); J.save(); return { ok: true, page: pub(p) };
|
||
}
|
||
async function update(owner, id, body) {
|
||
const p = J.db.pages.find(p => p.id === String(id) && p.owner === norm(owner)); if (!p) return { error: 'No such page.' };
|
||
if (body.remove) { J.db.pages = J.db.pages.filter(x => x !== p); J.save(); return { ok: true, removed: true }; }
|
||
if (body.title != null) p.title = String(body.title).trim().slice(0, 100) || p.title;
|
||
if (body.type != null && TYPES.includes(body.type)) p.type = body.type;
|
||
if (body.palette != null || body.design != null || body.layout != null || body.niche != null || body.hero != null) p.design = designFrom(body, p.design || {});
|
||
if (body.angle != null) p.angle = String(body.angle).slice(0, 160);
|
||
if (body.content != null) { const c = sanitizeContent(Object.assign({}, p.content, body.content), p.type); if (p.type === 'squeeze' && c.formEmbed) { const why = formrestyle.problem(c.formEmbed); if (why) return { error: why }; } p.content = c; }
|
||
if (body.status != null) { if (body.status === 'published') { if (!p.content.headline) return { error: 'Give the page a headline before publishing.' }; if (p.type !== 'squeeze' && !p.content.cta.url) return { error: 'Add the button link (where the page sends people) before publishing.' }; p.status = 'published'; } else p.status = 'draft'; }
|
||
p.updated = Date.now(); J.save(); return { ok: true, page: pub(p) };
|
||
}
|
||
// -- serving
|
||
function html(p, opts) { return render.render(p, opts); }
|
||
function view(p, req, kind) {
|
||
const ua = String(req.headers['user-agent'] || ''); const bot = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i.test(ua) || !ua;
|
||
const ip = String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
|
||
const v = crypto.createHash('sha256').update(new Date().toISOString().slice(0, 10) + '|' + ip + '|' + ua).digest('hex').slice(0, 16);
|
||
if (!bot) { J.db.views.push({ p: p.id, ts: Date.now(), v, k: kind || 'view' }); if (J.db.views.length > 200000) J.db.views = J.db.views.slice(-150000); J.save(); }
|
||
}
|
||
// -- leads (our own capture form): the member's list
|
||
async function lead(slug, body, req) {
|
||
const p = bySlug(slug); if (!p || p.status !== 'published') return { error: 'That page is not live.' };
|
||
if (String(body.website || '').trim()) return { ok: true, next: p.content.cta.url || '/' }; // honeypot filled: pretend, never store
|
||
const email = norm(body.email); if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return { error: 'That email address does not look right.' };
|
||
const name = String(body.name || '').trim().slice(0, 60); const lsid = /^[a-z0-9]{6,20}$/i.test(String(body.lsid || '')) ? String(body.lsid) : '';
|
||
const ip = String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
|
||
if (!J.db.leads.some(l => l.p === p.id && l.email === email)) { J.db.leads.push({ p: p.id, owner: p.owner, email, name, ts: Date.now(), lsid, ip: crypto.createHash('sha256').update(ip).digest('hex').slice(0, 12) }); J.save(); }
|
||
return { ok: true, next: p.content.cta.url || '/', owner: p.owner, lsid, pageId: p.id };
|
||
}
|
||
async function leads(owner, id) { const p = id ? J.db.pages.find(p => p.id === String(id) && p.owner === norm(owner)) : null; return J.db.leads.filter(l => l.owner === norm(owner) && (!id || l.p === (p && p.id))).sort((a, b) => b.ts - a.ts).map(l => ({ page: (J.db.pages.find(p => p.id === l.p) || {}).title || '', email: l.email, name: l.name, ts: l.ts, lsid: l.lsid })); }
|
||
function csv(rows) { const q = s => '"' + String(s == null ? '' : s).replace(/"/g, '""') + '"'; return ['page,email,name,when'].concat(rows.map(r => [r.page, r.email, r.name, new Date(r.ts).toISOString()].map(q).join(','))).join('\r\n') + '\r\n'; }
|
||
// -- the URL scanner: what the destination says about itself (public hosts only, small, quick)
|
||
function isPrivateIp(ip) { if (net.isIPv4(ip)) { const p = ip.split('.').map(Number); return p[0] === 10 || p[0] === 127 || p[0] === 0 || (p[0] === 169 && p[1] === 254) || (p[0] === 172 && p[1] >= 16 && p[1] <= 31) || (p[0] === 192 && p[1] === 168); } return true; }
|
||
function fetchText(url, hops) {
|
||
return new Promise((resolve, reject) => {
|
||
let u; try { u = new URL(url); } catch (e) { return reject(new Error('bad url')); }
|
||
const mod = u.protocol === 'https:' ? https : http;
|
||
const req = mod.get(u, { headers: { 'User-Agent': 'Mozilla/5.0 (compatible; LinkSpinScanner/1.0)', Accept: 'text/html,*/*' }, timeout: 8000 }, res => {
|
||
if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location && (hops || 0) < 3) { res.resume(); return resolve(fetchText(new URL(res.headers.location, u).toString(), (hops || 0) + 1)); }
|
||
let d = ''; res.setEncoding('utf8'); res.on('data', c => { d += c; if (d.length > 600000) { req.destroy(); resolve({ status: res.statusCode, body: d, url: u.toString() }); } }); res.on('end', () => resolve({ status: res.statusCode, body: d, url: u.toString() }));
|
||
});
|
||
req.on('timeout', () => req.destroy(new Error('timeout'))); req.on('error', reject);
|
||
});
|
||
}
|
||
const meta = (h, name) => { const m = h.match(new RegExp('<meta[^>]+(?:property|name)=["\']' + name + '["\'][^>]*content=["\']([^"\']*)', 'i')) || h.match(new RegExp('<meta[^>]+content=["\']([^"\']*)["\'][^>]*(?:property|name)=["\']' + name + '["\']', 'i')); return m ? m[1].trim() : ''; };
|
||
const strip = s => String(s || '').replace(/<[^>]+>/g, ' ').replace(/ /g, ' ').replace(/&/g, '&').replace(/'|'/g, "'").replace(/"/g, '"').replace(/\s+/g, ' ').trim();
|
||
async function scan(url) {
|
||
url = cleanUrl(withScheme(url)); if (!url) return { error: 'Give the scanner a website address, like example.com or https://example.com/page.' };
|
||
const host = new URL(url).hostname.toLowerCase();
|
||
if (!host.includes('.') || net.isIP(host)) return { error: 'Scan a public website address.' };
|
||
try { const rs = await dns.lookup(host, { all: true }); if (!rs.length || rs.some(r => isPrivateIp(r.address))) return { error: 'That host is not reachable from here.' }; } catch (e) { return { error: 'That host does not resolve.' }; }
|
||
let r; try { r = await fetchText(url); } catch (e) { return { error: 'Could not fetch that page (' + e.message + ').' }; }
|
||
const h = r.body || '';
|
||
const title = strip(meta(h, 'og:title') || (h.match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1] || '');
|
||
const desc = strip(meta(h, 'og:description') || meta(h, 'description'));
|
||
const h1 = strip((h.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i) || [])[1] || '');
|
||
const image = cleanUrl(meta(h, 'og:image')); const color = (meta(h, 'theme-color') || '').slice(0, 9);
|
||
const heads = []; const re = /<h[23][^>]*>([\s\S]*?)<\/h[23]>/gi; let m; while ((m = re.exec(h)) && heads.length < 8) { const t = strip(m[1]); if (t && t.length < 120) heads.push(t); }
|
||
const lis = []; const re2 = /<li[^>]*>([\s\S]*?)<\/li>/gi; while ((m = re2.exec(h)) && lis.length < 12) { const t = strip(m[1]); if (t && t.length > 12 && t.length < 140) lis.push(t); }
|
||
return { ok: true, scan: { url: r.url, status: r.status, title: title.slice(0, 200), description: desc.slice(0, 300), h1: h1.slice(0, 200), image, color, headings: heads, bullets: lis.slice(0, 8), scannedAt: Date.now() } };
|
||
}
|
||
// -- copy: from the scan + angle, by the model when a key exists, else a plain template
|
||
// "Brand | Tagline" page titles: the brand names the site, the tagline is the headline. Separators: | — – - · : ::
|
||
function splitTitle(title, url) {
|
||
const t = String(title || '').trim(); if (!t) return { brand: '', tagline: '' };
|
||
const GENERIC = /^(home|homepage|welcome|index|official site|official website|main page|start)$/i;
|
||
const parts = t.split(/\s+[|\u2014\u2013\-\u00b7]+\s+|\s*\|\s*|:\s+/).map(x => x.trim()).filter(x => x && !GENERIC.test(x));
|
||
if (parts.length === 1) return { brand: parts[0], tagline: '' };
|
||
if (parts.length < 2) return { brand: t, tagline: '' };
|
||
let host = ''; try { host = new URL(url || '').hostname.replace(/^www\./, '').toLowerCase(); } catch (e) {}
|
||
const bare = host.replace(/\.[a-z]+$/, '');
|
||
const looksBrand = x => { const l = x.toLowerCase().replace(/\s+/g, ''); return !!host && (l === host || l === bare || l.includes(host) || (bare.length > 3 && l.includes(bare))); };
|
||
let brand = parts.find(looksBrand) || parts.slice().sort((a, b) => a.length - b.length)[0];
|
||
const rest = parts.filter(x => x !== brand);
|
||
return { brand, tagline: rest.slice().sort((a, b) => b.length - a.length)[0] || '' };
|
||
}
|
||
function templateCopy(type, scanRes, angle, cta) {
|
||
const s = Object.assign({ bullets: [], headings: [] }, scanRes || {}); const a = String(angle || '').trim();
|
||
const st = splitTitle(s.title, s.url); const name = st.brand || s.h1 || 'this page';
|
||
const head = st.tagline || s.h1 || name;
|
||
const base = { eyebrow: type === 'review' ? 'An honest look' : 'Before you click through', headline: a || (type === 'squeeze' ? 'Get the details on ' + name : head), sub: s.description || '', bullets: (s.bullets || []).slice(0, 5), cta: { text: type === 'squeeze' ? 'Send me the details' : 'Take a look', url: cta || s.url || '' }, image: s.image || '', body: '' };
|
||
if (type === 'review') Object.assign(base, { rating: 4, pros: (s.bullets || []).slice(0, 3), cons: ['Results depend on the work you put in'], verdict: 'Worth a look if ' + (a || 'this fits what you are already doing') + '.' });
|
||
if (type === 'bridge') base.body = (a ? a + '\n\n' : '') + (s.description ? s.description + '\n\n' : '') + 'I am sending you to ' + name + ' because it does what it says. Take a look, then decide.';
|
||
return base;
|
||
}
|
||
function llm(messages) {
|
||
const key = keyFn(); if (!key) return Promise.reject(new Error('nokey'));
|
||
return new Promise((resolve, reject) => {
|
||
const data = JSON.stringify({ model: 'deepseek/deepseek-chat', temperature: 0.7, max_tokens: 1400, messages });
|
||
const req = https.request({ hostname: 'openrouter.ai', path: '/api/v1/chat/completions', method: 'POST', headers: { Authorization: 'Bearer ' + key, 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) }, timeout: 60000 }, res => { let d = ''; res.on('data', c => d += c); res.on('end', () => { try { const j = JSON.parse(d); resolve(String(j.choices[0].message.content || '')); } catch (e) { reject(new Error('openrouter ' + res.statusCode)); } }); });
|
||
req.on('timeout', () => req.destroy(new Error('timeout'))); req.on('error', reject); req.write(data); req.end();
|
||
});
|
||
}
|
||
async function write(owner, id, body) {
|
||
const p = J.db.pages.find(p => p.id === String(id) && p.owner === norm(owner)); if (!p) return { error: 'No such page.' };
|
||
const s = p.scan || {}; const angle = String(body.angle != null ? body.angle : p.angle || '').slice(0, 160); const cta = cleanUrl(body.cta || (p.content.cta && p.content.cta.url) || s.url);
|
||
let content = templateCopy(p.type, s, angle, cta), by = 'template';
|
||
try {
|
||
const ask = 'Write a ' + p.type + ' page for an internet marketer. Facts about the destination: ' + JSON.stringify({ site: splitTitle(s.title, s.url).brand || s.title, tagline: splitTitle(s.title, s.url).tagline || undefined, description: s.description, headline: s.h1, points: s.bullets, headings: s.headings }).slice(0, 2500) + '. Angle in the marketer\'s words: "' + angle + '". Rules: plain, specific, no hype, no income promises, no em dashes, US English, first person. Return ONLY JSON with keys: eyebrow (<=60 chars), headline (<=90), sub (<=200), bullets (3-5 short strings), body (2-4 short paragraphs separated by blank lines, or empty for squeeze)' + (p.type === 'review' ? ', rating (1-5), pros (3), cons (2), verdict (<=200)' : '') + (p.type === 'bridge' ? ', bonusTitle, bonus (one short paragraph or empty)' : '') + ', ctaText (<=40).';
|
||
const txt = await llm([{ role: 'system', content: 'You write short, honest marketing pages. Output JSON only.' }, { role: 'user', content: ask }]);
|
||
const j = JSON.parse((txt.match(/\{[\s\S]*\}/) || ['{}'])[0]);
|
||
if (j.headline) { content = Object.assign(content, { eyebrow: j.eyebrow, headline: j.headline, sub: j.sub, bullets: strs(j.bullets, 6, 160), body: j.body || '', rating: j.rating, pros: strs(j.pros, 6, 140), cons: strs(j.cons, 6, 140), verdict: j.verdict, bonusTitle: j.bonusTitle, bonus: j.bonus, cta: { text: j.ctaText || content.cta.text, url: cta } }); by = 'model'; }
|
||
} catch (e) { if (e.message !== 'nokey') console.error('pages write', e.message); }
|
||
p.content = sanitizeContent(Object.assign({}, p.content, content, { formEmbed: p.content.formEmbed }), p.type); p.angle = angle; p.updated = Date.now(); J.save();
|
||
return { ok: true, page: pub(p), by };
|
||
}
|
||
function totals() { return { pages: J.db.pages.length, published: J.db.pages.filter(p => p.status === 'published').length, leads: J.db.leads.length }; }
|
||
// -- Reports (2026-10-10): the member's page views, uniques, clicks-through and leads for the last N days, by Central day and by page
|
||
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||
async function summary(owner, days) {
|
||
const mine = J.db.pages.filter(p => p.owner === norm(owner)); const ids = new Set(mine.map(p => p.id));
|
||
const since = Date.now() - (Number(days) || 30) * 86400000;
|
||
const views = J.db.views.filter(v => ids.has(v.p) && v.ts >= since); const leads = J.db.leads.filter(l => l.owner === norm(owner) && l.ts >= since);
|
||
const shows = views.filter(v => v.k !== 'cta'), clicks = views.filter(v => v.k === 'cta');
|
||
const dayMap = {}; const dayOf = k => dayMap[k] = dayMap[k] || { day: k, views: 0, u: new Set(), clicks: 0, leads: 0 };
|
||
for (const v of shows) { const d = dayOf(ctDay(v.ts)); d.views++; d.u.add(v.v); } for (const v of clicks) dayOf(ctDay(v.ts)).clicks++; for (const l of leads) dayOf(ctDay(l.ts)).leads++;
|
||
const byDay = Object.values(dayMap).sort((a, b) => a.day < b.day ? -1 : 1).map(d => ({ day: d.day, views: d.views, u: d.u.size, clicks: d.clicks, leads: d.leads }));
|
||
const byPage = mine.map(p => { const vs = shows.filter(v => v.p === p.id); return { id: p.id, title: p.title, slug: p.slug, type: p.type, status: p.status, views: vs.length, uniques: new Set(vs.map(v => v.v)).size, clicks: clicks.filter(v => v.p === p.id).length, leads: leads.filter(l => l.p === p.id).length }; }).sort((a, b) => b.views - a.views);
|
||
return { pages: mine.length, live: mine.filter(p => p.status === 'published').length, views: shows.length, uniques: new Set(shows.map(v => v.v)).size, clicks: clicks.length, leads: leads.length, byDay, byPage };
|
||
}
|
||
// -- hosted images (2026-10-10): png/jpg/webp up to 2 MB, 50 per member, stored under DATA_DIR/uploads/pages/<owner-hash>/<id>.<ext>
|
||
// and served at /u/pages/<owner-hash>/<id>.<ext>. Re-encoded with sharp when that module is installed (it is not a
|
||
// dependency today), otherwise magic bytes + size are checked and the file is stored as it came.
|
||
const IMG_MAX = 50, IMG_BYTES = 2 * 1024 * 1024;
|
||
const IMG_EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' };
|
||
const ownerHash = o => crypto.createHash('sha256').update(norm(o)).digest('hex').slice(0, 16);
|
||
const imgDir = o => path.join(DATA_DIR, 'uploads', 'pages', ownerHash(o));
|
||
let sharp = null; try { sharp = require('sharp'); } catch (e) { sharp = null; }
|
||
function sniff(buf) {
|
||
if (buf.length > 16 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) return 'image/png';
|
||
if (buf.length > 16 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'image/jpeg';
|
||
if (buf.length > 16 && buf.slice(0, 4).toString() === 'RIFF' && buf.slice(8, 12).toString() === 'WEBP') return 'image/webp';
|
||
return null;
|
||
}
|
||
// the request body as { buf, ct }: a raw image body, multipart/form-data (first file part), or JSON { data: <base64 or data: URL> }
|
||
function readUpload(req) {
|
||
return new Promise((resolve) => {
|
||
const ct = String(req.headers['content-type'] || '').toLowerCase(); const chunks = []; let n = 0; let done = false;
|
||
const fail = msg => { if (!done) { done = true; resolve({ error: msg }); } };
|
||
req.on('data', c => { n += c.length; if (n > IMG_BYTES * 1.4 + 4096) { req.destroy(); return fail('That image is over 2 MB. Make it smaller and try again.'); } chunks.push(c); });
|
||
req.on('error', () => fail('Upload interrupted.'));
|
||
req.on('end', () => {
|
||
if (done) return; done = true; const raw = Buffer.concat(chunks);
|
||
try {
|
||
if (ct.startsWith('multipart/form-data')) {
|
||
const bm = /boundary=("?)([^";]+)\1/i.exec(ct); if (!bm) return resolve({ error: 'Bad multipart body.' });
|
||
const boundary = Buffer.from('--' + bm[2]); let pos = raw.indexOf(boundary);
|
||
while (pos !== -1) {
|
||
const hs = pos + boundary.length + 2; const he = raw.indexOf('\r\n\r\n', hs); if (he === -1) break;
|
||
const head = raw.slice(hs, he).toString('latin1'); const next = raw.indexOf(boundary, he + 4); if (next === -1) break;
|
||
const body = raw.slice(he + 4, next - 2); // strip the CRLF before the next boundary
|
||
if (/filename=/i.test(head)) { const cm = /content-type:\s*([^\r\n;]+)/i.exec(head); return resolve({ buf: body, ct: cm ? cm[1].trim().toLowerCase() : (sniff(body) || '') }); }
|
||
pos = next;
|
||
}
|
||
return resolve({ error: 'No file in the upload.' });
|
||
}
|
||
if (ct.startsWith('application/json')) {
|
||
const j = JSON.parse(raw.toString('utf8') || '{}'); let data = String(j.data || j.image || ''); let mime = String(j.type || '').toLowerCase();
|
||
const dm = /^data:([a-z0-9.+\/-]+);base64,/i.exec(data); if (dm) { mime = dm[1].toLowerCase(); data = data.slice(dm[0].length); }
|
||
const buf = Buffer.from(data.replace(/\s+/g, ''), 'base64'); return resolve({ buf, ct: mime || sniff(buf) || '' });
|
||
}
|
||
return resolve({ buf: raw, ct: ct.split(';')[0].trim() });
|
||
} catch (e) { resolve({ error: 'Could not read the upload.' }); }
|
||
});
|
||
});
|
||
}
|
||
async function uploadImage(owner, buf, ct) {
|
||
if (!buf || !buf.length) return { error: 'No image data arrived.' };
|
||
if (buf.length > IMG_BYTES) return { error: 'That image is over 2 MB. Make it smaller and try again.' };
|
||
const real = sniff(buf); if (!real || !IMG_EXT[real]) return { error: 'Use a PNG, JPG or WebP image.' };
|
||
if (ct && IMG_EXT[ct] && ct !== real) return { error: 'That file does not look like a real ' + IMG_EXT[ct].toUpperCase() + '.' };
|
||
if (J.db.images.filter(i => i.owner === norm(owner)).length >= IMG_MAX) return { error: 'You have ' + IMG_MAX + ' images already. Delete one first.' };
|
||
let out = buf, mime = real;
|
||
if (sharp) { try { const img = sharp(buf, { failOn: 'error' }).rotate().resize({ width: 2000, height: 2000, fit: 'inside', withoutEnlargement: true }); out = mime === 'image/png' ? await img.png({ compressionLevel: 9 }).toBuffer() : mime === 'image/webp' ? await img.webp({ quality: 85 }).toBuffer() : await img.jpeg({ quality: 85, mozjpeg: true }).toBuffer(); } catch (e) { return { error: 'That image could not be read.' }; } }
|
||
const id = crypto.randomBytes(6).toString('hex'); const ext = IMG_EXT[mime]; const dir = imgDir(owner);
|
||
fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, id + '.' + ext), out);
|
||
const rec = { id, owner: norm(owner), h: ownerHash(owner), ext, mime, size: out.length, ts: Date.now() };
|
||
J.db.images.push(rec); J.save(); return { ok: true, image: pubImage(rec) };
|
||
}
|
||
function pubImage(i) { return { id: i.id, url: imageBase() + '/u/pages/' + i.h + '/' + i.id + '.' + i.ext, path: '/u/pages/' + i.h + '/' + i.id + '.' + i.ext, size: i.size, ts: i.ts, type: i.mime }; }
|
||
async function images(owner) { return J.db.images.filter(i => i.owner === norm(owner)).sort((a, b) => b.ts - a.ts).map(pubImage); }
|
||
async function removeImage(owner, id) {
|
||
const i = J.db.images.find(x => x.id === String(id) && x.owner === norm(owner)); if (!i) return { error: 'No such image.' };
|
||
try { fs.unlinkSync(path.join(imgDir(owner), i.id + '.' + i.ext)); } catch (e) {}
|
||
J.db.images = J.db.images.filter(x => x !== i); J.save(); return { ok: true, images: await images(owner) };
|
||
}
|
||
// the file behind /u/pages/<hash>/<id>.<ext>, only when the index knows it (never a raw directory read)
|
||
function imageFile(hash, id, ext) { const i = J.db.images.find(x => x.h === String(hash) && x.id === String(id) && x.ext === String(ext)); return i ? { file: path.join(DATA_DIR, 'uploads', 'pages', i.h, i.id + '.' + i.ext), mime: i.mime } : null; }
|
||
module.exports = { init, TYPES, list, get, bySlug, create, update, html, view, lead, leads, csv, scan, write, totals, summary, readUpload, uploadImage, images, removeImage, imageFile, IMG_MAX, IMG_BYTES, providers: () => formrestyle.PROVIDERS, provider: formrestyle.provider };
|