Zones guardrails: origin lock to the declared site, warm-up then earning, hold under 40% viewable, admin Zones pane with pause

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-09-29 17:38:08 -05:00
parent e36b590788
commit cfb9ed13d0
5 changed files with 79 additions and 18 deletions
+9 -1
View File
@@ -98,6 +98,7 @@
<button data-pane="members" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="7" r="3.2"/><circle cx="5" cy="17" r="2.6"/><circle cx="19" cy="17" r="2.6"/><path d="M12 10v3M12 13l-5 2M12 13l5 2"/></svg>Members</button>
<button data-pane="reports" type="button"><svg viewBox="0 0 24 24"><path d="M12 3l9 16H3z"/><path d="M12 10v4M12 17v.5"/></svg>Reports<span class="pill" id="repBadge" hidden></span></button>
<button data-pane="traffic" type="button"><svg viewBox="0 0 24 24"><path d="M3 17l6-6 4 4 8-8"/><path d="M14 7h7v7"/></svg>Traffic</button>
<button data-pane="zones" type="button"><svg viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18M8 15h8"/></svg>Zones</button>
<button data-pane="blog" type="button"><svg viewBox="0 0 24 24"><path d="M4 4h12l4 4v12H4z"/><path d="M8 12h8M8 16h8M8 8h4"/></svg>Blog</button>
<button data-pane="releases" type="button"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h10M4 18h7"/><circle cx="18" cy="17" r="3"/></svg>Releases</button>
<button data-pane="pnl" type="button"><svg viewBox="0 0 24 24"><path d="M4 19V5M4 19h16"/><path d="M8 15l3-4 3 2 5-6"/></svg>P&amp;L</button>
@@ -286,6 +287,13 @@
</div>
</div>
<div class="pane" id="pane-zones" hidden>
<div class="card">
<div class="card-head"><h3>Member zones</h3><span class="sub" id="znSub"></span></div>
<p class="muted small" style="margin:0 0 10px" id="znRules"></p>
<p style="margin:0 0 6px;display:flex;gap:8px;align-items:center"><input class="tfilter small" data-for="znTable" placeholder="Filter zones" style="max-width:260px"><span class="tfilter-count muted small"></span></p><div class="tablewrap"><table class="adm-table" id="znTable"></table></div>
</div>
</div>
<div class="pane" id="pane-traffic" hidden>
<div class="card">
<div class="card-head"><h3>Where visitors come from</h3><span class="sub" id="trfSub"></span></div>
@@ -487,6 +495,6 @@
</div>
<script src="/assets/common.js?v=ls20260916a"></script>
<script src="/assets/admin.js?v=20260915a"></script>
<script src="/assets/admin.js?v=20260929a"></script>
</body>
</html>
+17 -2
View File
@@ -44,8 +44,8 @@
});
// ── panes ──
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', settings: 'Settings' };
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, settings: loadSettings };
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', reports: 'Reports', zones: 'Zones', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', settings: 'Settings' };
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, reports: loadReports, zones: loadZones, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, settings: loadSettings };
function setPane(name) {
if (!TITLES[name]) name = 'overview';
document.querySelectorAll('.pane').forEach(p => { p.hidden = p.id !== 'pane-' + name; });
@@ -473,6 +473,21 @@
let pnlDays = 30;
const pol = w => { try { return (Number(BigInt(w || '0') / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }); } catch (e) { return '0'; } };
const usdOf = (w, px) => { try { return '$' + ((Number(BigInt(w || '0') / 10n ** 14n) / 10000) * px).toLocaleString(undefined, { maximumFractionDigits: 0 }); } catch (e) { return '$0'; } };
// ── zones: every member ad slot, its site, mix and earning status; pause = house banner only (2026-09-29) ──
async function loadZones() {
const d = await (await fetch('/api/admin/zones')).json();
if (d.error) throw new Error(d.error);
const n = v => Number(v || 0).toLocaleString();
$('znSub').textContent = n(d.totals.zones) + ' zones · ' + n(d.totals.views30) + ' views in 30 days · ' + n(d.totals.nas30) + ' network · ' + n(d.totals.credits) + ' credits paid';
$('znRules').textContent = 'Paid ads (LinkSpin campaigns, then Network Ad Space) serve only when the tag runs on the declared site; anywhere else shows the house banner and earns nothing. A zone earns after its first ' + d.warmup + ' on-site views with at least ' + Math.round(d.holdRatio * 100) + '% viewable, and goes on hold below that. Rates: 1 credit per ' + d.rates.viewsPerCredit + ' LinkSpin views, 1 per ' + d.rates.nasViewsPerCredit + ' network views, ' + d.rates.capPerVisitorDay + ' credited views per visitor per zone per day. Pause a zone to serve house only (brand safety).';
const ago = t => t ? new Date(t).toLocaleString() : '';
$('znTable').innerHTML = '<tr><th>Zone</th><th>Owner</th><th>Site</th><th>Size</th><th>Views</th><th>Viewable</th><th>Mix<br><span class="muted">LinkSpin / network / house / off-site</span></th><th>Clicks</th><th>Credits</th><th>Status</th><th>Last view</th><th></th></tr>'
+ (d.zones.length ? d.zones.map(z => '<tr><td><b>' + esc(z.name) + '</b><br><span class="muted small">' + z.id + '</span></td><td>' + esc(z.owner) + '</td><td><a href="https://' + esc(z.site) + '" target="_blank" rel="noopener">' + esc(z.site) + '</a></td><td>' + z.size + '</td><td>' + n(z.views30) + '</td><td>' + (z.viewablePct == null ? '<span class="muted">-</span>' : z.viewablePct + '% ' + (z.grade || '')) + '</td><td>' + n(z.campaign30) + ' / ' + n(z.nas30) + ' / ' + n(z.house30) + ' / ' + n(z.offsite30) + '</td><td>' + n(z.clicks30) + '</td><td>' + n(z.credits) + '</td><td>' + esc(z.statusLabel) + (z.note ? '<br><span class="muted small">' + esc(z.note) + '</span>' : '') + '</td><td>' + ago(z.lastSeen) + '</td><td class="act"><button type="button" class="btn small ghost" data-znpause="' + z.id + '" data-on="' + (z.paused ? 0 : 1) + '">' + (z.paused ? 'Resume' : 'Pause') + '</button></td></tr>').join('') : '<tr><td colspan="12" class="muted">No zones yet.</td></tr>');
document.querySelectorAll('[data-znpause]').forEach(b => b.addEventListener('click', async () => {
const pausing = b.dataset.on === '1';
try { await api('/api/admin/zones/' + b.dataset.znpause, pausing ? { paused: true, note: 'Paused ' + new Date().toLocaleDateString() } : { paused: false, note: '' }, 'POST'); loadZones(); } catch (e) { IAP.status(e.message, 'bad'); }
}));
}
// ── traffic: referring domains / sources, landing pages, angles, by day ──
let trfDays = 30;
document.querySelectorAll('#trfRange [data-days]').forEach(b => b.addEventListener('click', () => { trfDays = Number(b.dataset.days); document.querySelectorAll('#trfRange [data-days]').forEach(x => x.classList.toggle('on', x === b)); loadTraffic().catch(e => IAP.status(e.message, 'bad')); }));
+3 -3
View File
@@ -13,9 +13,9 @@
$('tiles').innerHTML = [['Views served, 30 d', fmt(t.v)], ['Viewable', t.v ? Math.round(t.ok / t.v * 100) + '%' : '0%'], ['Clicks out', fmt(t.k)], ['Credits earned', fmt(t.c)]].map(([k, v], i) => '<div class="tile' + (i === 3 ? ' hi' : '') + '"><span class="k">' + k + '</span><span class="v">' + v + '</span></div>').join('');
$('rateNote').textContent = 'You earn 1 credit per ' + (RATE.viewsPerCredit || 5) + ' viewable views of a LinkSpin campaign and 1 per ' + (RATE.nasViewsPerCredit || 10) + ' viewable views of a network ad, capped at ' + (RATE.capPerVisitorDay || 50) + ' credited views per visitor per zone per day. House banners are not paid. Bots never count.';
const q = g => '<span class="q ' + (g === 'A' ? 'ok' : g === 'B' ? 'warn' : g === 'C' ? 'bad' : 'muted') + '">' + [1, 2, 3, 4, 5].map(i => '<i class="' + (g === 'A' ? (i <= 5 ? 'on' : '') : g === 'B' ? (i <= 3 ? 'on' : '') : g === 'C' ? (i <= 1 ? 'on' : '') : '') + '"></i>').join('') + '</span>' + (g || '');
$('rows').innerHTML = Z.length ? Z.map(z => '<div class="rw' + (z.id === SEL ? ' on' : '') + '"><div><b>' + esc(z.name) + '</b>' + (z.site ? ' <span class="muted">· ' + esc(z.site) + '</span>' : '') + '<br><span class="mono muted" style="font-size:11px">' + z.id + ' · ' + (z.lastSeen ? 'last view ' + ago(z.lastSeen) : 'no views yet') + (z.views30 ? ' · mix: ' + fmt(z.campaign30 || 0) + ' LinkSpin / ' + fmt(z.nas30 || 0) + ' network / ' + fmt(z.house30 || 0) + ' house' : '') + '</span></div><span class="mono">' + z.size + '</span><span class="r num">' + fmt(z.views30) + '</span><span class="r num">' + (z.viewablePct == null ? '<span class="muted">·</span>' : z.viewablePct + '%') + '</span><span class="r num">' + fmt(z.credits) + '</span><span class="mono" style="font-size:11px">' + (z.grade ? q(z.grade) : '<span class="muted">no data</span>') + (!z.active ? ' <span class="tag warn">OFF</span>' : '') + '</span><span style="display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap"><button class="btn sm" type="button" data-tag="' + z.id + '">Tag</button><button class="btn sm" type="button" data-tog="' + z.id + '">' + (z.active ? 'Off' : 'On') + '</button><button class="btn sm danger" type="button" data-del="' + z.id + '" aria-label="Remove">&times;</button></span></div>').join('')
$('rows').innerHTML = Z.length ? Z.map(z => '<div class="rw' + (z.id === SEL ? ' on' : '') + '"><div><b>' + esc(z.name) + '</b>' + (z.site ? ' <span class="muted">· ' + esc(z.site) + '</span>' : '') + '<br><span class="mono muted" style="font-size:11px">' + z.id + ' · ' + (z.lastSeen ? 'last view ' + ago(z.lastSeen) : 'no views yet') + (z.views30 ? ' · mix: ' + fmt(z.campaign30 || 0) + ' LinkSpin / ' + fmt(z.nas30 || 0) + ' network / ' + fmt(z.house30 || 0) + ' house' : '') + '</span></div><span class="mono">' + z.size + '</span><span class="r num">' + fmt(z.views30) + '</span><span class="r num">' + (z.viewablePct == null ? '<span class="muted">·</span>' : z.viewablePct + '%') + '</span><span class="r num">' + fmt(z.credits) + '</span><span class="mono" style="font-size:11px">' + (z.grade ? q(z.grade) : '<span class="muted">no data</span>') + ' <span class="tag ' + (z.status === 'earning' ? 'ok' : z.status === 'warming' ? '' : 'warn') + '">' + esc(z.statusLabel || '') + '</span>' + '</span><span style="display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap"><button class="btn sm" type="button" data-tag="' + z.id + '">Tag</button><button class="btn sm" type="button" data-tog="' + z.id + '">' + (z.active ? 'Off' : 'On') + '</button><button class="btn sm danger" type="button" data-del="' + z.id + '" aria-label="Remove">&times;</button></span></div>').join('')
: '<div class="rw"><span class="muted">No zones yet. Add one, paste the tag on your site, and the banner is live.</span></div>';
$('foot').textContent = 'viewable = at least half the banner on screen for one second, reported by the tag · quality: A 60%+ viewable, B 40%+, C below · network frequency: one credited view per visitor per zone per day up to the cap';
$('foot').textContent = 'viewable = at least half the banner on screen for one second, reported by the tag · quality: A 60%+ viewable, B 40%+, C below · paid ads serve only on the declared site; a zone earns after its first 100 on-site views with 40%+ viewable and goes on hold below that';
$('rows').querySelectorAll('[data-tag]').forEach(b => b.addEventListener('click', () => showTag(b.dataset.tag)));
$('rows').querySelectorAll('[data-tog]').forEach(b => b.addEventListener('click', async () => { const z = Z.find(x => x.id === b.dataset.tog); try { await api('/api/my/zones/' + z.id, { active: !z.active }); load(); } catch (e) { toast(e.message, true); } }));
$('rows').querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', async () => { if (!await dialog({ title: 'Remove this zone?', text: 'The tag on your site stops showing ads. Credits already earned stay.', ok: 'Remove', danger: true })) return; try { await api('/api/my/zones/' + b.dataset.del, { remove: true }); SEL = null; $('tagPanel').hidden = true; load(); } catch (e) { toast(e.message, true); } }));
@@ -23,7 +23,7 @@
}
function showTag(id) { const z = Z.find(x => x.id === id); if (!z) return; SEL = id; $('tagPanel').hidden = false; $('tagTitle').textContent = 'Embed tag · ' + z.name; $('tagCode').textContent = tag(z); $('tagNote').textContent = 'Paste it where the banner should appear (' + z.size + '). It sizes itself and never loads more than one ad.'; $('tagCopy').onclick = () => CR.copy(tag(z)); $('tagCheck').onclick = async () => { await load(); const zz = Z.find(x => x.id === id); toast(zz && zz.lastSeen && Date.now() - zz.lastSeen < 3600e3 ? 'Live: last view ' + ago(zz.lastSeen) : 'No view in the last hour. Is the tag on a page people open?', !(zz && zz.lastSeen && Date.now() - zz.lastSeen < 3600e3)); }; }
$('newBtn').addEventListener('click', async () => {
const v = await dialog({ title: 'Add a zone', text: 'One zone per spot on a page. Pick the size that fits the space.', fields: [{ k: 'name', label: 'Name', placeholder: 'My blog · sidebar', max: 60 }, { k: 'site', label: 'Site it lives on', placeholder: 'myblog.com', max: 80 }, { k: 'size', label: 'Size: ' + (SIZES.join(', ') || '728x90, 468x60, 300x250, 160x600, 320x50'), value: '728x90', mono: true }], ok: 'Create' });
const v = await dialog({ title: 'Add a zone', text: 'One zone per spot on a page. Paid ads only serve on the site you name here; anywhere else the tag shows the house banner.', fields: [{ k: 'name', label: 'Name', placeholder: 'My blog · sidebar', max: 60 }, { k: 'site', label: 'Site it lives on (required)', placeholder: 'myblog.com', max: 80 }, { k: 'size', label: 'Size: ' + (SIZES.join(', ') || '728x90, 468x60, 300x250, 160x600, 320x50'), value: '728x90', mono: true }], ok: 'Create' });
if (!v) return; try { const r = await api('/api/my/zones', v); SEL = r.zone.id; toast('Zone created. Copy the tag.'); load(); } catch (e) { toast(e.message, true); }
});
CR.requireSession(load);
+9
View File
@@ -1861,6 +1861,15 @@ const server = http.createServer(async (req, res) => {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await zones.update(s.email, m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/zones' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
return json(res, 200, { zones: await zones.adminList(), totals: zones.totals(), rates: zones.settings(), warmup: zones.WARMUP, holdRatio: zones.HOLD_RATIO }, { 'Cache-Control': 'no-store' });
}
m = /^\/api\/admin\/zones\/(ls-[a-f0-9]{6})$/.exec(p);
if (m && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
const r = await zones.adminSet(m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/pages' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const hosts = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(x => x && !x.startsWith('www.'));
+41 -12
View File
@@ -22,17 +22,34 @@ const DAY = 86400000;
function settings() { let s = {}; try { s = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'zone-rates.json'), 'utf8')); } catch (e) {} return Object.assign({ viewsPerCredit: 5, nasViewsPerCredit: 10, capPerVisitorDay: 50, houseOn: 1, nasOn: 1 }, s); }
// the document an NAS fallback renders in: our own frame, so the NAS tag's document.write lands in a page we control
function nasFrame(size) { const wh = SIZES[size]; if (!wh || !NAS_SIZES.has(size)) return null; return '<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}body{width:' + wh[0] + 'px;height:' + wh[1] + 'px}img{border:0;display:block}</style></head><body>' + NAS_TAG(wh[0], wh[1]) + '</body></html>'; }
function pubZone(z) {
const since30 = Date.now() - 30 * DAY; const imps = J.db.imps.filter(i => i.z === z.id && i.ts >= since30 && !i.bot);
const seen = imps.filter(i => i.ok).length; const clicks = imps.filter(i => i.k).length; const last = J.db.imps.filter(i => i.z === z.id).slice(-1)[0];
const ratio = imps.length ? seen / imps.length : 0;
return { id: z.id, name: z.name, site: z.site, size: z.size, active: !!z.active, created: z.created, views30: imps.length, viewable30: seen, viewablePct: imps.length ? Math.round(ratio * 100) : null, clicks30: clicks, credits: z.credits || 0, grade: !imps.length ? null : ratio >= 0.6 ? 'A' : ratio >= 0.4 ? 'B' : 'C', lastSeen: last ? last.ts : 0, house30: imps.filter(i => i.house).length, nas30: imps.filter(i => i.nas).length, campaign30: imps.filter(i => i.camp).length };
// Earning status (Marty, 2026-09-29): a zone earns only once its first WARMUP on-site views have landed with at least
// HOLD_RATIO of them viewable; below that it keeps serving but stops earning; an admin pause serves house only.
const WARMUP = 100, HOLD_RATIO = 0.4;
function statusOf(z, imps) {
if (z.adminPaused) return { state: 'paused', label: 'Paused by admin' };
if (!z.active) return { state: 'off', label: 'Off' };
const onSite = imps.filter(i => !i.off); const seen = onSite.filter(i => i.ok).length;
if (onSite.length < WARMUP) return { state: 'warming', label: 'Warming up: ' + onSite.length + '/' + WARMUP + ' views', warm: onSite.length };
if (seen / onSite.length < HOLD_RATIO) return { state: 'hold', label: 'On hold: under ' + Math.round(HOLD_RATIO * 100) + '% viewable' };
return { state: 'earning', label: 'Earning' };
}
function impsOf(z) { const since30 = Date.now() - 30 * DAY; return J.db.imps.filter(i => i.z === z.id && i.ts >= since30 && !i.bot); }
function pubZone(z) {
const imps = impsOf(z);
const seen = imps.filter(i => i.ok).length; const clicks = imps.filter(i => i.k).length; const last = J.db.imps.filter(i => i.z === z.id).slice(-1)[0];
const ratio = imps.length ? seen / imps.length : 0; const st = statusOf(z, imps);
return { id: z.id, name: z.name, site: z.site, size: z.size, active: !!z.active, created: z.created, views30: imps.length, viewable30: seen, viewablePct: imps.length ? Math.round(ratio * 100) : null, clicks30: clicks, credits: z.credits || 0, grade: !imps.length ? null : ratio >= 0.6 ? 'A' : ratio >= 0.4 ? 'B' : 'C', lastSeen: last ? last.ts : 0, house30: imps.filter(i => i.house).length, nas30: imps.filter(i => i.nas).length, campaign30: imps.filter(i => i.camp).length, offsite30: imps.filter(i => i.off).length, status: st.state, statusLabel: st.label, paused: !!z.adminPaused };
}
// the site the tag is running on, from the browser's referrer (cross-origin fetches still send the origin); matches the
// declared site or any subdomain of it
function siteHostOf(req) { try { return new URL(String(req.headers.referer || req.headers.origin || '')).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } }
function onDeclaredSite(z, host) { const s = String(z.site || '').replace(/^www\./, ''); return !!host && !!s && (host === s || host.endsWith('.' + s)); }
async function list(owner) { return J.db.zones.filter(z => z.owner === norm(owner)).map(pubZone); }
async function create(owner, body) {
if (J.db.zones.filter(z => z.owner === norm(owner)).length >= 50) return { error: 'Up to 50 zones per account.' };
const size = SIZES[String(body.size || '')] ? String(body.size) : '728x90';
const name = String(body.name || '').trim().slice(0, 60) || 'Zone'; const site = String(body.site || '').trim().toLowerCase().replace(/^https?:\/\//, '').split('/')[0].slice(0, 80);
const name = String(body.name || '').trim().slice(0, 60) || 'Zone'; const site = String(body.site || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0].split(':')[0].slice(0, 80);
if (!/^[a-z0-9.-]+$/.test(site) || !site.includes('.')) return { error: 'Enter the site the tag will live on, like myblog.com. Paid ads only serve on that site.' };
const z = { id: 'ls-' + crypto.randomBytes(3).toString('hex'), owner: norm(owner), name, site, size, active: true, created: Date.now(), credits: 0 };
J.db.zones.push(z); J.save(); return { ok: true, zone: pubZone(z) };
}
@@ -40,7 +57,7 @@ async function update(owner, id, body) {
const z = J.db.zones.find(z => z.id === id && z.owner === norm(owner)); if (!z) return { error: 'No such zone.' };
if (body.remove) { J.db.zones = J.db.zones.filter(x => x !== z); J.save(); return { ok: true, removed: true }; }
if (body.name != null) z.name = String(body.name).trim().slice(0, 60) || z.name;
if (body.site != null) z.site = String(body.site).trim().toLowerCase().replace(/^https?:\/\//, '').split('/')[0].slice(0, 80);
if (body.site != null) { const site = String(body.site).trim().toLowerCase().replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0].split(':')[0].slice(0, 80); if (!/^[a-z0-9.-]+$/.test(site) || !site.includes('.')) return { error: 'Enter a site like myblog.com.' }; z.site = site; }
if (body.active != null) z.active = !!body.active;
J.save(); return { ok: true, zone: pubZone(z) };
}
@@ -50,12 +67,15 @@ function visitorOf(req) { const ua = String(req.headers['user-agent'] || ''); co
async function serve(zoneId, req, geoOpts) {
const z = J.db.zones.find(z => z.id === String(zoneId)); if (!z || !z.active) return null;
const [w, h] = SIZES[z.size]; const vis = visitorOf(req); const s = settings();
// origin lock: paid inventory (campaigns, network ads) only on the declared site; anywhere else, or with no referrer,
// the tag shows the house banner and nothing is earned. An admin pause does the same.
const off = !onDeclaredSite(z, siteHostOf(req)); const paidOk = !vis.bot && !off && !z.adminPaused;
// waterfall: 1) a LinkSpin member campaign 2) a Network Ad Space ad (NAS serves 728x90 and 468x60) 3) the LinkSpin house banner
let ad = null; if (!vis.bot) { try { ad = await ads.serve('banner', Object.assign({ width: w, height: h, excludeEmail: z.owner }, geoOpts || {})); } catch (e) { ad = null; } }
const nas = !ad && !vis.bot && s.nasOn && NAS_SIZES.has(z.size);
let ad = null; if (paidOk) { try { ad = await ads.serve('banner', Object.assign({ width: w, height: h, excludeEmail: z.owner }, geoOpts || {})); } catch (e) { ad = null; } }
const nas = !ad && paidOk && s.nasOn && NAS_SIZES.has(z.size);
const house = !ad && !nas;
if (house && !s.houseOn) return null;
const imp = { id: crypto.randomBytes(6).toString('hex'), z: z.id, ts: Date.now(), v: vis.v, bot: vis.bot ? 1 : 0, ok: 0, k: 0, house: house ? 1 : 0, nas: nas ? 1 : 0, camp: ad ? ad.id : 0 };
const imp = { id: crypto.randomBytes(6).toString('hex'), z: z.id, ts: Date.now(), v: vis.v, bot: vis.bot ? 1 : 0, ok: 0, k: 0, house: house ? 1 : 0, nas: nas ? 1 : 0, camp: ad ? ad.id : 0, off: off ? 1 : 0 };
J.db.imps.push(imp); if (J.db.imps.length > 300000) J.db.imps = J.db.imps.slice(-200000); J.save();
if (nas) return { imp: imp.id, w, h, kind: 'nas', frame: '/z/nas?s=' + z.size + '&i=' + imp.id, nas: true };
return { imp: imp.id, w, h, kind: house ? 'house' : 'campaign', img: ad ? (ad.image || ad.imageUrl || ad.src || '') : HOUSE[z.size], alt: ad ? (ad.title || 'Advertisement') : 'LinkSpin: one link, every page you promote', click: '/api/zone/click/' + imp.id, house };
@@ -68,7 +88,8 @@ async function seen(impId, req) {
const s = settings(); const day = new Date().toISOString().slice(0, 10);
const todayByVisitor = J.db.imps.filter(i => i.z === z.id && i.v === imp.v && i.ok && new Date(i.ts).toISOString().slice(0, 10) === day).length;
imp.ok = 1;
if (todayByVisitor < s.capPerVisitorDay && !imp.house) { // house views are not paid: nobody bought them
const earning = statusOf(z, impsOf(z)).state === 'earning';
if (earning && todayByVisitor < s.capPerVisitorDay && !imp.house && !imp.off) { // house and off-site views are not paid
// LinkSpin campaign views and NAS views accrue on separate meters with their own rates; whole credits go to the owner
const key = z.owner + (imp.nas ? '|nas' : ''); const per = imp.nas ? s.nasViewsPerCredit : s.viewsPerCredit;
J.db.acc[key] = (J.db.acc[key] || 0) + 1;
@@ -82,5 +103,13 @@ async function click(impId) {
if (imp.house || !imp.camp) return 'https://' + siteHost + '/';
try { return (await ads.click(imp.camp)) || ('https://' + siteHost + '/'); } catch (e) { return 'https://' + siteHost + '/'; }
}
// -- admin: every zone with its owner, site, mix and status; pause/resume
async function adminList() { return J.db.zones.map(z => Object.assign(pubZone(z), { owner: z.owner, note: z.adminNote || '' })).sort((a, b) => b.views30 - a.views30); }
async function adminSet(id, body) {
const z = J.db.zones.find(z => z.id === String(id)); if (!z) return { error: 'No such zone.' };
if (body.paused != null) z.adminPaused = !!body.paused;
if (body.note != null) z.adminNote = String(body.note).slice(0, 200);
J.save(); return { ok: true, zone: Object.assign(pubZone(z), { owner: z.owner, note: z.adminNote || '' }) };
}
function totals() { const since = Date.now() - 30 * DAY; const imps = J.db.imps.filter(i => i.ts >= since && !i.bot); return { zones: J.db.zones.length, views30: imps.length, viewable30: imps.filter(i => i.ok).length, clicks30: imps.filter(i => i.k).length, nas30: imps.filter(i => i.nas).length, credits: J.db.zones.reduce((n, z) => n + (z.credits || 0), 0) }; }
module.exports = { init, SIZES, NAS_SIZES, settings, nasFrame, list, create, update, tag, serve, seen, click, totals };
module.exports = { init, SIZES, NAS_SIZES, WARMUP, HOLD_RATIO, settings, nasFrame, list, create, update, tag, serve, seen, click, totals, adminList, adminSet };