Merge Banner Spin phases 1 and 2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+376
@@ -0,0 +1,376 @@
|
||||
// Banner Spin (LinkSpin, 2026-10-18, plan approved by Marty the same day): one image URL + one click URL that rotate up to
|
||||
// 25 banners, each with its own target. Phase 1 (engine) + phase 2 (builder) of "LinkSpin Banner Spin: plan".
|
||||
//
|
||||
// Serving. /i/<code>.gif picks a banner on every load (weighted pick, pause, dayparting, fallback: the rotator's own rules)
|
||||
// and answers with the image itself (uploaded files from DATA_DIR/uploads, hot ones cached in memory) or a no-store 302
|
||||
// to a pasted https image. Every image response is Cache-Control: no-store, private with a fresh ETag, so a browser asks
|
||||
// again on every page view. /s/<code>.js writes the banner AND its own click link in one go (exact match). /c/<code> is the
|
||||
// click. Paths are neutral on purpose: no size token and never the words banner or ads (EasyList), and codes never
|
||||
// contain "ad". Every link domain answers every code, like /r/.
|
||||
//
|
||||
// Click matching (the image and the click are two separate requests). On each image load the server keeps a note in
|
||||
// memory: visitor key + referring page host -> the banner it showed, for 15 minutes. The visitor key is the same
|
||||
// daily-salted hash spin links use (no IP stored). On a click the note for that key + host is looked up (the most recent
|
||||
// one when there are several) and the visitor goes to that banner's target; no note -> the fallback target, logged as
|
||||
// unmatched. /s/ clicks carry the banner (?x=) and match exactly. Rotation modes: random by weight (default) or one per
|
||||
// visitor (the same banner all day, a stable hash of the visitor key).
|
||||
//
|
||||
// Counting. Impressions are COUNTERS (per banner, per placement host, per Central day, plus a small uniques sample), kept
|
||||
// as pending deltas in memory and merged into DATA_DIR/bannerspin-counts.json every few seconds (read, add, atomic
|
||||
// write, so two app copies during a deploy overlap both land). Bots and prefetchers are not counted; one visitor's
|
||||
// reloads count once per minute per banner. Clicks are rows like spin-link clicks, with the usual lsid click id
|
||||
// ('k' + 11 hex, never valid hex so it can never collide with a rotator id), so joins / wallets / purchases and partner
|
||||
// postbacks credit the banner (rotator.convert falls through to convert() here), and a traffic source's postback fires.
|
||||
//
|
||||
// Access. Members with at least one own package of $25 or more. Starter 2 Banner Spins x 5 banners; Builder (level 2
|
||||
// open, 2 qualifying buyers) 5 x 15; Leader (level 3 open, 5 qualifying buyers) 10 x 25. Facts come from server.js
|
||||
// (chain + positions); once seen they are remembered here so a rolling chain window never takes a tier away. Dropping
|
||||
// below a tier keeps everything serving; it only stops new ones.
|
||||
//
|
||||
// Moderation. Admin can take one banner or a whole Banner Spin offline (a neutral blank image + the fallback link), or
|
||||
// switch the whole feature off. Store: DATA_DIR/bannerspin.json (atomic writes).
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
let DATA_DIR = null, UPLOADS_DIR = null, rotator = null, geo = null, SOURCES = null, OWN_HOSTS = () => [], FACTS = async () => ({ ownBuy: false, buyers: 0 }), ADMIN = '';
|
||||
const DAY = 86400000;
|
||||
const SIZES = { '468x60': [468, 60], '728x90': [728, 90], '300x250': [300, 250], '125x125': [125, 125], '160x600': [160, 600], '120x600': [120, 600], '336x280': [336, 280], '250x250': [250, 250], '320x50': [320, 50] };
|
||||
const TIERS = {
|
||||
starter: { key: 'starter', label: 'Starter', spins: 2, banners: 5, need: 'your own package of $25 or more' },
|
||||
builder: { key: 'builder', label: 'Builder', spins: 5, banners: 15, need: 'level 2 open, 2 qualifying buyers' },
|
||||
leader: { key: 'leader', label: 'Leader', spins: 10, banners: 25, need: 'level 3 open, 5 qualifying buyers' }
|
||||
};
|
||||
const ORDER = ['starter', 'builder', 'leader'];
|
||||
const MAX_BYTES = 150 * 1024, MAX_BANNERS = 25;
|
||||
const NOTE_TTL = 15 * 60000, DEDUPE_MS = 60000, FLUSH_MS = 5000, UNIQ_CAP = 500, HOSTS_CAP = 200;
|
||||
const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i;
|
||||
const norm = e => String(e || '').trim().toLowerCase();
|
||||
const CT_FMT = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit' });
|
||||
const ctDay = ts => CT_FMT.format(new Date(ts || Date.now()));
|
||||
const LOCAL_IMG = /^\/uploads\/([a-f0-9]{24}\.(png|jpg|gif))$/;
|
||||
const MIME = { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' };
|
||||
const httpsUrl = u => { let s = String(u || '').trim(); if (s && !/^[a-z][a-z0-9+.-]*:\/\//i.test(s) && /^[^\s\/]+\.[^\s]+/.test(s)) s = 'https://' + s; return /^https:\/\/[^\s"'<>]+$/i.test(s) && s.length <= 500 ? s : null; };
|
||||
|
||||
function writeAtomic(file, data) { try { const tmp = file + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, data); fs.renameSync(tmp, file); } catch (e) { console.error('bannerspin save', e.message); } }
|
||||
const J = { db: null, FILE: () => path.join(DATA_DIR, 'bannerspin.json'),
|
||||
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = null; } if (!this.db || typeof this.db !== 'object') this.db = { v: 1 };
|
||||
for (const k of ['spins', 'clicks', 'conv']) if (!Array.isArray(this.db[k])) this.db[k] = [];
|
||||
for (const k of ['images', 'grants', 'qual', 'settings']) if (!this.db[k] || typeof this.db[k] !== 'object') this.db[k] = {}; },
|
||||
save() { writeAtomic(this.FILE(), JSON.stringify(this.db)); } };
|
||||
// impression counters: d[spinId][day] = { b: { bid: n }, h: { host: { bid: n } }, u: { bid: [visitor prefixes] } }
|
||||
const C = { db: { v: 1, d: {} }, FILE: () => path.join(DATA_DIR, 'bannerspin-counts.json'),
|
||||
read() { try { const x = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); return x && x.d ? x : { v: 1, d: {} }; } catch (e) { return { v: 1, d: {} }; } } };
|
||||
let PENDING = { d: {} }, DIRTY = false, timer = null, lastPrune = 0;
|
||||
|
||||
function init(opts) {
|
||||
DATA_DIR = opts.dataDir; UPLOADS_DIR = opts.uploadsDir || path.join(DATA_DIR, 'uploads'); rotator = opts.rotator || null; geo = opts.geo || null; SOURCES = opts.sources || null;
|
||||
OWN_HOSTS = opts.ownHosts || OWN_HOSTS; FACTS = opts.facts || FACTS; ADMIN = norm(opts.adminEmail);
|
||||
J.load(); C.db = C.read();
|
||||
if (opts.schedule !== false) { timer = setInterval(() => { flush(); sweep(); }, FLUSH_MS); if (timer.unref) timer.unref(); }
|
||||
}
|
||||
|
||||
// ── codes: 7 chars, no 0/1/i/l/o, never containing "ad" or digit-x-digit (EasyList), unique among Banner Spins ──
|
||||
const ALPHA = 'abcdefghjkmnpqrstuvwxyz23456789';
|
||||
const BAD_CODE = /ad|banner|\dx\d/; // no digit-x-digit run either, so nothing reads like a size
|
||||
function newCode() { for (;;) { let s = ''; for (let i = 0; i < 7; i++) s += ALPHA[crypto.randomInt(ALPHA.length)]; if (!BAD_CODE.test(s) && !J.db.spins.some(x => x.code === s)) return s; } }
|
||||
|
||||
// ── visitor key: the rotator's daily-salted hash (UTC day | ip | ua), nothing stored but the hash ──
|
||||
const ipOf = req => String(req.headers['x-forwarded-for'] || (req.socket && req.socket.remoteAddress) || '').split(',')[0].trim();
|
||||
const vkey = (req, ts) => crypto.createHash('sha256').update(new Date(ts || Date.now()).toISOString().slice(0, 10) + '|' + ipOf(req) + '|' + String(req.headers['user-agent'] || '')).digest('hex').slice(0, 16);
|
||||
// keys to try for a click: today's, and yesterday's for the first 15 minutes after UTC midnight (a note made at 23:59 still matches)
|
||||
function vkeys(req) { const now = Date.now(); const k = [vkey(req, now)]; if (now % DAY < NOTE_TTL) k.push(vkey(req, now - DAY)); return k; }
|
||||
const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT.test(ua); };
|
||||
const isPrefetch = req => /prefetch|prerender|preview/i.test([req.headers.purpose, req.headers['sec-purpose'], req.headers['x-purpose'], req.headers['x-moz']].filter(Boolean).join(' '));
|
||||
// the placement: the page the banner sits on (the browser's referrer, else its origin), www stripped
|
||||
function hostOf(req) { try { return new URL(String(req.headers.referer || req.headers.origin || '')).hostname.toLowerCase().replace(/^www\./, '').slice(0, 80); } catch (e) { return ''; } }
|
||||
|
||||
// ── in-memory notes: visitor key -> [{ s, h, b, ts }] (newest last), 15 min ──
|
||||
const NOTES = new Map(); const SEEN = new Map(); // SEEN: v|spin|bid -> ts of the last counted impression
|
||||
function note(v, s, h, b) { let a = NOTES.get(v); if (!a) { if (NOTES.size > 200000) return; a = []; NOTES.set(v, a); } a.push({ s, h, b, ts: Date.now() }); if (a.length > 12) a.splice(0, a.length - 12); }
|
||||
function findNote(keys, s, h) {
|
||||
const now = Date.now(); let best = null, any = null;
|
||||
for (const v of keys) for (const n of (NOTES.get(v) || [])) { if (n.s !== s || now - n.ts > NOTE_TTL) continue; if (!any || n.ts >= any.ts) any = n; if (n.h === h && (!best || n.ts >= best.ts)) best = n; }
|
||||
// a click with no referrer (strict privacy settings) takes the visitor's most recent note on this Banner Spin
|
||||
return best || (!h ? any : null);
|
||||
}
|
||||
function sweep() { const now = Date.now(); for (const [k, a] of NOTES) { const keep = a.filter(n => now - n.ts <= NOTE_TTL); if (keep.length) NOTES.set(k, keep); else NOTES.delete(k); } for (const [k, t] of SEEN) if (now - t > DEDUPE_MS) SEEN.delete(k); }
|
||||
|
||||
// ── counters ──
|
||||
function bump(sid, bid, host, v) {
|
||||
const day = ctDay(); const s = PENDING.d[sid] = PENDING.d[sid] || {}; const d = s[day] = s[day] || { b: {}, h: {}, u: {} };
|
||||
d.b[bid] = (d.b[bid] || 0) + 1; const hk = host || '(none)'; const hh = d.h[hk] = d.h[hk] || {}; hh[bid] = (hh[bid] || 0) + 1;
|
||||
const u = d.u[bid] = d.u[bid] || []; const p = v.slice(0, 8); if (u.length < UNIQ_CAP && !u.includes(p)) u.push(p);
|
||||
DIRTY = true;
|
||||
}
|
||||
function mergeInto(base, add) {
|
||||
for (const [sid, days] of Object.entries(add.d)) { const s = base.d[sid] = base.d[sid] || {};
|
||||
for (const [day, x] of Object.entries(days)) { const d = s[day] = s[day] || { b: {}, h: {}, u: {} };
|
||||
for (const [b, n] of Object.entries(x.b)) d.b[b] = (d.b[b] || 0) + n;
|
||||
for (const [h, m] of Object.entries(x.h)) { let hh = d.h[h]; if (!hh) { if (Object.keys(d.h).length >= HOSTS_CAP) { hh = d.h['(other)'] = d.h['(other)'] || {}; } else hh = d.h[h] = {}; } for (const [b, n] of Object.entries(m)) hh[b] = (hh[b] || 0) + n; }
|
||||
for (const [b, arr] of Object.entries(x.u)) { const u = d.u[b] = d.u[b] || []; for (const p of arr) if (u.length < UNIQ_CAP && !u.includes(p)) u.push(p); } } }
|
||||
return base;
|
||||
}
|
||||
function flush() {
|
||||
if (!DIRTY || !DATA_DIR) return; const add = PENDING; PENDING = { d: {} }; DIRTY = false;
|
||||
const base = mergeInto(C.read(), add); // read-add-write: another app copy's deltas (deploy overlap) are kept
|
||||
if (Date.now() - lastPrune > 3600000) { lastPrune = Date.now(); const cut = ctDay(Date.now() - 400 * DAY); const live = new Set(J.db.spins.map(s => String(s.id))); for (const sid of Object.keys(base.d)) { if (!live.has(sid)) { delete base.d[sid]; continue; } for (const day of Object.keys(base.d[sid])) if (day < cut) delete base.d[sid][day]; } }
|
||||
writeAtomic(C.FILE(), JSON.stringify(base)); C.db = base;
|
||||
}
|
||||
// counted impressions for one spin, flushed + pending, as { day: { b, h, u } }
|
||||
function countsOf(sid) { const out = {}; for (const src of [C.db.d[sid] || {}, PENDING.d[sid] || {}]) mergeInto({ d: { x: out } }, { d: { x: src } }); return out; }
|
||||
|
||||
// ── tiers ──
|
||||
async function tierFor(email) {
|
||||
const e = norm(email); if (!e) return none('Sign in first.');
|
||||
const grant = J.db.grants[e];
|
||||
let f = { ownBuy: false, buyers: 0 }; try { f = Object.assign(f, await FACTS(e)); } catch (er) {}
|
||||
const q = J.db.qual[e] || {}; const own = !!(f.ownBuy || q.own); const buyers = Math.max(Number(f.buyers) || 0, Number(q.buyers) || 0);
|
||||
if ((own && !q.own) || buyers > (Number(q.buyers) || 0)) { J.db.qual[e] = { own, buyers, ts: Date.now() }; J.save(); } // once seen, kept
|
||||
let key = !own ? null : buyers >= 5 ? 'leader' : buyers >= 2 ? 'builder' : 'starter';
|
||||
if (e === ADMIN) key = 'leader';
|
||||
if (grant && TIERS[grant] && (!key || ORDER.indexOf(grant) > ORDER.indexOf(key))) key = grant;
|
||||
if (!key) return Object.assign(none('Banner Spin opens with your own package of $25 or more. Buy one under Credits and it unlocks right away.'), { buyers, ownBuy: own });
|
||||
const t = TIERS[key]; const nx = TIERS[ORDER[ORDER.indexOf(key) + 1]];
|
||||
return { ok: true, key, label: t.label, spins: t.spins, banners: t.banners, ownBuy: own, buyers, granted: !!grant, next: nx ? { label: nx.label, spins: nx.spins, banners: nx.banners, need: nx.need } : null };
|
||||
}
|
||||
const none = reason => ({ ok: false, key: '', label: 'Locked', spins: 0, banners: 0, reason, next: { label: TIERS.starter.label, spins: TIERS.starter.spins, banners: TIERS.starter.banners, need: TIERS.starter.need } });
|
||||
|
||||
// ── member CRUD ──
|
||||
const mine = owner => J.db.spins.filter(s => s.owner === norm(owner));
|
||||
const findMine = (owner, id) => J.db.spins.find(s => s.id === Number(id) && s.owner === norm(owner)) || null;
|
||||
function cleanImage(owner, img) {
|
||||
const s = String(img || '').trim(); if (!s) return { error: 'Add the banner image: upload one or paste an https image address.' };
|
||||
const m = LOCAL_IMG.exec(s);
|
||||
if (m) { const rec = J.db.images[m[1]]; if (!rec || rec.owner !== norm(owner)) return { error: 'Upload that image again from this screen.' }; return { image: s, w: rec.w, h: rec.h, bytes: rec.bytes }; }
|
||||
const u = httpsUrl(s); if (!u) return { error: 'An image address must start with https://' };
|
||||
return { image: u, w: 0, h: 0, bytes: 0 };
|
||||
}
|
||||
function cleanTarget(owner, body) {
|
||||
if (body.link != null && String(body.link) !== '') { const rid = Number(body.link); const r = rotator && rotator.findMine ? rotator.findMine(owner, rid) : null; if (!r) return { error: 'Pick one of your own spin links.' }; return { target: '', link: rid }; }
|
||||
const u = httpsUrl(body.target); if (!u) return { error: 'Where should a click go? Paste an https:// address or pick one of your spin links.' };
|
||||
return { target: u, link: 0 };
|
||||
}
|
||||
const sizeWarn = (spin, w, h) => { const [W, H] = SIZES[spin.size]; return w && h && (w !== W || h !== H) ? 'This image is ' + w + 'x' + h + ' and this Banner Spin is ' + spin.size + '. It will be stretched to fit.' : ''; };
|
||||
function pub(s, extra) {
|
||||
const cl = {}; for (const c of J.db.clicks) if (c.s === s.id && !c.bot) { const o = cl[c.b] = cl[c.b] || { n: 0, m: 0 }; o.n++; if (c.m !== 'none' && c.m !== 'off') o.m++; }
|
||||
const cnt = countsOf(s.id); const imps = {}; const since = ctDay(Date.now() - 30 * DAY); const imps30 = {};
|
||||
for (const [day, d] of Object.entries(cnt)) for (const [b, n] of Object.entries(d.b)) { imps[b] = (imps[b] || 0) + n; if (day >= since) imps30[b] = (imps30[b] || 0) + n; }
|
||||
const sum = o => Object.values(o).reduce((a, b) => a + (typeof b === 'number' ? b : b.n), 0);
|
||||
const conv = J.db.conv.filter(c => c.s === s.id).length;
|
||||
return Object.assign({ id: s.id, code: s.code, name: s.name, size: s.size, mode: s.mode || 'weight', owner: s.owner, created: s.created, paused: !!s.paused, adminOff: !!s.adminOff, adminNote: s.adminNote || '',
|
||||
fallback: s.fallback || '', fallbackImage: s.fallbackImage || '', hours: s.hours || null, tz: s.tz || 'visitor', sourceId: s.sourceId || '',
|
||||
banners: s.banners.map(b => ({ id: b.id, label: b.label || '', image: b.image, w: b.w || 0, h: b.h || 0, bytes: b.bytes || 0, target: b.target || '', link: b.link || 0, weight: b.weight, active: !!b.active, adminOff: !!b.adminOff, hours: b.hours || null, added: b.added,
|
||||
imps: imps[b.id] || 0, imps30: imps30[b.id] || 0, clicks: (cl[b.id] || {}).n || 0, matched: (cl[b.id] || {}).m || 0, warn: sizeWarn(s, b.w, b.h) })),
|
||||
imps: sum(imps), imps30: sum(imps30), fallbackImps: imps[0] || 0, clicks: sum(cl), matched: Object.values(cl).reduce((a, o) => a + o.m, 0), conversions: conv }, extra || {});
|
||||
}
|
||||
async function list(owner) { return mine(owner).map(s => pub(s)); }
|
||||
async function create(owner, body) {
|
||||
const t = await tierFor(owner); if (!t.ok) return { error: t.reason, tier: t };
|
||||
if (mine(owner).length >= t.spins) return { error: 'Your ' + t.label + ' tier holds ' + t.spins + ' Banner Spins.' + (t.next ? ' ' + t.next.label + ' (' + t.next.need + ') holds ' + t.next.spins + '.' : ''), tier: t };
|
||||
const name = String(body.name || '').trim().slice(0, 80); if (!name) return { error: 'Give the Banner Spin a name.' };
|
||||
const size = String(body.size || ''); if (!SIZES[size]) return { error: 'Pick one of the sizes: ' + Object.keys(SIZES).join(', ') + '.' };
|
||||
const s = { id: J.db.spins.reduce((m, x) => Math.max(m, x.id), 0) + 1, owner: norm(owner), name, code: newCode(), size, mode: body.mode === 'visitor' ? 'visitor' : 'weight', fallback: httpsUrl(body.fallback) || '', fallbackImage: '', banners: [], nextBanner: 1, paused: false, created: Date.now() };
|
||||
J.db.spins.push(s); J.save(); return { ok: true, spin: pub(s) };
|
||||
}
|
||||
async function update(owner, id, body) {
|
||||
const s = findMine(owner, id); if (!s) return { error: 'No such Banner Spin.' };
|
||||
if (body.remove) { J.db.spins = J.db.spins.filter(x => x !== s); J.save(); return { ok: true, removed: true }; }
|
||||
if (body.name != null) { const n = String(body.name).trim().slice(0, 80); if (n) s.name = n; }
|
||||
if (body.paused != null) s.paused = !!body.paused;
|
||||
if (body.mode != null) s.mode = body.mode === 'visitor' ? 'visitor' : 'weight';
|
||||
if (body.fallback != null) { const f = String(body.fallback).trim(); if (f && !httpsUrl(f)) return { error: 'The fallback must be an https:// address.' }; s.fallback = f ? httpsUrl(f) : ''; }
|
||||
if (body.fallbackImage != null) { const f = String(body.fallbackImage).trim(); if (!f) s.fallbackImage = ''; else { const im = cleanImage(owner, f); if (im.error) return im; s.fallbackImage = im.image; } }
|
||||
if (body.hours !== undefined) { const h = rotator.cleanHours(body.hours); if (h.error) return h; if (h.hours) s.hours = h.hours; else delete s.hours; }
|
||||
if (body.tz !== undefined) { const t = rotator.cleanTz(body.tz); if (t.error) return t; if (t.tz === 'visitor') delete s.tz; else s.tz = t.tz; }
|
||||
if (body.sourceId !== undefined) { const sid = String(body.sourceId || '').trim(); if (!sid) delete s.sourceId; else { if (!/^[a-f0-9]{10}$/.test(sid) || !SOURCES || !SOURCES.find(owner, sid)) return { error: 'No such source.' }; s.sourceId = sid; } }
|
||||
J.save(); return { ok: true, spin: pub(s) };
|
||||
}
|
||||
async function addBanner(owner, id, body) {
|
||||
const s = findMine(owner, id); if (!s) return { error: 'No such Banner Spin.' };
|
||||
const t = await tierFor(owner); const cap = Math.min(MAX_BANNERS, t.ok ? t.banners : 0);
|
||||
if (!t.ok) return { error: t.reason, tier: t };
|
||||
if (s.banners.length >= cap) return { error: 'Your ' + t.label + ' tier holds ' + cap + ' banners per Banner Spin.' + (t.next ? ' ' + t.next.label + ' (' + t.next.need + ') holds ' + t.next.banners + '.' : ''), tier: t };
|
||||
const im = cleanImage(owner, body.image); if (im.error) return im;
|
||||
const tg = cleanTarget(owner, body); if (tg.error) return tg;
|
||||
if (!im.w && body.w && body.h) { im.w = Math.min(4000, Math.max(0, Math.round(Number(body.w) || 0))); im.h = Math.min(4000, Math.max(0, Math.round(Number(body.h) || 0))); } // pasted image: the size the builder measured, for the warning only
|
||||
const b = { id: s.nextBanner++, label: String(body.label || '').trim().slice(0, 60), image: im.image, w: im.w, h: im.h, bytes: im.bytes, target: tg.target, link: tg.link, weight: Math.max(1, Math.min(100, Math.round(Number(body.weight) || 10))), active: true, added: Date.now() };
|
||||
s.banners.push(b); J.save(); return { ok: true, spin: pub(s), warn: sizeWarn(s, b.w, b.h) };
|
||||
}
|
||||
async function updateBanner(owner, id, bid, body) {
|
||||
const s = findMine(owner, id); if (!s) return { error: 'No such Banner Spin.' };
|
||||
const b = s.banners.find(x => x.id === Number(bid)); if (!b) return { error: 'No such banner.' };
|
||||
if (body.remove) { s.banners = s.banners.filter(x => x !== b); J.save(); return { ok: true, spin: pub(s) }; }
|
||||
if (body.weight != null) b.weight = Math.max(1, Math.min(100, Math.round(Number(body.weight) || 1)));
|
||||
if (body.active != null) b.active = !!body.active;
|
||||
if (body.label != null) b.label = String(body.label).trim().slice(0, 60);
|
||||
if (body.image != null) { const im = cleanImage(owner, body.image); if (im.error) return im; Object.assign(b, { image: im.image, w: im.w, h: im.h, bytes: im.bytes }); }
|
||||
if (body.target != null || body.link != null) { const tg = cleanTarget(owner, body); if (tg.error) return tg; b.target = tg.target; b.link = tg.link; }
|
||||
if (body.hours !== undefined) { const h = rotator.cleanHours(body.hours); if (h.error) return h; if (h.hours) b.hours = h.hours; else delete b.hours; }
|
||||
J.save(); return { ok: true, spin: pub(s) };
|
||||
}
|
||||
// an uploaded image (server.js checked type, magic and the 150 KB limit, and wrote the file): remember owner + size
|
||||
function noteImage(owner, name, w, h, bytes, mime) { J.db.images[name] = { owner: norm(owner), w, h, bytes, mime, ts: Date.now() }; J.save(); }
|
||||
|
||||
// image dimensions from the header bytes: PNG IHDR, GIF logical screen, JPEG SOFn
|
||||
function dims(buf, mime) {
|
||||
try {
|
||||
if (mime === 'image/png' && buf.length > 24) return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) };
|
||||
if (mime === 'image/gif' && buf.length > 10) return { w: buf.readUInt16LE(6), h: buf.readUInt16LE(8) };
|
||||
if (mime === 'image/jpeg') { let i = 2; while (i + 9 < buf.length) { if (buf[i] !== 0xff) { i++; continue; } const mk = buf[i + 1]; const len = buf.readUInt16BE(i + 2);
|
||||
if (mk >= 0xc0 && mk <= 0xcf && mk !== 0xc4 && mk !== 0xc8 && mk !== 0xcc) return { h: buf.readUInt16BE(i + 5), w: buf.readUInt16BE(i + 7) }; i += 2 + len; } }
|
||||
} catch (e) {}
|
||||
return { w: 0, h: 0 };
|
||||
}
|
||||
|
||||
// ── serving ──
|
||||
const live = () => !J.db.settings.off;
|
||||
const byCode = code => J.db.spins.find(s => s.code === norm(code)) || null;
|
||||
function cellFor(s, req) { let country = ''; try { country = geo && geo.countryOf ? (geo.countryOf(ipOf(req)) || '') : ''; } catch (e) {} return { cell: rotator.cellAt(rotator.zoneFor(s, country)), country }; }
|
||||
function pick(s, cell, v) {
|
||||
const lv = s.banners.filter(b => b.active && !b.adminOff && rotator.isOn(b.hours, cell)); if (!lv.length) return null;
|
||||
const total = lv.reduce((n, b) => n + b.weight, 0);
|
||||
let x = s.mode === 'visitor' ? parseInt(crypto.createHash('sha256').update(v + '|' + s.id).digest('hex').slice(0, 8), 16) % total : crypto.randomInt(total);
|
||||
for (const b of lv) { x -= b.weight; if (x < 0) return b; } return lv[lv.length - 1];
|
||||
}
|
||||
// what to show right now: { banner, fallback, blank } plus the note/count side effects (count = false for an exact ?x= fetch)
|
||||
function choose(s, req, opts) {
|
||||
opts = opts || {};
|
||||
if (!live() || s.adminOff) return { blank: true };
|
||||
if (opts.x != null) { const b = s.banners.find(q => q.id === Number(opts.x) && !q.adminOff); return b ? { banner: b } : { blank: true }; }
|
||||
const v = vkey(req); const { cell } = cellFor(s, req);
|
||||
const off = s.paused || !rotator.isOn(s.hours, cell);
|
||||
const b = off ? null : pick(s, cell, v);
|
||||
const out = b ? { banner: b } : (s.fallbackImage ? { fallback: true } : { blank: true, fallback: true });
|
||||
if (!isBot(req) && !isPrefetch(req)) {
|
||||
const bid = b ? b.id : 0; const host = hostOf(req);
|
||||
note(v, s.id, host, bid);
|
||||
const k = v + '|' + s.id + '|' + bid; const last = SEEN.get(k);
|
||||
if (!last || Date.now() - last >= DEDUPE_MS) { SEEN.set(k, Date.now()); bump(String(s.id), bid, host, v); }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// the image source for a choice: { local: name } | { url } | { blank: [w, h] }
|
||||
function sourceOf(s, ch) {
|
||||
const img = ch.banner ? ch.banner.image : ch.fallback && s.fallbackImage ? s.fallbackImage : '';
|
||||
if (!img) return { blank: SIZES[s.size] };
|
||||
const m = LOCAL_IMG.exec(img); return m ? { local: m[1] } : { url: img };
|
||||
}
|
||||
async function image(code, req, x) { const s = byCode(code); if (!s) return null; const ch = choose(s, req, { x }); return Object.assign({ size: SIZES[s.size] }, sourceOf(s, ch)); }
|
||||
|
||||
// the script embed: picks, counts and writes the banner with its own click link (exact match)
|
||||
async function script(code, req, base) {
|
||||
const s = byCode(code); if (!s) return null;
|
||||
const ch = choose(s, req); const [w, h] = SIZES[s.size];
|
||||
const x = ch.banner ? ch.banner.id : 0;
|
||||
const src = ch.banner && !LOCAL_IMG.test(ch.banner.image) ? ch.banner.image : base + '/i/' + s.code + '.gif' + (x ? '?x=' + x : '?x=0');
|
||||
const href = base + '/c/' + s.code + '?x=' + x;
|
||||
const html = '<a href="' + href.replace(/"/g, '"') + '" target="_blank" rel="noopener"><img src="' + src.replace(/"/g, '"') + '" width="' + w + '" height="' + h + '" alt="" style="border:0;max-width:100%;height:auto"></a>';
|
||||
const js = JSON.stringify(html).replace(/</g, '\\u003c');
|
||||
return '(function(){var h=' + js + ',s=document.currentScript;if(!s){var a=document.getElementsByTagName("script");for(var i=a.length-1;i>=0;i--){if((a[i].src||"").indexOf("/s/' + s.code + '.js")>-1){s=a[i];break;}}}var d=document.createElement("span");d.innerHTML=h;if(s&&s.parentNode){s.parentNode.insertBefore(d.firstChild,s.nextSibling);}else{document.write(h);}})();';
|
||||
}
|
||||
|
||||
// the click: { url, lsid } or null (unknown code). reqHost = the link domain the click came in on (spin-link targets stay on it).
|
||||
async function click(code, req, reqHost) {
|
||||
const s = byCode(code); if (!s) return null;
|
||||
const bot = isBot(req) ? 1 : 0; const h = hostOf(req); const keys = vkeys(req);
|
||||
const u = new URL(req.url, 'http://x'); const xs = u.searchParams.get('x');
|
||||
let b = null, m = 'none';
|
||||
if (!live() || s.adminOff) m = 'off';
|
||||
else if (xs != null && /^\d{1,4}$/.test(xs)) { b = Number(xs) ? s.banners.find(q => q.id === Number(xs) && !q.adminOff) || null : null; m = 'exact'; }
|
||||
else { const n = findNote(keys, s.id, h); if (n) { b = n.b ? s.banners.find(q => q.id === n.b && !q.adminOff) || null : null; m = 'note'; } }
|
||||
// where to: the banner's target (its spin link, on the same link domain), else the fallback
|
||||
let url = null;
|
||||
if (b) { if (b.link) { const r = rotator && rotator.rawRotations ? rotator.rawRotations().find(x => x.id === b.link && x.owner === s.owner) : null; url = r ? 'https://' + (reqHost || 'linkspin.app') + '/r/' + r.code : null; } else url = b.target; }
|
||||
if (!url) { url = s.fallback || null; if (b) b = null; }
|
||||
if (!url) { const first = s.banners.find(q => q.active && !q.adminOff && q.target); url = first ? first.target : null; } // no fallback set: the first live banner beats a dead end
|
||||
let country = ''; try { country = geo && geo.countryOf ? (geo.countryOf(ipOf(req)) || '') : ''; } catch (e) {}
|
||||
const ua = String(req.headers['user-agent'] || ''); const device = /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop';
|
||||
const q = {}; { let n = 0; for (const [k, val] of u.searchParams) { const key = String(k).toLowerCase(); if (n >= 20) break; if (/^(clickid|click_id|cid|subid|sub_id|s[1-5]|sub[1-5]|t[1-5]|aff_sub[1-5]?|utm_(source|medium|campaign|term|content)|src|source|campaign|zone|placement|cost|creative|site|keyword|geo|os|browser|device|carrier|format|external_id|visitor_id)$/.test(key)) { q[key] = String(val).slice(0, 200); n++; } } }
|
||||
const id = 'k' + crypto.randomBytes(6).toString('hex').slice(0, 11);
|
||||
J.db.clicks.push({ id, s: s.id, b: b ? b.id : 0, ts: Date.now(), v: keys[0], h: h || undefined, m, bot, c: country || undefined, dv: device, q: Object.keys(q).length ? q : undefined, sr: s.sourceId || undefined });
|
||||
if (J.db.clicks.length > 200000) J.db.clicks = J.db.clicks.slice(-150000);
|
||||
J.save();
|
||||
if (url) {
|
||||
const vals = { clickid: q.clickid || q.cid || q.click_id || '', subid: q.subid || q.sub_id || q.s1 || '', s1: q.s1 || q.sub1 || '', s2: q.s2 || q.sub2 || '', s3: q.s3 || q.sub3 || '', s4: q.s4 || q.sub4 || '', s5: q.s5 || q.sub5 || '', source: h || 'direct', country, device, lsid: id, code: s.code };
|
||||
for (const [k, val] of Object.entries(q)) if (vals[k] == null) vals[k] = val;
|
||||
url = url.replace(/\{([a-z0-9_]{1,24})\}/gi, (mm, k) => encodeURIComponent(vals[k.toLowerCase()] == null ? '' : vals[k.toLowerCase()]));
|
||||
try { const t = new URL(url); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid') && !/^\/r\//.test(t.pathname)) { t.searchParams.set('lsid', id); url = t.toString(); } } catch (e) {}
|
||||
}
|
||||
return { url, lsid: id, banner: b, matched: m };
|
||||
}
|
||||
// conversions (rotator.convert falls through to here for a 'k' click id): dedupe per click + event
|
||||
async function convert(lsid, ev, facts) {
|
||||
const c = J.db.clicks.find(x => x.id === String(lsid)); if (!c) return null;
|
||||
const s = J.db.spins.find(x => x.id === c.s); if (!s) return null;
|
||||
if (!J.db.conv.some(x => x.lsid === c.id && x.ev === ev)) { J.db.conv.push({ lsid: c.id, s: s.id, b: c.b, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: c.sr || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
|
||||
return { owner: s.owner, code: s.code, rotationId: 0, bannerSpinId: s.id, bannerId: c.b, q: c.q || {}, s: c.h || 'direct', c: c.c || '', dv: c.dv, sourceId: c.sr || '' };
|
||||
}
|
||||
|
||||
// ── stats: per banner and per placement (impressions, clicks, CTR, match rate), last 30 Central days by day ──
|
||||
async function stats(owner, id) {
|
||||
const s = findMine(owner, id); if (!s) return null;
|
||||
const cnt = countsOf(s.id); const clicks = J.db.clicks.filter(c => c.s === s.id && !c.bot);
|
||||
const per = {}; const at = (o, k) => (o[k] = o[k] || { imps: 0, clicks: 0, matched: 0, uniq: 0 });
|
||||
const hosts = {}; const days = {};
|
||||
for (const [day, d] of Object.entries(cnt)) {
|
||||
for (const [b, n] of Object.entries(d.b)) { at(per, b).imps += n; at(days, day).imps += n; }
|
||||
for (const [b, arr] of Object.entries(d.u)) at(per, b).uniq += arr.length;
|
||||
for (const [hh, m] of Object.entries(d.h)) for (const n of Object.values(m)) at(hosts, hh).imps += n;
|
||||
}
|
||||
for (const c of clicks) { const ok = c.m === 'exact' || c.m === 'note'; const o = at(per, c.b); o.clicks++; if (ok) o.matched++; const ho = at(hosts, c.h || '(none)'); ho.clicks++; if (ok) ho.matched++; const dd = at(days, ctDay(c.ts)); dd.clicks++; if (ok) dd.matched++; }
|
||||
const ctr = o => o.imps ? Math.round(o.clicks / o.imps * 10000) / 100 : null; const mr = o => o.clicks ? Math.round(o.matched / o.clicks * 100) : null;
|
||||
const conv = J.db.conv.filter(c => c.s === s.id); const convBy = {}; for (const c of conv) { const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; } const convB = {}; for (const c of conv) convB[c.b] = (convB[c.b] || 0) + 1;
|
||||
const banners = s.banners.map(b => { const o = per[b.id] || { imps: 0, clicks: 0, matched: 0, uniq: 0 }; return { id: b.id, label: b.label || '', image: b.image, active: !!b.active, imps: o.imps, uniques: o.uniq, clicks: o.clicks, matched: o.matched, ctr: ctr(o), matchRate: mr(o), conversions: convB[b.id] || 0 }; });
|
||||
const fb = per[0] || { imps: 0, clicks: 0, matched: 0, uniq: 0 };
|
||||
const tot = { imps: 0, clicks: clicks.length, matched: 0, uniq: 0 }; for (const o of Object.values(per)) { tot.imps += o.imps; tot.matched += o.matched; tot.uniq += o.uniq; }
|
||||
const since = ctDay(Date.now() - 30 * DAY);
|
||||
return { spin: pub(s), totals: { imps: tot.imps, clicks: tot.clicks, ctr: ctr(tot), matchRate: mr(tot), matched: tot.matched, unmatched: clicks.filter(c => c.m === 'none').length, uniquesSampled: tot.uniq, conversions: conv.length, bots: J.db.clicks.filter(c => c.s === s.id && c.bot).length },
|
||||
banners, fallback: { imps: fb.imps, clicks: fb.clicks, ctr: ctr(fb) },
|
||||
placements: Object.entries(hosts).map(([host, o]) => ({ host, imps: o.imps, clicks: o.clicks, ctr: ctr(o), matchRate: mr(o) })).sort((a, b) => b.imps - a.imps || b.clicks - a.clicks).slice(0, 30),
|
||||
days: Object.entries(days).filter(([d]) => d >= since).sort().map(([day, o]) => ({ day, imps: o.imps, clicks: o.clicks })), conversions: Object.entries(convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
|
||||
}
|
||||
|
||||
// ── admin ──
|
||||
function adminAll() {
|
||||
const cl = {}; for (const c of J.db.clicks) if (!c.bot) cl[c.s] = (cl[c.s] || 0) + 1;
|
||||
return J.db.spins.map(s => { let imps = 0; for (const d of Object.values(countsOf(s.id))) for (const n of Object.values(d.b)) imps += n;
|
||||
return { id: s.id, code: s.code, name: s.name, owner: s.owner, size: s.size, mode: s.mode || 'weight', created: s.created, paused: !!s.paused, adminOff: !!s.adminOff, adminNote: s.adminNote || '', fallback: s.fallback || '', fallbackImage: s.fallbackImage || '', sourceId: s.sourceId || '', dayparted: !!s.hours,
|
||||
banners: s.banners.map(b => ({ id: b.id, label: b.label || '', image: b.image, target: b.target || '', link: b.link || 0, weight: b.weight, active: !!b.active, adminOff: !!b.adminOff })), imps, clicks: cl[s.id] || 0, conversions: J.db.conv.filter(c => c.s === s.id).length }; });
|
||||
}
|
||||
function adminSet(id, body) {
|
||||
const s = J.db.spins.find(x => x.id === Number(id)); if (!s) return { error: 'No such Banner Spin.' };
|
||||
const nt = body.note != null ? String(body.note).slice(0, 200) : null;
|
||||
if (body.bannerId != null) { const b = s.banners.find(x => x.id === Number(body.bannerId)); if (!b) return { error: 'No such banner.' }; if (body.off != null) b.adminOff = !!body.off; if (nt != null) b.adminNote = nt; }
|
||||
else { if (body.off != null) s.adminOff = !!body.off; if (nt != null) s.adminNote = nt; }
|
||||
J.save(); return { ok: true, spin: adminAll().find(x => x.id === s.id) };
|
||||
}
|
||||
function setGlobal(body) { if (body.off != null) J.db.settings.off = !!body.off; if (body.grant && body.email) { const e = norm(body.email); if (body.grant === 'none') delete J.db.grants[e]; else if (TIERS[body.grant]) J.db.grants[e] = body.grant; else return { error: 'Grant is starter, builder, leader or none.' }; } J.save(); return { ok: true, off: !!J.db.settings.off, grants: J.db.grants }; }
|
||||
function settings() { return { off: !!J.db.settings.off, grants: J.db.grants }; }
|
||||
// image files Banner Spins use, for the admin upload list (file name -> owner + where)
|
||||
function imageRefs() { const out = {}; for (const s of J.db.spins) for (const im of s.banners.map(b => b.image).concat(s.fallbackImage || [])) { const m = LOCAL_IMG.exec(im || ''); if (m) out[m[1]] = { email: s.owner, where: 'Banner Spin ' + s.code }; } for (const [n, r] of Object.entries(J.db.images)) if (!out[n]) out[n] = { email: r.owner, where: '' }; return out; }
|
||||
function totals() { return { spins: J.db.spins.length, banners: J.db.spins.reduce((n, s) => n + s.banners.length, 0), clicks: J.db.clicks.length }; }
|
||||
|
||||
// a transparent PNG at the exact banner size, for the blank image (admin off, nothing to show); cached per size
|
||||
const BLANK = new Map();
|
||||
function crc32(buf) { let c, crc = 0xffffffff; for (let n = 0; n < buf.length; n++) { c = (crc ^ buf[n]) & 0xff; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; crc = (crc >>> 8) ^ c; } return (crc ^ 0xffffffff) >>> 0; }
|
||||
function blankPng(w, h) {
|
||||
const key = w + 'x' + h; if (BLANK.has(key)) return BLANK.get(key);
|
||||
const zlib = require('zlib'); const chunk = (type, data) => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type), data]); const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(td)); return Buffer.concat([len, td, crc]); };
|
||||
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 6; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; // 8-bit RGBA, all zero = transparent
|
||||
const raw = Buffer.alloc((w * 4 + 1) * h); // filter byte 0 + transparent pixels per row
|
||||
const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw, { level: 9 })), chunk('IEND', Buffer.alloc(0))]);
|
||||
BLANK.set(key, png); return png;
|
||||
}
|
||||
// hot uploaded images in memory (each at most 150 KB, 32 MB in all)
|
||||
const IMG = new Map(); let IMG_BYTES = 0;
|
||||
function readImage(name) {
|
||||
const hit = IMG.get(name); if (hit) { IMG.delete(name); IMG.set(name, hit); return hit; }
|
||||
let buf; try { buf = fs.readFileSync(path.join(UPLOADS_DIR, name)); } catch (e) { return null; }
|
||||
const rec = { buf, mime: MIME[name.split('.').pop()] || 'application/octet-stream' };
|
||||
if (buf.length <= MAX_BYTES) { IMG.set(name, rec); IMG_BYTES += buf.length; while (IMG_BYTES > 32 * 1024 * 1024) { const [k, v] = IMG.entries().next().value; IMG.delete(k); IMG_BYTES -= v.buf.length; } }
|
||||
return rec;
|
||||
}
|
||||
const _test = { notes: () => NOTES, flush, vkey };
|
||||
module.exports = { init, SIZES, TIERS, MAX_BYTES, tierFor, list, create, update, addBanner, updateBanner, noteImage, dims, image, script, click, convert, stats, adminAll, adminSet, setGlobal, settings, imageRefs, totals, blankPng, readImage, flush, findMine, _test };
|
||||
+20
-2
@@ -11,11 +11,11 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let R = null; // { dataDir, uploadsDir, accounts, pages, rotator, sources, zones, ads, postbacks, audiences, messages, videomaker, reports, domains, adminEmail, houseOwner, linkHost(), pagesHost(), siteHost }
|
||||
let R = null; // { dataDir, uploadsDir, accounts, pages, rotator, bannerspin, sources, zones, ads, postbacks, audiences, messages, videomaker, reports, domains, adminEmail, houseOwner, linkHost(), pagesHost(), siteHost }
|
||||
function init(refs) { R = refs; }
|
||||
|
||||
const TYPES = [
|
||||
{ key: 'page', label: 'Pages' }, { key: 'link', label: 'Links' }, { key: 'source', label: 'Sources' }, { key: 'zone', label: 'Zones' },
|
||||
{ key: 'page', label: 'Pages' }, { key: 'link', label: 'Links' }, { key: 'bannerspin', label: 'Banner Spins' }, { key: 'source', label: 'Sources' }, { key: 'zone', label: 'Zones' },
|
||||
{ key: 'ad', label: 'Ads' }, { key: 'postback', label: 'Postbacks' }, { key: 'upload', label: 'Uploads' }, { key: 'profile', label: 'Profiles' },
|
||||
{ key: 'message', label: 'Broadcasts' }, { key: 'audience', label: 'Audiences' }, { key: 'video', label: 'Videos' }
|
||||
];
|
||||
@@ -81,6 +81,23 @@ async function collect(fresh) {
|
||||
search: [r.code].concat(r.destinations.map(d => d.url + ' ' + (d.label || '')), r.fallback) });
|
||||
}
|
||||
|
||||
// Banner Spins (2026-10-18): one image URL + one click URL rotating the member's banners; admin can take a banner or the whole thing offline
|
||||
if (R.bannerspin) for (const b of R.bannerspin.adminAll()) {
|
||||
const flags = [];
|
||||
if (b.adminOff) flags.push({ k: 'off', t: 'Taken offline by admin' + (b.adminNote ? ': ' + b.adminNote : '') });
|
||||
const offB = b.banners.filter(x => x.adminOff); if (offB.length) flags.push({ k: 'off', t: offB.length + ' banner' + (offB.length > 1 ? 's' : '') + ' taken offline by admin' });
|
||||
const live = !b.adminOff && !b.paused && b.banners.some(x => x.active && !x.adminOff);
|
||||
const stamp = 'Taken offline from Member content ' + ctDay(Date.now());
|
||||
const actions = [b.adminOff ? { label: 'Put Banner Spin back online', path: '/api/admin/bannerspins/' + b.id, body: { off: false, note: '' } } : { label: 'Take Banner Spin offline', path: '/api/admin/bannerspins/' + b.id, body: { off: true, note: stamp }, warn: 'Take this Banner Spin offline? Every placement shows a blank image and clicks go to its fallback.' }]
|
||||
.concat(b.banners.map(x => x.adminOff ? { label: 'Banner ' + x.id + ' back online', path: '/api/admin/bannerspins/' + b.id, body: { bannerId: x.id, off: false, note: '' } } : { label: 'Banner ' + x.id + ' offline', path: '/api/admin/bannerspins/' + b.id, body: { bannerId: x.id, off: true, note: stamp }, warn: 'Take banner ' + x.id + ' offline? The Banner Spin keeps rotating the others.' }));
|
||||
add({ type: 'bannerspin', id: String(b.id), ownerEmail: b.owner, title: b.name, created: b.created, status: b.adminOff ? 'offline' : b.paused ? 'paused' : live ? 'live' : 'empty', live,
|
||||
url: 'https://' + linkHost + '/i/' + b.code + '.gif', open: null,
|
||||
detail: { code: b.code, size: b.size, mode: b.mode, image: 'https://' + linkHost + '/i/' + b.code + '.gif', click: 'https://' + linkHost + '/c/' + b.code, fallback: b.fallback, fallbackImage: b.fallbackImage, dayparted: b.dayparted, sourceId: b.sourceId,
|
||||
banners: b.banners.map(x => ({ id: x.id, label: x.label, image: x.image, target: x.target, link: x.link, weight: x.weight, active: x.active, adminOff: x.adminOff })) },
|
||||
counts: { imps: b.imps, clicks: b.clicks, conversions: b.conversions }, hosts: b.banners.map(x => hostOf(x.target)).concat(hostOf(b.fallback), b.banners.map(x => hostOf(x.image))), flags, actions,
|
||||
search: [b.code, b.size, b.fallback].concat(b.banners.map(x => x.image + ' ' + x.target + ' ' + (x.label || ''))) });
|
||||
}
|
||||
|
||||
// traffic sources
|
||||
for (const s of R.sources.adminAll()) add({ type: 'source', id: s.id, ownerEmail: s.owner, title: s.name, created: s.created, status: s.enabled ? 'live' : 'off', live: !!s.enabled, url: s.site ? 'https://' + s.site : '', open: null,
|
||||
detail: { template: s.template, site: s.site, costModel: s.costModel, postbackUrl: s.postbackUrl, method: s.method, events: s.events, params: (s.params || []).length, lastStatus: s.lastStatus },
|
||||
@@ -133,6 +150,7 @@ async function collect(fresh) {
|
||||
const camps = await R.ads.adminList(1000000);
|
||||
for (const c of camps) { if (c.house) continue; const blob = JSON.stringify([c.imageUrl, c.body]); let m; UP_RE.lastIndex = 0; while ((m = UP_RE.exec(blob))) ref(m[1], c.owner, 'campaign #' + c.id + ' (' + c.type + ')'); }
|
||||
} catch (e) {}
|
||||
try { if (R.bannerspin) for (const [f, x] of Object.entries(R.bannerspin.imageRefs())) if (x.where) ref(f, x.email, x.where); } catch (e) {}
|
||||
const idx = readIdx();
|
||||
let files = []; try { files = fs.readdirSync(R.uploadsDir).filter(f => /^[a-z0-9]{24}\.(png|jpg|webp|gif|mp4|webm)$/i.test(f)); } catch (e) {}
|
||||
const seenUp = new Set();
|
||||
|
||||
+1
-1
@@ -472,6 +472,6 @@
|
||||
</div>
|
||||
|
||||
<script src="/assets/common.js?v=20261016a"></script>
|
||||
<script src="/assets/admin.js?v=20261018b"></script>
|
||||
<script src="/assets/admin.js?v=20261018bs"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -515,7 +515,7 @@
|
||||
const ctHost = u => { try { return new URL(u, location.origin).hostname.replace(/^www\./, ''); } catch (e) { return ''; } };
|
||||
const ctCut = (s, n) => { s = String(s || ''); return s.length > n ? s.slice(0, n - 1) + '…' : s; };
|
||||
const ctLabel = k => ((CT.data && CT.data.types) || []).reduce((m, t) => t.key === k ? t.label : m, k);
|
||||
const CT_ONE = { page: 'Page', link: 'Link', source: 'Source', zone: 'Zone', ad: 'Ad', postback: 'Postback', upload: 'Upload', profile: 'Profile', message: 'Broadcast', audience: 'Audience', video: 'Video' };
|
||||
const CT_ONE = { page: 'Page', link: 'Link', bannerspin: 'Banner Spin', source: 'Source', zone: 'Zone', ad: 'Ad', postback: 'Postback', upload: 'Upload', profile: 'Profile', message: 'Broadcast', audience: 'Audience', video: 'Video' };
|
||||
function ctDetail(r) {
|
||||
const d = r.detail || {}; const L = [];
|
||||
const line = h => { if (h) L.push('<div class="ct-l">' + h + '</div>'); };
|
||||
@@ -529,6 +529,11 @@
|
||||
line(ctA(r.url, ctCut(r.url, 60)) + ' · <span class="mono">' + esc(d.code) + '</span> · ' + ds.length + ' destination' + (ds.length === 1 ? '' : 's') + (d.dayparted ? ' · dayparted' : '') + (d.expires ? ' · demo expires ' + ctWhen(d.expires) : ''));
|
||||
line(ds.slice(0, 6).map(x => '<span class="ct-dest' + (x.active ? '' : ' off') + '">' + ctA(x.url, ctHost(x.url) || x.url) + (x.weight > 1 ? ' ×' + x.weight : '') + (!x.active ? ' <span class="muted">' + (x.autoPaused ? 'auto-paused' : 'paused') + '</span>' : '') + (x.health && x.health !== 'ok' && x.health !== 'live' ? ' <span class="bad">' + esc(x.health) + '</span>' : '') + '</span>').join(' ') + (ds.length > 6 ? ' <span class="muted">+' + (ds.length - 6) + ' more</span>' : ''));
|
||||
if (d.fallback) line('Fallback: ' + ctA(d.fallback, ctCut(d.fallback, 70)));
|
||||
} else if (r.type === 'bannerspin') {
|
||||
const bs = d.banners || [];
|
||||
line('<span class="chip-t">' + esc(d.size) + '</span> <span class="mono">' + esc(d.code) + '</span> · ' + (d.mode === 'visitor' ? 'one per visitor' : 'random by weight') + ' · ' + bs.length + ' banner' + (bs.length === 1 ? '' : 's') + (d.dayparted ? ' · dayparted' : '') + ' · ' + ctA(d.image, 'image URL') + ' · ' + ctA(d.click, 'click URL'));
|
||||
line(bs.slice(0, 8).map(x => '<span class="ct-dest' + (x.active && !x.adminOff ? '' : ' off') + '">' + ctImg(x.image) + ' #' + x.id + ' ' + (x.link ? 'spin link #' + x.link : ctA(x.target, ctHost(x.target) || x.target)) + (x.weight > 1 ? ' ×' + x.weight : '') + (x.adminOff ? ' <span class="bad">offline</span>' : !x.active ? ' <span class="muted">paused</span>' : '') + '</span>').join(' ') + (bs.length > 8 ? ' <span class="muted">+' + (bs.length - 8) + ' more</span>' : ''));
|
||||
line('Fallback: ' + (d.fallback ? ctA(d.fallback, ctCut(d.fallback, 70)) : '<span class="muted">none</span>') + (d.fallbackImage ? ' ' + ctImg(d.fallbackImage) : ''));
|
||||
} else if (r.type === 'source') {
|
||||
line(esc(d.template === 'custom' ? 'Custom source' : 'Template ' + d.template) + (d.site ? ' · ' + ctA('https://' + d.site, d.site) : '') + (d.costModel ? ' · ' + esc(d.costModel) : '') + ' · ' + ctN(d.params) + ' params');
|
||||
line(d.postbackUrl ? 'Postback (' + esc(d.method) + ', ' + esc((d.events || []).join(', ')) + '): <span class="mono small">' + esc(ctCut(d.postbackUrl, 90)) + '</span>' : '<span class="muted">No postback</span>');
|
||||
@@ -565,6 +570,7 @@
|
||||
const c = r.counts || {}; const d = r.detail || {}; const k = (n, l) => '<div><b>' + (n == null ? '-' : n) + '</b> <span class="muted">' + l + '</span></div>';
|
||||
if (r.type === 'page') return k(ctN(c.views), 'views') + k(ctN(c.uniques), 'uniques') + k(ctN(c.clicks), 'clicks out') + k(ctN(c.leads), 'leads');
|
||||
if (r.type === 'link') return k(ctN(c.clicks7), 'clicks 7d') + k(ctN(c.clicks), 'all time') + (c.conversions ? k(ctN(c.conversions), 'conversions') : '') + (c.bots ? k(ctN(c.bots), 'bots') : '');
|
||||
if (r.type === 'bannerspin') return k(ctN(c.imps), 'impressions') + k(ctN(c.clicks), 'clicks') + (c.conversions ? k(ctN(c.conversions), 'conversions') : '');
|
||||
if (r.type === 'zone') return k(ctN(c.views30), 'imps 30d') + k(c.viewablePct == null ? '-' : c.viewablePct + '%', 'viewable') + k(ctN(c.clicks30), 'clicks') + k(ctN(c.credits), 'credits paid');
|
||||
if (r.type === 'ad') return k(ctN(d.spent) + ' / ' + ctN(d.budget), 'spent') + k(ctN(c.imps) + (c.impsNas ? ' +' + ctN(c.impsNas) : ''), 'views') + k(ctN(c.clicks), 'clicks');
|
||||
if (r.type === 'source' || r.type === 'postback') return k(ctN(c.sent), 'sent') + k(ctN(c.fails), 'fails');
|
||||
@@ -594,7 +600,7 @@
|
||||
+ '<td data-l="Created" class="small when">' + ctWhen(r.created) + '</td>'
|
||||
+ '<td data-l="Status"><span class="st ' + esc(r.live ? 'active' : (r.status === 'draft' || r.status === 'paused' ? r.status : 'out')) + '">' + esc(r.status) + '</span></td>'
|
||||
+ '<td data-l="Numbers" class="small ct-nums">' + ctNums(r) + '</td>'
|
||||
+ '<td class="act">' + (r.actions || []).map((a, j) => '<button type="button" class="btn small ' + (/^Pause/.test(a.label) ? 'sec' : '') + '" data-ctact="' + i + ':' + j + '">' + esc(a.label) + '</button>').join('') + (r.open && r.type !== 'page' ? ctA(r.open, 'Open') : '') + '</td></tr>').join('')
|
||||
+ '<td class="act">' + (r.actions || []).map((a, j) => '<button type="button" class="btn small ' + (/^Pause|offline$/.test(a.label) ? 'sec' : '') + '" data-ctact="' + i + ':' + j + '">' + esc(a.label) + '</button>').join('') + (r.open && r.type !== 'page' ? ctA(r.open, 'Open') : '') + '</td></tr>').join('')
|
||||
: '<tr><td colspan="7" class="muted">Nothing matches.</td></tr>');
|
||||
$('ctPager').innerHTML = d.pages > 1 ? '<button type="button" class="btn small sec" data-ctpage="' + (d.page - 1) + '"' + (d.page <= 1 ? ' disabled' : '') + '>← Newer</button><span class="small muted">Page ' + d.page + ' of ' + d.pages + ' · ' + d.per + ' per page</span><button type="button" class="btn small sec" data-ctpage="' + (d.page + 1) + '"' + (d.page >= d.pages ? ' disabled' : '') + '>Older →</button>' : '';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
// LinkSpin Banner Spin builder (2026-10-18), the second view of the Links screen. One image address + one click address
|
||||
// rotate up to 25 banners, each with its own target. API: /api/my/bannerspins (bannerspin.js on the server). Uses the
|
||||
// Control Room shell (cr-shell.js) and the hours editor links.js shares as window.LSHours.
|
||||
(function () {
|
||||
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog;
|
||||
let D = null, SPINS = [], SEL = null, STATS = {}, ROT = [], SRC = [], HOST = '', PEND = null, FB = null, BHE = null, HRS = null;
|
||||
const MAXB = () => (D && D.maxBytes) || 153600;
|
||||
const kb = n => Math.max(1, Math.round((n || 0) / 1024)) + ' KB';
|
||||
const sizeOf = s => s.size.split('x').map(Number);
|
||||
const pct = v => v == null ? '-' : v + '%';
|
||||
const health = s => s.adminOff ? { cls: 'bad', t: 'OFFLINE (ADMIN)' } : s.paused ? { cls: 'warn', t: 'PAUSED' } : !s.banners.some(b => b.active && !b.adminOff) ? { cls: 'bad', t: 'NO LIVE BANNER' } : { cls: 'ok', t: 'LIVE' };
|
||||
const base = () => 'https://' + (HOST || location.host);
|
||||
const imgUrl = s => base() + '/i/' + s.code + '.gif', clickUrl = s => base() + '/c/' + s.code, jsUrl = s => base() + '/s/' + s.code + '.js';
|
||||
|
||||
// ── view switch: Spin links | Banner Spins (hash #b or #b<id> opens this view) ──
|
||||
function setView(v) {
|
||||
const on = v === 'banners';
|
||||
$('vsw').querySelectorAll('button').forEach(b => b.classList.toggle('on', b.dataset.v === v));
|
||||
$('ws').hidden = on; $('bsWs').hidden = !on;
|
||||
const nb = $('newBtn'), bn = $('bsNewBtn'); if (nb) nb.hidden = on; if (bn) bn.hidden = !on;
|
||||
if (on) { if (!/^#b/.test(location.hash)) history.replaceState(null, '', '#b' + (SEL || '')); load(true); }
|
||||
else { if (/^#b/.test(location.hash)) history.replaceState(null, '', location.pathname); if (window.LSLinks) window.LSLinks.reload(); }
|
||||
}
|
||||
$('vsw').querySelectorAll('button').forEach(b => b.addEventListener('click', () => setView(b.dataset.v)));
|
||||
|
||||
async function load(keep) {
|
||||
try { D = await CR.get('/api/my/bannerspins'); } catch (e) { toast(e.message, true); return; }
|
||||
SPINS = (D.spins || []).slice().sort((a, b) => (b.imps30 || 0) - (a.imps30 || 0));
|
||||
try { ROT = (await CR.get('/api/my/rotations')).rotations || []; } catch (e) { ROT = []; }
|
||||
try { SRC = (await CR.get('/api/my/sources')).sources || []; } catch (e) { SRC = []; }
|
||||
const hs = D.hosts || []; if (!HOST || !hs.some(h => h.host === HOST)) { const soc = hs.find(h => h.channel === 'social'); HOST = (soc || hs[0] || { host: location.host }).host; }
|
||||
renderTier(); renderList();
|
||||
if (!$('bsWs').hidden) CR.sub(SPINS.length + ' Banner Spin' + (SPINS.length === 1 ? '' : 's') + ' · ' + fmt(SPINS.reduce((n, x) => n + (x.imps30 || 0), 0)) + ' views in 30 days');
|
||||
const want = SEL != null ? SEL : (Number(location.hash.replace(/^#b/, '')) || null);
|
||||
if (want && SPINS.find(x => x.id === want)) return select(want, keep);
|
||||
if (!SPINS.length) { SEL = null; $('bsNoSel').hidden = false; $('bsSel').hidden = true; $('bsWs').classList.remove('focus'); return; }
|
||||
select(SPINS[0].id, true);
|
||||
}
|
||||
function renderTier() {
|
||||
const t = D.tier || {}; const used = SPINS.length;
|
||||
let h;
|
||||
if (!t.ok) h = '<div class="tierbar"><span class="tag warn">LOCKED</span><span>' + esc(t.reason || 'Banner Spin opens with your own package of $25 or more.') + '</span><a class="btn sm" href="/credits">Buy a package</a></div>';
|
||||
else h = '<div class="tierbar"><span class="tag ok">' + esc(t.label) + '</span><span><b>' + used + ' of ' + t.spins + '</b> Banner Spins, up to <b>' + t.banners + '</b> banners each.</span></div>'
|
||||
+ (t.next ? '<div class="muted" style="margin-top:4px">' + esc(t.next.label) + ': ' + t.next.spins + ' Banner Spins x ' + t.next.banners + ' banners, at ' + esc(t.next.need) + '.</div>' : '<div class="muted" style="margin-top:4px">Top tier. Free add-on, nothing to pay.</div>');
|
||||
if (D.off) h += '<div class="note" style="margin-top:6px">Banner Spin is switched off for maintenance. Your placements show a blank image until it is back.</div>';
|
||||
$('bsTier').innerHTML = h;
|
||||
$('bsNoSelText').textContent = t.ok ? 'One image address and one click address that rotate up to ' + t.banners + ' banners, each with its own target. Put it on your site, a forum signature or a safelist once; change the banners here any time.' : (t.reason || '') + ' Your tier then sets how many you can make: Starter 2 x 5 banners, Builder 5 x 15, Leader 10 x 25.';
|
||||
$('bsNewBtn2').hidden = !t.ok; const nb = $('bsNewBtn'); if (nb) nb.disabled = !t.ok || used >= t.spins;
|
||||
}
|
||||
function renderList() {
|
||||
$('bsCount').textContent = SPINS.length + ' Banner Spin' + (SPINS.length === 1 ? '' : 's');
|
||||
$('bsItems').innerHTML = SPINS.length ? SPINS.map(s => { const h = health(s); return '<div class="item' + (s.id === SEL ? ' on' : '') + '" data-id="' + s.id + '" role="button" tabindex="0"><div><div class="nm">' + esc(s.name) + (h.cls !== 'ok' ? ' <span class="tag ' + h.cls + '">' + h.t + '</span>' : '') + '</div><div class="cd">' + esc(s.size) + ' · ' + s.banners.length + ' banner' + (s.banners.length === 1 ? '' : 's') + ' · /i/' + esc(s.code) + '</div></div><div class="rt"><span class="n">' + fmt(s.imps30) + '</span><span class="muted" style="font-size:10px">views 30 d</span></div></div>'; }).join('')
|
||||
: '<div class="empty"><div class="muted">No Banner Spins yet.</div></div>';
|
||||
$('bsItems').querySelectorAll('.item').forEach(el => { const go = () => select(Number(el.dataset.id)); el.addEventListener('click', go); el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } }); });
|
||||
}
|
||||
const cur = () => SPINS.find(x => x.id === SEL) || null;
|
||||
function select(id, quiet) {
|
||||
SEL = id; const s = cur(); if (!s) return;
|
||||
if (location.hash !== '#b' + id) history.replaceState(null, '', '#b' + id);
|
||||
$('bsNoSel').hidden = true; $('bsSel').hidden = false; $('bsWs').classList.add('focus');
|
||||
$('bsItems').querySelectorAll('.item').forEach(el => el.classList.toggle('on', Number(el.dataset.id) === id));
|
||||
$('bsName').textContent = s.name; $('bsSize').textContent = s.size;
|
||||
const h = health(s); $('bsLive').innerHTML = '<span class="' + h.cls + '"><span class="dot"></span>' + h.t + '</span>';
|
||||
$('bsPause').textContent = s.paused ? 'Resume' : 'Pause';
|
||||
$('bsHoursChip').textContent = LSHours.chip(s.hours, s.tz); $('bsHoursChip').classList.toggle('set', !!s.hours);
|
||||
$('bsOffNote').hidden = !s.adminOff; if (s.adminOff) $('bsOffNote').textContent = 'LinkSpin took this Banner Spin offline' + (s.adminNote ? ' (' + s.adminNote + ')' : '') + '. Placements show a blank image and clicks go to the fallback. Ask on Help if you think this is a mistake.';
|
||||
renderTiles(s, STATS[id]); renderBanners(s); renderSettings(s); renderCodes(s); renderAddLimit(s);
|
||||
if (!quiet) window.scrollTo({ top: 0 });
|
||||
loadStats(id);
|
||||
}
|
||||
function renderTiles(s, st) {
|
||||
const t = st && st.totals;
|
||||
$('bsTiles').innerHTML = [
|
||||
CR.tile({ k: 'Views, 30 d', v: fmt(s.imps30), hi: true }), CR.tile({ k: 'Views, all time', v: fmt(s.imps) }), CR.tile({ k: 'Clicks', v: fmt(s.clicks) }),
|
||||
CR.tile({ k: 'CTR', v: t && t.ctr != null ? t.ctr + '%' : (s.imps ? (Math.round(s.clicks / s.imps * 10000) / 100) + '%' : '-') }),
|
||||
CR.tile({ k: 'Click match rate', v: t ? pct(t.matchRate) : (s.clicks ? Math.round(s.matched / s.clicks * 100) + '%' : '-') }), CR.tile({ k: 'Conversions', v: fmt(s.conversions) }),
|
||||
CR.tile({ k: 'Live banners', v: s.banners.filter(b => b.active && !b.adminOff).length + ' / ' + s.banners.length })].join('');
|
||||
}
|
||||
const targetText = b => { if (b.link) { const r = ROT.find(x => x.id === b.link); return r ? 'Spin link: ' + r.name + ' (/r/' + r.code + ')' : 'Spin link (deleted)'; } return b.target; };
|
||||
function renderBanners(s) {
|
||||
const total = s.banners.filter(b => b.active && !b.adminOff).reduce((n, b) => n + b.weight, 0) || 1;
|
||||
const [W, H] = sizeOf(s);
|
||||
$('bsRows').innerHTML = s.banners.length ? s.banners.map(b => { const share = b.active && !b.adminOff ? Math.round(b.weight / total * 100) : 0;
|
||||
return '<div class="rw" data-bid="' + b.id + '"><div style="display:grid;gap:5px;min-width:0"><img class="bthumb" src="' + esc(b.image) + '" alt="" width="' + W + '" height="' + H + '" loading="lazy" referrerpolicy="no-referrer">'
|
||||
+ '<div style="font-weight:700">' + esc(b.label || 'Banner ' + b.id) + (b.hours ? ' <button class="hchip set" type="button" data-bh="' + b.id + '">' + esc(LSHours.text(b.hours)) + '</button>' : '') + '</div>'
|
||||
+ '<div class="mono muted" style="font-size:11px;overflow-wrap:anywhere">' + esc(targetText(b)) + '</div>'
|
||||
+ '<div style="font-size:11px">' + (b.w ? '<span class="' + (b.warn ? 'wm' : 'okm') + '">' + b.w + 'x' + b.h + (b.bytes ? ', ' + kb(b.bytes) : '') + (b.warn ? ', not ' + esc(s.size) : ', fits') + '</span>' : '<span class="muted">pasted image, size not checked</span>') + '</div></div>'
|
||||
+ '<div class="wrow"><div class="bar" style="width:60px"><i style="width:' + share + '%"></i></div><input class="field mono" type="number" min="1" max="100" value="' + b.weight + '" data-w="' + b.id + '" aria-label="Weight"><span class="mono muted" style="font-size:11px">' + share + '%</span></div>'
|
||||
+ '<span class="r num"><span class="ml">Views </span>' + fmt(b.imps) + '</span><span class="r num"><span class="ml">Clicks </span>' + fmt(b.clicks) + '</span>'
|
||||
+ '<span class="tag ' + (b.adminOff ? 'bad' : b.active ? 'ok' : 'dim') + '">' + (b.adminOff ? 'OFFLINE' : b.active ? 'LIVE' : 'PAUSED') + '</span>'
|
||||
+ '<span style="display:flex;gap:6px;justify-content:flex-end"><button class="btn sm" type="button" data-bh="' + b.id + '" title="Hours for this banner" aria-label="Hours for this banner"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg></button><button class="btn sm" type="button" data-t="' + b.id + '">' + (b.active ? 'Pause' : 'Resume') + '</button><button class="btn sm danger" type="button" data-x="' + b.id + '" aria-label="Remove">×</button></span></div>'
|
||||
+ (BHE && BHE.sid === s.id && BHE.bid === b.id ? '<div class="rw edit" data-he="' + b.id + '"></div>' : ''); }).join('')
|
||||
: '<div class="rw"><span class="muted">No banners yet. Add the first one below. Until then every placement shows the fallback.</span></div>';
|
||||
$('bsFoot').textContent = 'weights are shares of the rotation · ' + (s.mode === 'visitor' ? 'one banner per visitor per day' : 'a fresh pick on every page view') + ' · fallback: ' + (s.fallback || 'none set') + (s.fallbackImps ? ' · fallback shown ' + fmt(s.fallbackImps) + ' times' : '');
|
||||
const heHost = $('bsRows').querySelector('[data-he]');
|
||||
if (heHost) { const b = s.banners.find(q => q.id === Number(heHost.dataset.he));
|
||||
LSHours.editor(heHost, { hours: b.hours, rotTz: s.tz, onCancel: () => { BHE = null; renderBanners(s); }, onSave: async hours => { try { await api('/api/my/bannerspins/' + s.id + '/banner/' + b.id, { hours }); BHE = null; toast(hours ? 'Hours saved' : 'Banner is always on'); load(true); } catch (e) { toast(e.message, true); } } }); }
|
||||
$('bsRows').querySelectorAll('[data-bh]').forEach(x => x.addEventListener('click', () => { const bid = Number(x.dataset.bh); BHE = BHE && BHE.bid === bid ? null : { sid: s.id, bid }; renderBanners(s); }));
|
||||
$('bsRows').querySelectorAll('[data-w]').forEach(i => i.addEventListener('change', async () => { try { await api('/api/my/bannerspins/' + s.id + '/banner/' + i.dataset.w, { weight: i.value }); toast('Weight saved'); load(true); } catch (e) { toast(e.message, true); } }));
|
||||
$('bsRows').querySelectorAll('[data-t]').forEach(x => x.addEventListener('click', async () => { const b = s.banners.find(q => q.id === Number(x.dataset.t)); try { await api('/api/my/bannerspins/' + s.id + '/banner/' + b.id, { active: !b.active }); load(true); } catch (e) { toast(e.message, true); } }));
|
||||
$('bsRows').querySelectorAll('[data-x]').forEach(x => x.addEventListener('click', async () => { if (!await dialog({ title: 'Remove this banner?', text: 'Its numbers stay in the stats.', ok: 'Remove', danger: true })) return; try { await api('/api/my/bannerspins/' + s.id + '/banner/' + x.dataset.x, { remove: true }); toast('Removed'); load(true); } catch (e) { toast(e.message, true); } }));
|
||||
// the "a click goes to" picker: a page address, or one of the member's spin links
|
||||
const sel = $('bsTgtKind'); const was = sel.value;
|
||||
sel.innerHTML = '<option value="url">A page address</option>' + ROT.map(r => '<option value="' + r.id + '">Spin link: ' + esc(r.name) + '</option>').join('');
|
||||
if ([...sel.options].some(o => o.value === was)) sel.value = was; $('bsTgtUrlWrap').hidden = sel.value !== 'url';
|
||||
}
|
||||
function renderAddLimit(s) {
|
||||
const t = D.tier || {}; const full = t.ok && s.banners.length >= t.banners;
|
||||
$('bsAddBtn').disabled = !t.ok || full;
|
||||
$('bsAddNote').innerHTML = !t.ok ? esc(t.reason || '') : full ? 'This Banner Spin holds ' + t.banners + ' banners on your ' + esc(t.label) + ' tier.' + (t.next ? ' ' + esc(t.next.label) + ' (' + esc(t.next.need) + ') holds ' + t.next.banners + '.' : '') : s.banners.length + ' of ' + t.banners + ' banners · uploads count toward your 10 files a day';
|
||||
}
|
||||
|
||||
// ── image checks: real size preview, wrong size / over limit warnings ──
|
||||
function measure(src) { return new Promise(res => { const im = new Image(); im.onload = () => res({ w: im.naturalWidth, h: im.naturalHeight }); im.onerror = () => res(null); im.referrerPolicy = 'no-referrer'; im.src = src; }); }
|
||||
function checkLine(s, d, bytes, kind) {
|
||||
const [W, H] = sizeOf(s); const out = [];
|
||||
if (kind && !/^image\/(png|jpeg|gif)$/.test(kind)) out.push('<span class="bm">Use a JPG, PNG or GIF file.</span>');
|
||||
if (bytes != null && bytes > MAXB()) out.push('<span class="bm">' + kb(bytes) + ' is over the 150 KB limit. Save it smaller (fewer colors or frames for a GIF).</span>');
|
||||
if (d && (d.w !== W || d.h !== H)) out.push('<span class="wm">This image is ' + d.w + 'x' + d.h + '; this Banner Spin is ' + W + 'x' + H + '. It would be stretched to fit. Use a ' + W + 'x' + H + ' image.</span>');
|
||||
if (d && d.w === W && d.h === H) out.push('<span class="okm">' + W + 'x' + H + (bytes != null ? ', ' + kb(bytes) : '') + ': fits this Banner Spin.</span>');
|
||||
if (!d) out.push('<span class="bm">That image did not load. Check the address.</span>');
|
||||
return out.join('<br>');
|
||||
}
|
||||
async function preview(host, s, src, bytes, kind) {
|
||||
const [W, H] = sizeOf(s);
|
||||
if (!src) { host.innerHTML = '<div class="bframe" style="width:' + W + 'px;height:' + H + 'px">' + W + 'x' + H + '</div><div class="muted" style="font-size:11px">Preview at real size</div>'; return null; }
|
||||
const d = await measure(src);
|
||||
host.innerHTML = (d ? '<img src="' + esc(src) + '" alt="" style="width:' + W + 'px;height:' + H + 'px" referrerpolicy="no-referrer">' : '') + '<div style="font-size:12px">' + checkLine(s, d, bytes, kind) + '</div><div class="muted" style="font-size:11px">Preview at real size, ' + W + 'x' + H + '</div>';
|
||||
return d;
|
||||
}
|
||||
async function pickFile(input, host, s, state) {
|
||||
const f = input.files && input.files[0]; if (!f) { state.file = null; return preview(host, s, null); }
|
||||
state.file = f; state.url = '';
|
||||
const u = URL.createObjectURL(f); const d = await preview(host, s, u, f.size, f.type); state.d = d; state.ok = !!d && f.size <= MAXB() && /^image\/(png|jpeg|gif)$/.test(f.type);
|
||||
}
|
||||
async function upload(f, s) {
|
||||
const r = await (await fetch('/api/my/bannerspins/upload?size=' + encodeURIComponent(s.size), { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json();
|
||||
if (r.error) throw new Error(r.error); return r;
|
||||
}
|
||||
// add a banner: upload first when a file is chosen, then save
|
||||
$('bsFile').addEventListener('change', () => { const s = cur(); if (!s) return; $('bsImgUrl').value = ''; PEND = PEND || {}; pickFile($('bsFile'), $('bsPrev'), s, PEND); });
|
||||
$('bsImgUrl').addEventListener('change', async () => { const s = cur(); if (!s) return; $('bsFile').value = ''; PEND = { url: $('bsImgUrl').value.trim() }; PEND.d = await preview($('bsPrev'), s, PEND.url || null); PEND.ok = !!PEND.d; });
|
||||
$('bsTgtKind').addEventListener('change', () => { $('bsTgtUrlWrap').hidden = $('bsTgtKind').value !== 'url'; });
|
||||
$('bsAddBtn').addEventListener('click', async () => {
|
||||
const s = cur(); if (!s) return; const P = PEND || {};
|
||||
if (!P.file && !P.url) { toast('Choose an image to upload or paste an image address', true); return; }
|
||||
if (P.file && !P.ok) { toast('Fix the image first (type, 150 KB limit)', true); return; }
|
||||
const body = { weight: $('bsWeight').value, label: $('bsLabel').value };
|
||||
if ($('bsTgtKind').value === 'url') { body.target = $('bsTgtUrl').value.trim(); if (!body.target) { $('bsTgtUrl').focus(); toast('Where should a click go?', true); return; } } else body.link = $('bsTgtKind').value;
|
||||
const b = $('bsAddBtn'); b.disabled = true;
|
||||
try {
|
||||
if (P.file) { const up = await upload(P.file, s); body.image = up.url; } else { body.image = P.url; if (P.d) { body.w = P.d.w; body.h = P.d.h; } }
|
||||
const r = await api('/api/my/bannerspins/' + s.id + '/banner', body);
|
||||
toast(r.warn ? 'Added. ' + r.warn : 'Banner added', !!r.warn);
|
||||
PEND = null; $('bsFile').value = ''; $('bsImgUrl').value = ''; $('bsLabel').value = ''; $('bsTgtUrl').value = ''; preview($('bsPrev'), s, null);
|
||||
await load(true);
|
||||
} catch (e) { toast(e.message, true); }
|
||||
b.disabled = false; renderAddLimit(cur() || s);
|
||||
});
|
||||
|
||||
// ── settings ──
|
||||
function renderSettings(s) {
|
||||
document.querySelectorAll('input[name="bsMode"]').forEach(r => { r.checked = r.value === (s.mode || 'weight'); });
|
||||
$('bsSrc').innerHTML = '<option value="">None</option>' + SRC.map(x => '<option value="' + x.id + '"' + (x.id === s.sourceId ? ' selected' : '') + '>' + esc(x.name) + (x.site ? ' · ' + esc(x.site) : '') + '</option>').join('');
|
||||
if (document.activeElement !== $('bsFallback')) $('bsFallback').value = s.fallback || '';
|
||||
if (!FB || FB.sid !== s.id) { FB = { sid: s.id }; $('bsFbFile').value = ''; $('bsFbUrl').value = /^https:/.test(s.fallbackImage || '') ? s.fallbackImage : ''; preview($('bsFbPrev'), s, s.fallbackImage || null); }
|
||||
$('bsFbClear').hidden = !s.fallbackImage;
|
||||
if (!(HRS && HRS.sid === s.id && HRS.dirty)) { HRS = { sid: s.id, dirty: false };
|
||||
LSHours.editor($('bsHours'), { hours: s.hours, tz: s.tz || 'visitor', onCancel: () => { HRS = null; renderSettings(s); }, onSave: async (hours, tz) => { try { await api('/api/my/bannerspins/' + s.id, { hours, tz }); HRS = null; toast(hours ? 'Hours saved' : 'Banner Spin is always on'); load(true); } catch (e) { toast(e.message, true); } } });
|
||||
$('bsHours').addEventListener('pointerdown', () => { if (HRS) HRS.dirty = true; }, { once: true }); }
|
||||
}
|
||||
document.querySelectorAll('input[name="bsMode"]').forEach(r => r.addEventListener('change', async () => { const s = cur(); if (!s || !r.checked) return; try { await api('/api/my/bannerspins/' + s.id, { mode: r.value }); toast(r.value === 'visitor' ? 'One banner per visitor per day' : 'Random by weight on every view'); load(true); } catch (e) { toast(e.message, true); } }));
|
||||
$('bsSrc').addEventListener('change', async () => { const s = cur(); if (!s) return; try { await api('/api/my/bannerspins/' + s.id, { sourceId: $('bsSrc').value }); toast($('bsSrc').value ? 'Source saved' : 'Source removed'); load(true); } catch (e) { toast(e.message, true); } });
|
||||
$('bsFbFile').addEventListener('change', () => { const s = cur(); if (!s) return; $('bsFbUrl').value = ''; FB = { sid: s.id }; pickFile($('bsFbFile'), $('bsFbPrev'), s, FB); });
|
||||
$('bsFbUrl').addEventListener('change', async () => { const s = cur(); if (!s) return; $('bsFbFile').value = ''; FB = { sid: s.id, url: $('bsFbUrl').value.trim() }; FB.d = await preview($('bsFbPrev'), s, FB.url || null); });
|
||||
$('bsFbSave').addEventListener('click', async () => {
|
||||
const s = cur(); if (!s) return; const body = { fallback: $('bsFallback').value.trim() };
|
||||
try {
|
||||
if (FB && FB.file) { if (!FB.ok) { toast('Fix the fallback image first', true); return; } body.fallbackImage = (await upload(FB.file, s)).url; }
|
||||
else if (FB && FB.url) body.fallbackImage = FB.url;
|
||||
await api('/api/my/bannerspins/' + s.id, body); FB = null; toast('Fallback saved'); load(true);
|
||||
} catch (e) { toast(e.message, true); }
|
||||
});
|
||||
$('bsFbClear').addEventListener('click', async () => { const s = cur(); if (!s) return; try { await api('/api/my/bannerspins/' + s.id, { fallbackImage: '' }); FB = null; toast('Fallback image removed'); load(true); } catch (e) { toast(e.message, true); } });
|
||||
|
||||
// ── the four embeds ──
|
||||
function renderCodes(s) {
|
||||
const hs = (D && D.hosts) || [];
|
||||
$('bsHost').innerHTML = hs.map(h => '<option value="' + esc(h.host) + '"' + (h.host === HOST ? ' selected' : '') + '>' + esc(h.host) + ' · ' + esc(h.label || h.channel) + '</option>').join('');
|
||||
const hh = hs.find(h => h.host === HOST); $('bsHostNote').textContent = hh && hh.note ? 'Meant for: ' + hh.note : '';
|
||||
const [W, H] = sizeOf(s); const src = SRC.find(x => x.id === s.sourceId);
|
||||
const qs = src && (src.params || []).length ? '?' + src.params.map(p => p.key + '=' + p.token).join('&') : '';
|
||||
const blocks = [
|
||||
['Image address + click address', 'For any place that asks for an image URL and a link URL (safelists, traffic exchanges, forum profiles).', imgUrl(s) + '\n' + clickUrl(s) + qs],
|
||||
['HTML snippet', 'For your own website or blog.', '<a href="' + clickUrl(s) + qs + '" target="_blank" rel="noopener"><img src="' + imgUrl(s) + '" width="' + W + '" height="' + H + '" alt="" style="border:0"></a>'],
|
||||
['Script tag (exact match)', 'Writes the banner and its own click link together, so every click lands on the right target. Use it wherever scripts are allowed.', '<script src="' + jsUrl(s) + '"></script>'],
|
||||
['Forum BBCode', 'For forum signatures and posts.', '[url=' + clickUrl(s) + qs + '][img]' + imgUrl(s) + '[/img][/url]']];
|
||||
$('bsCodes').innerHTML = blocks.map(([t, n, code], i) => '<div class="panel code-blk"><div class="hd2"><b>' + esc(t) + '</b><button class="btn sm pri" type="button" data-cp="' + i + '">Copy</button></div><div class="muted" style="font-size:12px">' + esc(n) + '</div><pre id="bsCode-' + i + '">' + esc(code) + '</pre>'
|
||||
+ (i === 0 ? '<div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn sm" type="button" data-cp1="img">Copy image address</button><button class="btn sm" type="button" data-cp1="click">Copy click address</button></div>' : '') + '</div>').join('')
|
||||
+ (src ? '<div class="muted" style="font-size:12px">The click address carries ' + esc(src.name) + '\'s macros, so its conversions fire that source\'s postback.</div>' : '');
|
||||
$('bsCodes').querySelectorAll('[data-cp]').forEach(b => b.addEventListener('click', () => CR.copy($('bsCode-' + b.dataset.cp).textContent)));
|
||||
$('bsCodes').querySelectorAll('[data-cp1]').forEach(b => b.addEventListener('click', () => CR.copy(b.dataset.cp1 === 'img' ? imgUrl(s) : clickUrl(s) + qs)));
|
||||
}
|
||||
$('bsHost').addEventListener('change', () => { HOST = $('bsHost').value; const s = cur(); if (s) renderCodes(s); });
|
||||
|
||||
// ── stats ──
|
||||
async function loadStats(id) {
|
||||
let st = STATS[id]; if (!st) { try { st = await CR.get('/api/my/bannerspins/' + id + '/stats'); } catch (e) { return; } STATS[id] = st; setTimeout(() => { delete STATS[id]; }, 30000); }
|
||||
if (SEL !== id) return; const s = cur(); if (s) renderTiles(s, st);
|
||||
const row = (name, o, extra) => '<div class="rw"><span style="overflow-wrap:anywhere">' + name + '</span><span class="r num">' + fmt(o.imps) + '</span><span class="r num">' + fmt(o.clicks) + '</span><span class="r num">' + (o.ctr == null ? '-' : o.ctr + '%') + '</span><span class="r num">' + (o.matchRate == null ? '-' : o.matchRate + '%') + '</span><span class="r num">' + (extra == null ? '' : fmt(extra)) + '</span></div>';
|
||||
$('bsStB').innerHTML = st.banners.length ? st.banners.map(b => row('<img src="' + esc(b.image) + '" alt="" style="max-height:28px;max-width:120px;vertical-align:middle;margin-right:6px" referrerpolicy="no-referrer">' + esc(b.label || 'Banner ' + b.id), b, b.conversions)).join('') + (st.fallback.imps || st.fallback.clicks ? row('<span class="muted">Fallback</span>', Object.assign({ matchRate: null }, st.fallback), null) : '') : '<div class="rw"><span class="muted">No banners yet.</span></div>';
|
||||
$('bsStP').innerHTML = st.placements.length ? st.placements.map(p => row(esc(p.host), p, null)).join('') : '<div class="rw"><span class="muted">No views yet. Put the code on a page and load it.</span></div>';
|
||||
const days = st.days || []; const dmax = Math.max(1, ...days.map(d => d.imps));
|
||||
$('bsDayBars').style.gridTemplateColumns = 'repeat(' + Math.max(1, days.length) + ',minmax(0,1fr))';
|
||||
$('bsDayBars').innerHTML = days.map(d => '<i style="height:' + Math.round(d.imps / dmax * 100) + '%" title="' + d.day + ' · ' + d.imps + ' views, ' + d.clicks + ' clicks"></i>').join('');
|
||||
$('bsDayAxis').innerHTML = days.length ? '<span>' + days[0].day + '</span><span>' + days[days.length - 1].day + '</span>' : '<span class="muted">no views recorded yet</span>';
|
||||
const t = st.totals; $('bsStNote').textContent = 'Views are counted on the server: bots and link previews are left out and one visitor reloading counts once a minute per banner. Matched = clicks we could tie to the banner that visitor saw (' + fmt(t.matched) + ' matched, ' + fmt(t.unmatched) + ' went to the fallback). About ' + fmt(t.uniquesSampled) + ' unique visitors (sampled).';
|
||||
}
|
||||
|
||||
// ── header actions ──
|
||||
async function newSpin() {
|
||||
const t = D && D.tier; if (!t || !t.ok) { toast((t && t.reason) || 'Banner Spin is locked', true); return; }
|
||||
if (SPINS.length >= t.spins) { toast('Your ' + t.label + ' tier holds ' + t.spins + ' Banner Spins', true); return; }
|
||||
let size = '468x60';
|
||||
const p = dialog({ title: 'New Banner Spin', text: 'One size per Banner Spin. Every banner in it should be that exact size.', html: '<label class="lbl">Size<select class="field mono" id="bsNewSize">' + ((D && D.sizes) || ['468x60']).map(z => '<option value="' + z + '"' + (z === size ? ' selected' : '') + '>' + z + '</option>').join('') + '</select></label>', fields: [{ k: 'name', label: 'Name (only you see it)', placeholder: 'Forum signature', max: 80 }, { k: 'fallback', label: 'Fallback page, where unmatched clicks go (you can set it later)', placeholder: 'https://', mono: true, type: 'url' }], ok: 'Create' });
|
||||
const ns = $('bsNewSize'); if (ns) ns.addEventListener('change', () => { size = ns.value; });
|
||||
const v = await p; if (!v || !v.name.trim()) return;
|
||||
try { const r = await api('/api/my/bannerspins', { name: v.name, size, fallback: v.fallback }); SEL = r.spin.id; toast('Banner Spin created. Add your banners.'); await load(true); } catch (e) { toast(e.message, true); }
|
||||
}
|
||||
const nb = $('bsNewBtn'); if (nb) nb.addEventListener('click', newSpin); $('bsNewBtn2').addEventListener('click', newSpin);
|
||||
$('bsBack').addEventListener('click', () => $('bsWs').classList.remove('focus'));
|
||||
$('bsBack').hidden = !window.matchMedia('(max-width:760px)').matches;
|
||||
$('bsRename').addEventListener('click', async () => { const s = cur(); if (!s) return; const v = await dialog({ title: 'Rename', fields: [{ k: 'name', label: 'Name', value: s.name, max: 80 }], ok: 'Save' }); if (!v || !v.name.trim()) return; try { await api('/api/my/bannerspins/' + s.id, { name: v.name }); load(true); } catch (e) { toast(e.message, true); } });
|
||||
$('bsPause').addEventListener('click', async () => { const s = cur(); if (!s) return; try { await api('/api/my/bannerspins/' + s.id, { paused: !s.paused }); toast(s.paused ? 'Live again' : 'Paused: placements show the fallback'); load(true); } catch (e) { toast(e.message, true); } });
|
||||
$('bsDel').addEventListener('click', async () => { const s = cur(); if (!s) return; if (!await dialog({ title: 'Delete ' + s.name + '?', text: 'Every placement using this image and click address stops working. This cannot be undone.', ok: 'Delete', danger: true })) return; try { await api('/api/my/bannerspins/' + s.id, { remove: true }); SEL = null; history.replaceState(null, '', '#b'); toast('Deleted'); load(); } catch (e) { toast(e.message, true); } });
|
||||
$('bsHoursChip').addEventListener('click', () => { showTab('settings'); const h = $('bsHours'); if (h.scrollIntoView) h.scrollIntoView({ block: 'start', behavior: 'smooth' }); });
|
||||
const TABS = ['banners', 'settings', 'code', 'stats'];
|
||||
const showTab = name => { $('bsTabs').querySelectorAll('button').forEach(x => x.classList.toggle('on', x.dataset.tab === name)); TABS.forEach(t => { $('bs-' + t).hidden = t !== name; }); if (name === 'stats' && SEL) { delete STATS[SEL]; loadStats(SEL); } };
|
||||
$('bsTabs').querySelectorAll('button').forEach(b => b.addEventListener('click', () => showTab(b.dataset.tab)));
|
||||
// links.js owns the session check and calls ready() once signed in (one sign-in flow per page)
|
||||
let READY = false;
|
||||
window.BannerSpin = { setView, showTab, load, ready: () => { if (READY) return; READY = true; if (/^#b/.test(location.hash)) setView('banners'); setInterval(() => { if (!document.hidden && !$('bsWs').hidden) load(true); }, 60000); } };
|
||||
})();
|
||||
@@ -2,7 +2,7 @@
|
||||
(function () {
|
||||
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog;
|
||||
let ROT = [], HOSTS = [], SEL = null, STATS = {}, FILTER = '', PB = null, SRC = []; // SRC = the member's traffic sources (sources.js, 2026-10-12)
|
||||
CR.mount({ active: 'links', title: 'Links', sub: 'loading', actions: '<button class="btn pri" id="newBtn" type="button">+ New spin</button>' });
|
||||
CR.mount({ active: 'links', title: 'Links', sub: 'loading', actions: '<button class="btn pri" id="newBtn" type="button">+ New spin</button><button class="btn pri" id="bsNewBtn" type="button" hidden>+ New Banner Spin</button>' });
|
||||
const linkUrl = r => 'https://' + (HOSTS[0] || location.host) + '/r/' + r.code;
|
||||
const clicks7 = r => r.hits7 || 0;
|
||||
const health = r => r.paused ? { cls: 'warn', t: 'PAUSED' } : !r.destinations.some(d => d.active) ? { cls: 'bad', t: 'NO LIVE DESTINATION' } : { cls: 'ok', t: 'LIVE' };
|
||||
@@ -56,6 +56,7 @@
|
||||
host.heState = () => ({ hours: grid.map(d => d.join('')), tz }); // so a redraw can keep unsaved taps
|
||||
paint();
|
||||
}
|
||||
window.LSHours = { editor: hoursEditor, text: hoursText, chip: hoursChip }; // shared with the Banner Spin builder (banner-spin.js, 2026-10-18)
|
||||
// ── health readouts ──
|
||||
const ago = ts => { const s = Math.max(0, Math.round((Date.now() - ts) / 1000)); return s < 60 ? 'just now' : s < 3600 ? Math.round(s / 60) + ' min ago' : s < 86400 ? Math.round(s / 3600) + ' h ago' : Math.round(s / 86400) + ' d ago'; };
|
||||
const mdy = ts => new Date(ts).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
||||
@@ -74,8 +75,9 @@
|
||||
try { const lh = await api('/api/my/link-hosts'); LH = (lh && lh.hosts) || []; } catch (e) { LH = []; } // link domains by channel (domains.js, 2026-10-10)
|
||||
try { SRC = (await CR.get('/api/my/sources')).sources || []; } catch (e) { SRC = []; }
|
||||
const tot7 = ROT.reduce((n, x) => n + clicks7(x), 0);
|
||||
CR.sub(ROT.length + ' link' + (ROT.length === 1 ? '' : 's') + ' · ' + fmt(tot7) + ' clicks in 7 days');
|
||||
if (!/^#b/.test(location.hash)) CR.sub(ROT.length + ' link' + (ROT.length === 1 ? '' : 's') + ' · ' + fmt(tot7) + ' clicks in 7 days');
|
||||
renderList();
|
||||
if (/^#b/.test(location.hash)) { renderList(); return; } // the Banner Spin view owns the page (banner-spin.js)
|
||||
const want = SEL != null ? SEL : (Number(location.hash.slice(1)) || null);
|
||||
if (want != null && ROT.find(x => x.id === want)) return select(want, true);
|
||||
if (!ROT.length) { $('noSel').hidden = false; $('sel').hidden = true; SEL = null; }
|
||||
@@ -235,5 +237,6 @@
|
||||
catch (e) { toast(e.message, true); } b.disabled = false; b.textContent = 'Check now'; });
|
||||
$('pbNew').addEventListener('click', () => pbForm(null));
|
||||
$('backBtn').hidden = !window.matchMedia('(max-width:760px)').matches;
|
||||
CR.requireSession(() => { load(); loadPb(); setInterval(() => { if (!document.hidden) load(true); }, 60000); });
|
||||
window.LSLinks = { reload: () => load(true) }; // the Banner Spin view switches back here
|
||||
CR.requireSession(() => { load(); loadPb(); if (window.BannerSpin) window.BannerSpin.ready(); setInterval(() => { if (!document.hidden) load(true); }, 60000); });
|
||||
})();
|
||||
|
||||
+104
-1
@@ -52,10 +52,34 @@
|
||||
@media (max-width:760px){.ws{grid-template-columns:minmax(0,1fr)}.tabs{flex-wrap:wrap}.list{border-right:0;border-bottom:1px solid var(--line);max-height:44vh}.ws.focus .list{display:none}.ws:not(.focus) .detail{display:none}
|
||||
.dhead{padding:12px 16px}.dhead .code{flex:1 1 100%;word-break:break-all}.dbody{padding:12px 16px}
|
||||
.dest .rw{grid-template-columns:1fr}.dest .rw .r{text-align:left}#addRow{grid-template-columns:1fr}.tiles{grid-template-columns:repeat(2,minmax(0,1fr))}.kv{grid-template-columns:minmax(0,1fr) 50px 50px}}
|
||||
/* Banner Spin builder (2026-10-18) */
|
||||
.vsw{display:flex;gap:4px;padding:10px 16px 0;border-bottom:1px solid var(--line);background:var(--panel)}
|
||||
.vsw button{background:transparent;border:1px solid transparent;border-bottom:0;border-radius:8px 8px 0 0;color:var(--muted);font-family:var(--display);font-size:15px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;padding:7px 14px;cursor:pointer;margin-bottom:-1px}
|
||||
.vsw button.on{background:var(--bg,#f6f8fb);border-color:var(--line);color:var(--accent-hi)}
|
||||
.vsw .nw{font-family:var(--mono);font-size:9px;letter-spacing:.06em;color:var(--sig-2);margin-left:4px}
|
||||
.bsr .hd,.bsr .rw{grid-template-columns:minmax(0,2.4fr) 140px 80px 80px 96px 130px}
|
||||
.bsr .rw.edit{grid-template-columns:1fr;background:var(--panel-2)}
|
||||
.bthumb{display:block;max-width:100%;max-height:96px;width:auto;height:auto;border:1px solid var(--line);border-radius:4px;background:repeating-conic-gradient(#eef1f5 0 25%,#fff 0 50%) 50%/12px 12px}
|
||||
.bprev{display:grid;gap:6px;justify-items:start;overflow:auto;max-width:100%}
|
||||
.bprev img{display:block;max-width:100%;height:auto;border:1px dashed var(--line-strong);background:repeating-conic-gradient(#eef1f5 0 25%,#fff 0 50%) 50%/12px 12px}
|
||||
.bframe{border:1px dashed var(--line-strong);display:grid;place-items:center;color:var(--muted);font-family:var(--mono);font-size:11px;max-width:100%;background:var(--panel-2)}
|
||||
.addg{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:10px}
|
||||
.addg .full{grid-column:1/-1}
|
||||
.tgt{display:grid;grid-template-columns:180px minmax(0,1fr);gap:8px;align-items:end}
|
||||
.okm{color:var(--ok);font-size:12px} .wm{color:var(--warn);font-size:12px} .bm{color:var(--bad);font-size:12px}
|
||||
.code-blk{display:grid;gap:6px} .code-blk pre{margin:0;white-space:pre-wrap;overflow-wrap:anywhere;font-family:var(--mono);font-size:12px;background:var(--panel-2);border:1px solid var(--line);border-radius:6px;padding:8px 10px}
|
||||
.code-blk .hd2{display:flex;justify-content:space-between;align-items:center;gap:8px;flex-wrap:wrap}
|
||||
.tierbar{display:flex;gap:10px;align-items:center;flex-wrap:wrap;font-size:12.5px}
|
||||
.modes{display:grid;gap:8px} .modes label{display:flex;gap:8px;align-items:flex-start;cursor:pointer} .modes input{margin-top:3px}
|
||||
.bsr .ml{display:none}
|
||||
.st3 .hd,.st3 .rw{grid-template-columns:minmax(0,2fr) 90px 80px 70px 80px 70px}
|
||||
@media (max-width:900px){.bsr .ml{display:inline;color:var(--muted);font-size:11px}.bsr .rw .r{text-align:left}.bsr .hd,.st3 .hd{display:none}.bsr .rw{grid-template-columns:1fr 1fr}.st3 .rw{grid-template-columns:1fr 1fr 1fr}.addg{grid-template-columns:1fr}}
|
||||
@media (max-width:760px){.bsr .rw{grid-template-columns:1fr}.tgt{grid-template-columns:1fr}.vsw{padding:8px 10px 0}.vsw button{padding:6px 10px;font-size:14px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="page">
|
||||
<div class="vsw" id="vsw" role="tablist" aria-label="Link type"><button type="button" class="on" data-v="links" role="tab">Spin links</button><button type="button" data-v="banners" role="tab">Banner Spins<span class="nw">NEW</span></button></div>
|
||||
<div class="ws" id="ws">
|
||||
<div class="list">
|
||||
<div class="hd"><h2 id="listCount">Links</h2><span class="muted mono" id="listSort">by clicks, 7 days</span></div>
|
||||
@@ -127,6 +151,84 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ws" id="bsWs" hidden>
|
||||
<div class="list">
|
||||
<div class="hd"><h2 id="bsCount">Banner Spins</h2><span class="muted mono" id="bsSort">by views, 30 d</span></div>
|
||||
<div class="flt" id="bsTier" style="font-size:12px"></div>
|
||||
<div class="items" id="bsItems"></div>
|
||||
</div>
|
||||
<div class="detail">
|
||||
<div class="empty" id="bsNoSel"><div class="h-disp" style="font-size:18px">Banner Spin</div><div class="muted" id="bsNoSelText">One image address and one click address that rotate up to 25 banners, each with its own target. Put it on your site, a forum signature or a safelist once; change the banners here any time.</div><button class="btn pri" type="button" id="bsNewBtn2">+ New Banner Spin</button></div>
|
||||
<div id="bsSel" hidden>
|
||||
<div class="dhead">
|
||||
<button class="btn sm" type="button" id="bsBack" hidden>← Banner Spins</button>
|
||||
<h2 id="bsName">Banner Spin</h2>
|
||||
<span class="tag plain" id="bsSize"></span>
|
||||
<span class="mono" id="bsLive"></span>
|
||||
<button class="hchip" type="button" id="bsHoursChip" title="Hours this Banner Spin is on">Always on</button>
|
||||
<span class="grow"></span>
|
||||
<button class="btn sm" type="button" id="bsRename">Rename</button>
|
||||
<button class="btn sm" type="button" id="bsPause">Pause</button>
|
||||
<button class="btn sm danger" type="button" id="bsDel">Delete</button>
|
||||
</div>
|
||||
<div class="dbody">
|
||||
<div class="note" id="bsOffNote" hidden></div>
|
||||
<div class="tiles" id="bsTiles"></div>
|
||||
<div class="tabs" id="bsTabs">
|
||||
<button type="button" class="on" data-tab="banners">Banners</button>
|
||||
<button type="button" data-tab="settings">Settings</button>
|
||||
<button type="button" data-tab="code">Get the code</button>
|
||||
<button type="button" data-tab="stats">Stats</button>
|
||||
</div>
|
||||
<div id="bs-banners">
|
||||
<div class="tbl bsr">
|
||||
<div class="hd"><span>Banner and target</span><span>Weight</span><span class="r">Views</span><span class="r">Clicks</span><span>Status</span><span></span></div>
|
||||
<div id="bsRows"></div>
|
||||
<div class="ft" id="bsFoot"></div>
|
||||
</div>
|
||||
<div class="panel" style="margin-top:12px" id="bsAdd">
|
||||
<h2>Add a banner</h2>
|
||||
<div class="addg">
|
||||
<label class="lbl">Upload an image (JPG, PNG or GIF, animated is fine, up to 150 KB)<input class="field" id="bsFile" type="file" accept="image/png,image/jpeg,image/gif"></label>
|
||||
<label class="lbl">Or paste an image address<input class="field mono" id="bsImgUrl" type="url" placeholder="https://"></label>
|
||||
<div class="full bprev" id="bsPrev"></div>
|
||||
<div class="full tgt"><label class="lbl" style="margin:0">A click goes to<select class="field" id="bsTgtKind"><option value="url">A page address</option></select></label><label class="lbl" style="margin:0" id="bsTgtUrlWrap">Page address<input class="field mono" id="bsTgtUrl" type="url" placeholder="https://"></label></div>
|
||||
<label class="lbl">Label (only you see it)<input class="field" id="bsLabel" type="text" maxlength="60" placeholder="Gold offer, blue version"></label>
|
||||
<label class="lbl">Weight, 1 to 100<input class="field mono" id="bsWeight" type="number" min="1" max="100" value="10"></label>
|
||||
</div>
|
||||
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap"><button class="btn pri" type="button" id="bsAddBtn">Add banner</button><span class="muted" id="bsAddNote" style="font-size:12px"></span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="bs-settings" hidden>
|
||||
<div class="two">
|
||||
<div class="panel"><h2>Rotation</h2><div class="modes" id="bsModes">
|
||||
<label><input type="radio" name="bsMode" value="weight"><span><b>Random by weight</b><br><span class="muted">Every page view picks again. A banner with weight 20 shows twice as often as one with 10.</span></span></label>
|
||||
<label><input type="radio" name="bsMode" value="visitor"><span><b>One per visitor</b><br><span class="muted">Each visitor sees the same banner all day; different visitors get different banners by weight.</span></span></label></div></div>
|
||||
<div class="panel"><h2>Traffic source</h2><label class="lbl" style="margin:0">Network this Banner Spin runs on<select class="field" id="bsSrc"><option value="">None</option></select></label><div class="muted" style="font-size:12px">Conversions from its clicks fire that source's postback. Add the network's click macros to the click address (Get the code shows it).</div></div>
|
||||
</div>
|
||||
<div class="panel" style="margin-top:12px"><h2>Fallback</h2><div class="muted">Used when the Banner Spin is paused, outside its hours, or every banner is paused. A click we cannot match to a banner goes to the fallback page too.</div>
|
||||
<label class="lbl">Fallback page<input class="field mono" id="bsFallback" type="url" placeholder="https://"></label>
|
||||
<div class="addg"><label class="lbl">Fallback banner image (optional), upload<input class="field" id="bsFbFile" type="file" accept="image/png,image/jpeg,image/gif"></label><label class="lbl">or paste an image address<input class="field mono" id="bsFbUrl" type="url" placeholder="https://"></label></div>
|
||||
<div class="bprev" id="bsFbPrev"></div>
|
||||
<div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn pri" type="button" id="bsFbSave">Save fallback</button><button class="btn" type="button" id="bsFbClear">Remove fallback image</button></div>
|
||||
</div>
|
||||
<div class="panel" style="margin-top:12px"><h2>Hours this Banner Spin is on</h2><div class="muted">Outside these hours every placement shows the fallback banner. Each banner can have its own hours too (the clock button on its row).</div><div id="bsHours"></div></div>
|
||||
</div>
|
||||
<div id="bs-code" hidden>
|
||||
<div class="panel" style="padding:10px 12px"><div style="display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:end"><label class="lbl" style="margin:0">Link domain<select class="field" id="bsHost"></select></label><span class="muted mono" id="bsHostNote" style="font-size:11px"></span></div></div>
|
||||
<div id="bsCodes" style="display:grid;gap:10px;margin-top:10px"></div>
|
||||
<div class="note" style="margin-top:10px" id="bsGmail"><b>Using it in email?</b> Gmail fetches an image once through its own image proxy and keeps that copy, so Gmail readers stop seeing the rotation. For email, make a Banner Spin with a single banner and swap that banner when you want a change. Other mail apps load the image fresh on each open.</div>
|
||||
<div class="note" style="margin-top:10px"><b>Paid ad networks</b> copy your image to their own servers when you upload a creative, so it will not rotate there. Use the script tag or the image address on sites, blogs, forums and safelists that load the image from us.</div>
|
||||
</div>
|
||||
<div id="bs-stats" hidden>
|
||||
<div class="panel"><h2>By banner</h2><div class="tbl st3"><div class="hd"><span>Banner</span><span class="r">Views</span><span class="r">Clicks</span><span class="r">CTR</span><span class="r">Matched</span><span class="r">Conv</span></div><div id="bsStB"></div></div></div>
|
||||
<div class="panel" style="margin-top:12px"><h2>By placement (the page the banner sits on)</h2><div class="tbl st3"><div class="hd"><span>Placement</span><span class="r">Views</span><span class="r">Clicks</span><span class="r">CTR</span><span class="r">Matched</span><span></span></div><div id="bsStP"></div></div></div>
|
||||
<div class="panel" style="margin-top:12px"><h2>Views by day, Central time, last 30</h2><div class="bars" id="bsDayBars"></div><div class="axis" id="bsDayAxis"></div><div class="muted" style="font-size:11.5px" id="bsStNote"></div></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dbody" id="pbWrap" style="border-top:1px solid var(--line)">
|
||||
<div class="panel pbpanel">
|
||||
<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap"><h2>Postbacks</h2><span class="muted">Tell your tracker or traffic network when a click converts. Fired server to server with the click id that came in on the link.</span><span class="grow"></span><button class="btn sm" type="button" id="pbNew">+ Postback</button></div>
|
||||
@@ -136,6 +238,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261018c"></script>
|
||||
<script src="/assets/links.js?v=20261012a"></script>
|
||||
<script src="/assets/links.js?v=20261018bs"></script>
|
||||
<script src="/assets/banner-spin.js?v=20261018bs"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
// Banner Spin end-to-end test (2026-10-18). Boots server.js on its own port with a throwaway, seeded data dir (JSON store,
|
||||
// no DB, no mail key, devCode sign-in, no chain-writing keys), builds a Banner Spin with 3 banners through the Links
|
||||
// screen UI, then plays simulated visitors against /i/, /c/ and /s/ on a link domain and checks matching, fallback,
|
||||
// counters, headers, tier limits, URL tokens, conversions, the admin kill switch and the admin Member content pane.
|
||||
// node qa/bannerspin.mjs (from the site dir)
|
||||
// Env: PORT (default 8961), PW (playwright package dir), SHOTS (screenshot dir, default D:/tmp/banner-spin)
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import zlib from 'node:zlib';
|
||||
import crypto from 'node:crypto';
|
||||
import { spawn } from 'node:child_process';
|
||||
|
||||
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||
const PORT = Number(process.env.PORT || 8961);
|
||||
const BASE = 'http://127.0.0.1:' + PORT;
|
||||
const SHOTS = process.env.SHOTS || 'D:/tmp/banner-spin';
|
||||
const LINK = 'lnk-one.test', LINK2 = 'lnk-two.test';
|
||||
const ADMIN_PW = 'localtest-bs';
|
||||
const results = []; let failed = 0;
|
||||
const check = (ok, what, detail) => { results.push((ok ? 'PASS ' : 'FAIL ') + what + (detail ? ' :: ' + detail : '')); if (!ok) failed++; };
|
||||
|
||||
// ── tiny PNG writer: solid RGB, or noise (incompressible, for the 150 KB limit) ──
|
||||
function crc32(buf) { let c, crc = 0xffffffff; for (let n = 0; n < buf.length; n++) { c = (crc ^ buf[n]) & 0xff; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; crc = (crc >>> 8) ^ c; } return (crc ^ 0xffffffff) >>> 0; }
|
||||
function png(w, h, rgb, noise) {
|
||||
const chunk = (t, d) => { const l = Buffer.alloc(4); l.writeUInt32BE(d.length); const td = Buffer.concat([Buffer.from(t), d]); const c = Buffer.alloc(4); c.writeUInt32BE(crc32(td)); return Buffer.concat([l, td, c]); };
|
||||
const ih = Buffer.alloc(13); ih.writeUInt32BE(w, 0); ih.writeUInt32BE(h, 4); ih[8] = 8; ih[9] = 2;
|
||||
const raw = Buffer.alloc((w * 3 + 1) * h);
|
||||
for (let y = 0; y < h; y++) { const o = y * (w * 3 + 1); for (let x = 0; x < w; x++) { const i = o + 1 + x * 3; if (noise) { raw[i] = crypto.randomInt(256); raw[i + 1] = crypto.randomInt(256); raw[i + 2] = crypto.randomInt(256); } else { const stripe = ((x >> 4) & 1) ? 30 : 0; raw[i] = Math.min(255, rgb[0] + stripe); raw[i + 1] = rgb[1]; raw[i + 2] = rgb[2]; } } }
|
||||
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ih), chunk('IDAT', zlib.deflateSync(raw, { level: noise ? 0 : 9 })), chunk('IEND', Buffer.alloc(0))]);
|
||||
}
|
||||
const sha = b => crypto.createHash('sha1').update(b).digest('hex');
|
||||
|
||||
// ── seed: accounts (starter / builder / locked), chain index events (no chain), link domains ──
|
||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'bs-qa-'));
|
||||
fs.mkdirSync(path.join(DATA, 'uploads'));
|
||||
const now = Date.now();
|
||||
const acct = (email, username, memberId) => ({ email, username, code: username.slice(0, 7), memberId, created: now - 86400000, sponsorRef: '' });
|
||||
const accounts = { v: 2, byEmail: { 'starter@bs.test': acct('starter@bs.test', 'bsstarter', 900001), 'builder@bs.test': acct('builder@bs.test', 'bsbuilder', 900002), 'locked@bs.test': acct('locked@bs.test', 'bslocked', 900003) }, byAddress: {}, byCode: {}, joins: 3, positions: {} };
|
||||
for (const a of Object.values(accounts.byEmail)) accounts.byCode[a.code] = a.email;
|
||||
fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(accounts));
|
||||
const ev = (type, o) => Object.assign({ type, block: 1, tx: '0x' + crypto.randomBytes(32).toString('hex'), li: 0, ts: now - 3600000 }, o);
|
||||
const events = [ev('Purchase', { buyerId: 900001, productId: 3, paidWei: '1', priceCents: 5000, creditType: 0, creditAmount: 5000 }), ev('Purchase', { buyerId: 900002, productId: 3, paidWei: '1', priceCents: 5000, creditType: 0, creditAmount: 5000 }),
|
||||
ev('Purchase', { buyerId: 900003, productId: 1, paidWei: '1', priceCents: 2000, creditType: 0, creditAmount: 2000 }), // a $20 buy: not enough for Banner Spin
|
||||
ev('BuyerCounted', { sponsorId: 900002, newBuyerId: 900010, newCount: 1 }), ev('BuyerCounted', { sponsorId: 900002, newBuyerId: 900011, newCount: 2 })];
|
||||
fs.writeFileSync(path.join(DATA, 'chain-index.json'), JSON.stringify({ v: 1, lastBlock: 4e9, events, totals: { purchases: 3, paidInWei: '3', payouts: 0, payoutWei: '0', activations: 0 } }));
|
||||
fs.writeFileSync(path.join(DATA, 'site.json'), JSON.stringify({ linkDomains: LINK + ',' + LINK2, linkDomainChannels: LINK + ':social,' + LINK2 + ':email' }));
|
||||
const IMG = { a: png(468, 60, [200, 40, 40]), b: png(468, 60, [40, 160, 60]), c: png(468, 60, [40, 80, 220]), wrong: png(300, 250, [120, 120, 120]), big: png(300, 250, null, true), fb: png(468, 60, [240, 200, 0]) };
|
||||
for (const [k, b] of Object.entries(IMG)) fs.writeFileSync(path.join(DATA, k + '.png'), b);
|
||||
fs.mkdirSync(SHOTS, { recursive: true });
|
||||
|
||||
// ── server ──
|
||||
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: ADMIN_PW, ADMIN_EMAIL: 'admin@bs.test' });
|
||||
delete env.NODE_ENV; delete env.DATABASE_URL; delete env.ENGINE_KEY; delete env.LS_SYNC_SECRET; delete env.OUTBOUND; delete env.LS_TESTERS; delete env.CURTAIN;
|
||||
const log = fs.createWriteStream(path.join(SHOTS, 'server.log'));
|
||||
const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
srv.stdout.pipe(log); srv.stderr.pipe(log);
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
|
||||
// raw HTTP with any Host / Referer / UA / client IP
|
||||
function req(method, p, o) {
|
||||
o = o || {};
|
||||
return new Promise((resolve, reject) => {
|
||||
const headers = Object.assign({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) QA', Host: o.host || '127.0.0.1:' + PORT }, o.headers || {});
|
||||
if (o.cookie) headers.Cookie = o.cookie; if (o.ip) headers['X-Forwarded-For'] = o.ip; if (o.referer) headers.Referer = o.referer; if (o.ua) headers['User-Agent'] = o.ua;
|
||||
let body = o.body; if (body && !Buffer.isBuffer(body)) { body = Buffer.from(JSON.stringify(body)); headers['Content-Type'] = 'application/json'; }
|
||||
if (body) headers['Content-Length'] = body.length;
|
||||
const r = http.request({ host: '127.0.0.1', port: PORT, path: p, method, headers }, res => { const ch = []; res.on('data', c => ch.push(c)); res.on('end', () => { const buf = Buffer.concat(ch); let j = null; try { j = JSON.parse(buf.toString()); } catch (e) {} resolve({ status: res.statusCode, headers: res.headers, buf, json: j }); }); });
|
||||
r.on('error', reject); if (body) r.write(body); r.end();
|
||||
});
|
||||
}
|
||||
async function signIn(email) {
|
||||
const ip = '10.9.' + crypto.randomInt(250) + '.' + crypto.randomInt(250);
|
||||
const s = await req('POST', '/api/auth/email/start', { ip, body: { email, fts: Date.now() - 8000, hp_field_x9: '', pick: null } });
|
||||
if (!s.json || !s.json.devCode) throw new Error('no devCode for ' + email + ': ' + s.buf.toString().slice(0, 200));
|
||||
const v = await req('POST', '/api/auth/email/verify', { ip, body: { email, code: s.json.devCode } });
|
||||
const sc = [].concat(v.headers['set-cookie'] || []).map(c => c.split(';')[0]).join('; ');
|
||||
if (!sc) throw new Error('no session cookie for ' + email);
|
||||
return sc;
|
||||
}
|
||||
|
||||
let browser;
|
||||
try {
|
||||
for (let i = 0; i < 40; i++) { try { const r = await req('GET', '/api/config'); if (r.status === 200) break; } catch (e) {} await sleep(500); }
|
||||
|
||||
// ── tiers and limits through the API ──
|
||||
const cS = await signIn('starter@bs.test'), cB = await signIn('builder@bs.test'), cL = await signIn('locked@bs.test');
|
||||
const lS = await req('GET', '/api/my/bannerspins', { cookie: cS }); const lB = await req('GET', '/api/my/bannerspins', { cookie: cB }); const lL = await req('GET', '/api/my/bannerspins', { cookie: cL });
|
||||
check(lS.json && lS.json.tier.key === 'starter' && lS.json.tier.spins === 2 && lS.json.tier.banners === 5, 'starter tier = 2 x 5', JSON.stringify(lS.json && lS.json.tier));
|
||||
check(lB.json && lB.json.tier.key === 'builder' && lB.json.tier.spins === 5 && lB.json.tier.banners === 15, 'builder tier (2 qualifying buyers) = 5 x 15', JSON.stringify(lB.json && lB.json.tier));
|
||||
check(lL.json && lL.json.tier.ok === false, 'a $20-only member is locked', lL.json && lL.json.tier.reason);
|
||||
const lockedCreate = await req('POST', '/api/my/bannerspins', { cookie: cL, body: { name: 'x', size: '468x60' } });
|
||||
check(lockedCreate.status === 400 && /\$25/.test(lockedCreate.json.error), 'locked member cannot create', lockedCreate.json && lockedCreate.json.error);
|
||||
const lockedUp = await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cL, body: IMG.a, headers: { 'Content-Type': 'image/png' } });
|
||||
check(lockedUp.status === 403, 'locked member cannot upload', String(lockedUp.status));
|
||||
|
||||
// a spin link of the starter's own, used as one banner's target
|
||||
const rot = await req('POST', '/api/my/rotations', { cookie: cS, body: { name: 'Main invite' } });
|
||||
await req('POST', '/api/my/rotations/' + rot.json.rotation.id + '/dest', { cookie: cS, body: { url: 'https://spin-dest.example/landing', weight: 10 } });
|
||||
const ROTCODE = rot.json.rotation.code;
|
||||
|
||||
// ── the builder UI: create a Banner Spin, add 3 banners ──
|
||||
browser = await chromium.launch();
|
||||
const ctx = await browser.newContext({ viewport: { width: 1360, height: 950 } });
|
||||
await ctx.addCookies(cS.split('; ').map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; }));
|
||||
const page = await ctx.newPage(); const pageErrors = [];
|
||||
page.on('pageerror', e => pageErrors.push(e.message)); page.on('console', m => { if (m.type() === 'error' && !/favicon|fonts|status of 40[014]/.test(m.text())) pageErrors.push(m.text()); });
|
||||
await page.goto(BASE + '/links#b', { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForSelector('#bsWs:not([hidden])', { timeout: 15000 });
|
||||
await page.waitForSelector('#bsTier .tag', { timeout: 15000 });
|
||||
check(/Starter/.test(await page.textContent('#bsTier')), 'builder shows the tier', (await page.textContent('#bsTier')).trim().slice(0, 120));
|
||||
await page.click('#bsNewBtn2');
|
||||
await page.fill('#dlg-name', 'Forum signature');
|
||||
await page.selectOption('#bsNewSize', '468x60');
|
||||
await page.fill('#dlg-fallback', 'https://fallback.example/home');
|
||||
await page.click('#dlgOk');
|
||||
await page.waitForSelector('#bsSel:not([hidden])', { timeout: 10000 });
|
||||
// wrong size warns, too big blocks
|
||||
await page.setInputFiles('#bsFile', path.join(DATA, 'wrong.png')); await page.waitForSelector('#bsPrev .wm', { timeout: 5000 });
|
||||
check(/300x250/.test(await page.textContent('#bsPrev')), 'wrong-size image warns in the builder', (await page.textContent('#bsPrev')).trim().slice(0, 120));
|
||||
await page.setInputFiles('#bsFile', path.join(DATA, 'big.png')); await page.waitForSelector('#bsPrev .bm', { timeout: 5000 });
|
||||
check(/150 KB/.test(await page.textContent('#bsPrev')), 'over-150 KB image is refused in the builder', (await page.textContent('#bsPrev')).trim().slice(0, 120));
|
||||
const banners = [['a.png', 'url', 'https://target-a.example/offer?sub={lsid}', '10', 'Red'], ['b.png', 'url', 'https://target-b.example/page', '20', 'Green'], ['c.png', 'link', '', '30', 'Blue to my spin link']];
|
||||
for (const [file, kind, url, w, label] of banners) {
|
||||
await page.setInputFiles('#bsFile', path.join(DATA, file)); await page.waitForSelector('#bsPrev .okm', { timeout: 5000 });
|
||||
if (kind === 'url') { await page.selectOption('#bsTgtKind', 'url'); await page.fill('#bsTgtUrl', url); } else await page.selectOption('#bsTgtKind', String(rot.json.rotation.id));
|
||||
await page.fill('#bsWeight', w); await page.fill('#bsLabel', label);
|
||||
const n0 = await page.locator('#bsRows .rw[data-bid]').count();
|
||||
await page.click('#bsAddBtn');
|
||||
await page.waitForFunction(n => document.querySelectorAll('#bsRows .rw[data-bid]').length > n, n0, { timeout: 10000 });
|
||||
}
|
||||
check(await page.locator('#bsRows .rw[data-bid]').count() === 3, '3 banners added through the UI');
|
||||
await page.screenshot({ path: path.join(SHOTS, 'builder-desktop-banners.png'), fullPage: true });
|
||||
await page.click('#bsTabs button[data-tab="code"]'); await page.selectOption('#bsHost', LINK);
|
||||
const codes = await page.$$eval('#bsCodes pre', ps => ps.map(p => p.textContent));
|
||||
check(codes.length === 4, 'four embeds offered', String(codes.length));
|
||||
await page.screenshot({ path: path.join(SHOTS, 'builder-desktop-code.png'), fullPage: true });
|
||||
await page.click('#bsTabs button[data-tab="settings"]'); await page.screenshot({ path: path.join(SHOTS, 'builder-desktop-settings.png'), fullPage: true });
|
||||
|
||||
const list = (await req('GET', '/api/my/bannerspins', { cookie: cS })).json; const S = list.spins[0]; const CODE = S.code;
|
||||
const imgPath = '/i/' + CODE + '.gif', clickPath = '/c/' + CODE, jsPath = '/s/' + CODE + '.js';
|
||||
// every URL a placement ever loads: the four embeds + what the script writes (uploads stay behind /i/, never in an embed)
|
||||
const jsOut = (await req('GET', jsPath, { host: LINK, ip: '10.0.0.250', ua: 'Mozilla/5.0 TokenCheck', referer: 'https://token.example/' })).buf.toString().replace(/\\"/g, '"');
|
||||
const urls = (codes.join('\n') + '\n' + jsOut).match(/https?:\/\/[^\s"'\]\[<>]+/g) || [];
|
||||
const BADTOK = /\dx\d|banner|ads/i; const pathOf = x => x.replace(/^https?:\/\/[^/]+/, '');
|
||||
check(urls.length >= 7 && urls.every(x => !BADTOK.test(pathOf(x))) && !BADTOK.test(CODE), 'no size / banner / ads tokens in any served URL path', (urls.filter(x => BADTOK.test(pathOf(x))).join(' ') || urls.length + ' URLs clean, e.g. ' + urls.slice(0, 3).map(pathOf).join(' ')));
|
||||
// the generator itself: 20,000 fresh codes, none with a token
|
||||
{ const ALPHA = 'abcdefghjkmnpqrstuvwxyz23456789'; let bad = 0; const re = /ad|banner|\dx\d/; for (let i = 0; i < 20000; i++) { let c = ''; for (let k = 0; k < 7; k++) c += ALPHA[crypto.randomInt(ALPHA.length)]; if (re.test(c)) bad++; } check(bad > 0, 'sanity: the unfiltered alphabet does produce risky codes (' + bad + ' of 20000), so the server filter matters'); }
|
||||
check(codes[0].includes('https://' + LINK + '/i/' + CODE + '.gif') && codes[2].includes('https://' + LINK + '/s/' + CODE + '.js') && codes[3].startsWith('[url=https://' + LINK + '/c/' + CODE + ']'), 'embeds use the chosen link domain', codes[0].split('\n')[0]);
|
||||
|
||||
// which banner an image body is, by its bytes
|
||||
const byHash = { [sha(IMG.a)]: 1, [sha(IMG.b)]: 2, [sha(IMG.c)]: 3 };
|
||||
const expectTarget = { 1: /^https:\/\/target-a\.example\/offer\?sub=k[0-9a-f]{11}$/, 2: /^https:\/\/target-b\.example\/page$/, 3: new RegExp('^https://' + LINK.replace('.', '\\.') + '/r/' + ROTCODE + '$'), 0: /^https:\/\/fallback\.example\/home$/ };
|
||||
|
||||
// ── headers ──
|
||||
const h1 = await req('GET', imgPath, { host: LINK, ip: '10.1.1.1', referer: 'https://forum-a.example/t/1' }); const h2 = await req('GET', imgPath, { host: LINK, ip: '10.1.1.1', referer: 'https://forum-a.example/t/1' });
|
||||
check(/no-store/.test(h1.headers['cache-control']) && /private/.test(h1.headers['cache-control']), 'image is Cache-Control: no-store, private', h1.headers['cache-control']);
|
||||
check(!!h1.headers.etag && h1.headers.etag !== h2.headers.etag, 'fresh ETag on every load', h1.headers.etag + ' vs ' + h2.headers.etag);
|
||||
check(h1.status === 200 && /^image\/png/.test(h1.headers['content-type']) && byHash[sha(h1.buf)], 'image body is one of the banners', h1.headers['content-type']);
|
||||
const h3 = await req('GET', imgPath, { host: LINK2, ip: '10.1.1.2', referer: 'https://x.example/' });
|
||||
check(h3.status === 200 && byHash[sha(h3.buf)], 'a second link domain answers the same code');
|
||||
const unknown = await req('GET', '/i/zzzzzzz.gif', { host: LINK }); check(unknown.status === 404, 'unknown code is 404');
|
||||
|
||||
// ── click matching: 3 visitors x 3 placements, interleaved, 40 rounds ──
|
||||
// record expected counted impressions: once per (visitor, banner) per minute (all of this runs inside a minute or two)
|
||||
await sleep(6000); const statsBase = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json.totals.imps;
|
||||
const visitors = [{ ip: '10.2.0.1', ua: 'Mozilla/5.0 (Windows NT 10.0) VisitorA' }, { ip: '10.2.0.2', ua: 'Mozilla/5.0 (iPhone) VisitorB' }, { ip: '10.2.0.3', ua: 'Mozilla/5.0 (Macintosh) VisitorC' }];
|
||||
const hostsP = ['https://forum-a.example/thread/9', 'https://blog-b.example/post', 'https://safelist-c.example/mail?id=4'];
|
||||
let pairs = 0, ok = 0, lsids = []; const seen = new Set(); const shownBy = { 1: 0, 2: 0, 3: 0 }; const t0 = Date.now(); const misses = [];
|
||||
for (let round = 0; round < 40; round++) {
|
||||
// every visitor loads the banner on two different placements, then clicks on one of them (order shuffled)
|
||||
const loads = [];
|
||||
for (const [vi, v] of visitors.entries()) { const a = hostsP[(round + vi) % 3], b = hostsP[(round + vi + 1) % 3]; loads.push({ v, ref: a }, { v, ref: b }); }
|
||||
loads.sort(() => crypto.randomInt(3) - 1);
|
||||
const shown = new Map();
|
||||
for (const L of loads) { const r = await req('GET', imgPath, { host: LINK, ip: L.v.ip, ua: L.v.ua, referer: L.ref }); const bid = byHash[sha(r.buf)]; shown.set(L.v.ip + '|' + new URL(L.ref).host, bid); shownBy[bid]++; seen.add(L.v.ip + '|' + bid); }
|
||||
for (const [vi, v] of visitors.entries()) {
|
||||
const ref = hostsP[(round + vi + (round % 2)) % 3]; const want = shown.get(v.ip + '|' + new URL(ref).host);
|
||||
const c = await req('GET', clickPath, { host: LINK, ip: v.ip, ua: v.ua, referer: ref });
|
||||
pairs++; const loc = c.headers.location || ''; if (expectTarget[want].test(loc)) ok++; else misses.push(want + ' -> ' + loc);
|
||||
const m = /sub=(k[0-9a-f]{11})/.exec(loc); if (m) lsids.push(m[1]);
|
||||
}
|
||||
}
|
||||
const rate = ok / pairs;
|
||||
check(rate >= 0.95, 'clicks land on the matching banner target >= 95%', ok + '/' + pairs + ' = ' + (rate * 100).toFixed(1) + '%' + (misses.length ? ' misses: ' + misses.slice(0, 3).join(', ') : ''));
|
||||
check(shownBy[3] > shownBy[1], 'weights shape the rotation (30 vs 10)', JSON.stringify(shownBy));
|
||||
const elapsed = Date.now() - t0;
|
||||
|
||||
// ── fallback: a visitor who never saw the image ──
|
||||
const fbc = await req('GET', clickPath, { host: LINK, ip: '10.3.3.3', ua: 'Mozilla/5.0 NeverSaw', referer: 'https://forum-a.example/thread/9' });
|
||||
check(expectTarget[0].test(fbc.headers.location || ''), 'no note -> fallback target', fbc.headers.location);
|
||||
|
||||
// ── bots and prefetchers are not counted ──
|
||||
for (let i = 0; i < 5; i++) { await req('GET', imgPath, { host: LINK, ip: '10.4.0.' + i, ua: 'Googlebot/2.1', referer: 'https://forum-a.example/' }); await req('GET', imgPath, { host: LINK, ip: '10.5.0.' + i, ua: 'Mozilla/5.0 Pre', referer: 'https://forum-a.example/', headers: { 'Sec-Purpose': 'prefetch' } }); }
|
||||
|
||||
// ── script embed: exact match ──
|
||||
const js = await req('GET', jsPath, { host: LINK, ip: '10.6.0.1', ua: 'Mozilla/5.0 ScriptUser', referer: 'https://blog-b.example/post' });
|
||||
const xm = /\/c\/[a-z0-9]+\?x=(\d+)/.exec(js.buf.toString()); const xb = xm ? Number(xm[1]) : -1;
|
||||
check(js.status === 200 && /javascript/.test(js.headers['content-type']) && /no-store/.test(js.headers['cache-control']) && xb >= 1, 'script embed writes banner + its own click link', js.buf.toString().slice(0, 90));
|
||||
const imgInJs = /src=\\"([^\\"]+)\\"/.exec(js.buf.toString()); const ji = imgInJs ? await req('GET', new URL(imgInJs[1]).pathname + new URL(imgInJs[1]).search, { host: LINK }) : null;
|
||||
check(ji && byHash[sha(ji.buf)] === xb, 'script image is the same banner its link names', imgInJs && imgInJs[1]);
|
||||
const jc = await req('GET', clickPath + '?x=' + xb, { host: LINK, ip: '10.6.0.99', ua: 'Mozilla/5.0 OtherDevice', referer: 'https://blog-b.example/post' });
|
||||
check(expectTarget[xb].test(jc.headers.location || ''), 'script click goes to that exact banner target', jc.headers.location);
|
||||
seen.add('10.6.0.1|' + xb);
|
||||
|
||||
// ── counters ──
|
||||
await sleep(6500);
|
||||
const st = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json;
|
||||
const expected = statsBase + seen.size;
|
||||
check(st.totals.imps === expected, 'impressions counted once per visitor per banner per minute, bots + prefetch excluded', 'counted ' + st.totals.imps + ', expected ' + expected + ' (loop took ' + Math.round(elapsed / 1000) + ' s)');
|
||||
const plHosts = st.placements.map(p => p.host);
|
||||
check(['forum-a.example', 'blog-b.example', 'safelist-c.example'].every(h => plHosts.includes(h)), 'per-placement counters', plHosts.join(', '));
|
||||
check(st.banners.every(b => b.imps > 0) && st.totals.clicks >= pairs, 'per-banner views + clicks move', st.banners.map(b => b.id + ':' + b.imps + '/' + b.clicks).join(' '));
|
||||
check(st.totals.matchRate >= 95, 'match rate in stats', st.totals.matchRate + '%, unmatched ' + st.totals.unmatched);
|
||||
const countsFile = JSON.parse(fs.readFileSync(path.join(DATA, 'bannerspin-counts.json'), 'utf8'));
|
||||
check(!!countsFile.d[String(S.id)], 'counters flushed to the volume file (no row per load)', Object.keys(countsFile.d[String(S.id)] || {}).join(','));
|
||||
|
||||
// ── conversions credit the banner click (partner postback with the lsid) ──
|
||||
const pb = (await req('GET', '/api/my/postbacks', { cookie: cS })).json;
|
||||
const conv = lsids.length ? await req('GET', '/pb/in?key=' + pb.key + '&lsid=' + lsids[0] + '&event=sale&value=1.00') : null;
|
||||
const st2 = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json;
|
||||
check(conv && conv.status === 200 && st2.totals.conversions === 1, 'a conversion on a banner click id lands on the Banner Spin', conv && conv.buf.toString().slice(0, 100));
|
||||
|
||||
// ── pause and the admin kill switch ──
|
||||
const blankOf = r => r.buf.slice(0, 8).toString('hex') === '89504e470d0a1a0a' && r.buf.readUInt32BE(16) === 468 && r.buf.readUInt32BE(20) === 60 && !byHash[sha(r.buf)];
|
||||
await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { paused: true } });
|
||||
const pz = await req('GET', imgPath, { host: LINK, ip: '10.7.0.1', referer: 'https://forum-a.example/' }); check(blankOf(pz), 'paused with no fallback image -> blank image at the right size');
|
||||
const fbUp = await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cS, body: IMG.fb, headers: { 'Content-Type': 'image/png' } });
|
||||
await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { fallbackImage: fbUp.json.url } });
|
||||
const pz2 = await req('GET', imgPath, { host: LINK, ip: '10.7.0.1', referer: 'https://forum-a.example/' }); check(sha(pz2.buf) === sha(IMG.fb), 'paused -> the fallback banner image');
|
||||
await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { paused: false } });
|
||||
const auth = { Authorization: 'Bearer ' + ADMIN_PW };
|
||||
await req('POST', '/api/admin/bannerspins/' + S.id, { headers: auth, body: { off: true, note: 'qa' } });
|
||||
const off1 = await req('GET', imgPath, { host: LINK, ip: '10.8.0.1', referer: 'https://forum-a.example/' }); const offc = await req('GET', clickPath, { host: LINK, ip: '10.8.0.1', referer: 'https://forum-a.example/' });
|
||||
check(blankOf(off1) && expectTarget[0].test(offc.headers.location || ''), 'admin kill switch: neutral blank image + fallback link', offc.headers.location);
|
||||
await req('POST', '/api/admin/bannerspins/' + S.id, { headers: auth, body: { off: false } });
|
||||
await req('POST', '/api/admin/bannerspins/' + S.id, { headers: auth, body: { bannerId: 1, off: true } });
|
||||
let saw1 = 0; for (let i = 0; i < 40; i++) { const r = await req('GET', imgPath, { host: LINK, ip: '10.8.1.' + i, referer: 'https://forum-a.example/' }); if (byHash[sha(r.buf)] === 1) saw1++; }
|
||||
check(saw1 === 0, 'one banner taken offline by admin never serves', saw1 + ' of 40');
|
||||
await req('POST', '/api/admin/bannerspins/' + S.id, { headers: auth, body: { bannerId: 1, off: false } });
|
||||
const adm = await req('GET', '/api/admin/content?type=bannerspin&fresh=1', { headers: auth });
|
||||
check(adm.json && adm.json.items && adm.json.items.length === 1 && adm.json.items[0].detail.banners.length === 3 && adm.json.items[0].actions.length === 4, 'admin Member content lists the Banner Spin with its banners + actions', adm.json && JSON.stringify(adm.json.totals.bannerspin));
|
||||
|
||||
// ── one-per-visitor mode: the same banner all day ──
|
||||
await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { mode: 'visitor' } });
|
||||
const same = new Set(); for (let i = 0; i < 12; i++) { const r = await req('GET', imgPath, { host: LINK, ip: '10.9.9.9', ua: 'Mozilla/5.0 Loyal', referer: 'https://forum-a.example/' }); same.add(byHash[sha(r.buf)]); }
|
||||
check(same.size === 1, 'one-per-visitor mode shows one banner all day', [...same].join(','));
|
||||
await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { mode: 'weight' } });
|
||||
|
||||
// ── tier limits: banners per Banner Spin (Starter 5), Banner Spins per member (Starter 2) ──
|
||||
const up = [];
|
||||
for (let i = 0; i < 3; i++) up.push((await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cS, body: png(468, 60, [i * 60, 10, 10]), headers: { 'Content-Type': 'image/png' } })).json);
|
||||
const add4 = await req('POST', '/api/my/bannerspins/' + S.id + '/banner', { cookie: cS, body: { image: up[0].url, target: 'https://t4.example/' } });
|
||||
const add5 = await req('POST', '/api/my/bannerspins/' + S.id + '/banner', { cookie: cS, body: { image: up[1].url, target: 'https://t5.example/' } });
|
||||
const add6 = await req('POST', '/api/my/bannerspins/' + S.id + '/banner', { cookie: cS, body: { image: up[2].url, target: 'https://t6.example/' } });
|
||||
check(add4.status === 200 && add5.status === 200 && add6.status === 400 && /5 banners/.test(add6.json.error), 'Starter: 6th banner refused', add6.json && add6.json.error);
|
||||
const sp2 = await req('POST', '/api/my/bannerspins', { cookie: cS, body: { name: 'Second', size: '728x90' } });
|
||||
const sp3 = await req('POST', '/api/my/bannerspins', { cookie: cS, body: { name: 'Third', size: '300x250' } });
|
||||
check(sp2.status === 200 && sp3.status === 400 && /2 Banner Spins/.test(sp3.json.error), 'Starter: 3rd Banner Spin refused', sp3.json && sp3.json.error);
|
||||
const badSize = await req('POST', '/api/my/bannerspins', { cookie: cB, body: { name: 'x', size: '999x99' } }); check(badSize.status === 400, 'unsupported size refused');
|
||||
const otherImg = await req('POST', '/api/my/bannerspins/' + sp2.json.spin.id + '/banner', { cookie: cB, body: { image: up[2].url, target: 'https://x.example/' } });
|
||||
check(otherImg.status === 400, 'a member cannot use another member\'s Banner Spin', otherImg.json && otherImg.json.error);
|
||||
const bigUp = await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cS, body: IMG.big, headers: { 'Content-Type': 'image/png' } }).catch(e => ({ status: 'reset' }));
|
||||
check(bigUp.status === 400 || bigUp.status === 'reset', 'server refuses an image over 150 KB', String(bigUp.status) + ' (' + IMG.big.length + ' bytes)');
|
||||
|
||||
// ── phone width screenshots ──
|
||||
const ph = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true });
|
||||
await ph.addCookies(cS.split('; ').map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; }));
|
||||
const pp = await ph.newPage(); pp.on('pageerror', e => pageErrors.push('phone: ' + e.message));
|
||||
await pp.goto(BASE + '/links#b' + S.id, { waitUntil: 'domcontentloaded' }); await pp.waitForSelector('#bsSel:not([hidden])', { timeout: 15000 }); await pp.waitForTimeout(800);
|
||||
await pp.screenshot({ path: path.join(SHOTS, 'builder-phone-banners.png'), fullPage: true });
|
||||
const overflow = await pp.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
|
||||
check(overflow <= 2, 'no horizontal page scroll at phone width', overflow + ' px');
|
||||
await pp.click('#bsTabs button[data-tab="code"]'); await pp.screenshot({ path: path.join(SHOTS, 'builder-phone-code.png'), fullPage: true });
|
||||
await pp.click('#bsTabs button[data-tab="stats"]'); await pp.waitForTimeout(800); await pp.screenshot({ path: path.join(SHOTS, 'builder-phone-stats.png'), fullPage: true });
|
||||
await page.reload({ waitUntil: 'domcontentloaded' }); await page.waitForSelector('#bsSel:not([hidden])', { timeout: 15000 });
|
||||
await page.click('#bsTabs button[data-tab="stats"]'); await page.waitForTimeout(1000); await page.screenshot({ path: path.join(SHOTS, 'builder-desktop-stats.png'), fullPage: true });
|
||||
await page.click('#vsw button[data-v="links"]'); await page.waitForTimeout(800);
|
||||
check(!(await page.isHidden('#ws')) && await page.isHidden('#bsWs'), 'switching back to Spin links works');
|
||||
check(pageErrors.length === 0, 'no page errors in the builder', pageErrors.slice(0, 3).join(' | '));
|
||||
} catch (e) {
|
||||
check(false, 'test run crashed', e.stack);
|
||||
} finally {
|
||||
try { if (browser) await browser.close(); } catch (e) {}
|
||||
srv.kill();
|
||||
console.log(results.join('\n'));
|
||||
console.log('\n' + (results.length - failed) + ' passed, ' + failed + ' failed. Screenshots + server log: ' + SHOTS + '. Data dir: ' + DATA);
|
||||
process.exit(failed ? 1 : 0);
|
||||
}
|
||||
+4
-2
@@ -187,8 +187,10 @@ async function resolve(code, req) {
|
||||
return { url: out, dest: d, rotation: r, lsid: id };
|
||||
}
|
||||
// conversions: record an event against the click that brought the person (dedupe per click + event)
|
||||
// Banner Spin clicks (bannerspin.js, 2026-10-18) carry their own click ids ('k' + 11 hex); an id we do not know is handed to it
|
||||
let EXT_CONVERT = null; function setExternalConvert(fn) { EXT_CONVERT = fn; }
|
||||
async function convert(lsid, ev, facts) {
|
||||
const h = J.db.hits.find(x => x.id === String(lsid)); if (!h) return null;
|
||||
const h = J.db.hits.find(x => x.id === String(lsid)); if (!h) return EXT_CONVERT ? EXT_CONVERT(lsid, ev, facts) : null;
|
||||
const r = J.db.rotations.find(x => x.id === h.r); if (!r) return null;
|
||||
if (!J.db.conv.some(c => c.lsid === h.id && c.ev === ev)) { J.db.conv.push({ lsid: h.id, r: r.id, d: h.d, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: h.sr || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
|
||||
return { owner: r.owner, code: r.code, rotationId: r.id, q: h.q || {}, s: h.s, c: h.c, dv: h.dv, sourceId: h.sr || '' };
|
||||
@@ -293,4 +295,4 @@ function adminAll() {
|
||||
hits: o.hits, hits7: o.hits7, bots: o.bots, conversions: cv[r.id] || 0 }; });
|
||||
}
|
||||
module.exports = { init, adminAll, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday,
|
||||
pub, rawRotations, save, findMine, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource };
|
||||
pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource };
|
||||
|
||||
@@ -43,6 +43,7 @@ const carry = require('./carry'); // sponsor carry-over: engine acti
|
||||
const rotator = require('./rotator');
|
||||
const health = require('./health'); // destination health checks + auto-pause (2026-10-10)
|
||||
const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29)
|
||||
const bannerspin = require('./bannerspin'); // Banner Spin: one image URL + one click URL rotating up to 25 banners (2026-10-18)
|
||||
const sources = require('./sources'); // traffic sources: network macros, campaign URLs, per-source postbacks, Reports dimension (2026-10-12)
|
||||
const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/<slug> (2026-09-29)
|
||||
const domains = require('./domains'); // link-domain pool by channel + six-hourly safety checks; burned domains leave the pool (2026-10-10)
|
||||
@@ -174,6 +175,20 @@ async function cachedMember(id) {
|
||||
let v = null; try { v = await chain.member(id); } catch (e) {}
|
||||
memberInfoCache.set(id, { t: Date.now(), v }); return v;
|
||||
}
|
||||
// Banner Spin access facts (2026-10-18): an own package of $25 or more on the main id or any linked position (the tank
|
||||
// adoption rule), and qualifying buyers counted the way pay levels count them (main + positions, so Qualified Start counts).
|
||||
// Cached a minute; bannerspin.js remembers what it has seen so the chain index window never takes a tier away.
|
||||
const bsFacts = new Map();
|
||||
async function bannerFacts(email) {
|
||||
const e = String(email || '').toLowerCase(); const hit = bsFacts.get(e); if (hit && Date.now() - hit.ts < 60000) return hit.f;
|
||||
const ids = []; try { const a = await accounts.byEmail(e); if (a && a.memberId) ids.push(a.memberId); for (const p of await accounts.positions(e)) if (p.memberId && !ids.includes(p.memberId)) ids.push(p.memberId); } catch (er) {}
|
||||
const ownBuy = ids.some(id => tank.hasOwnBuy(id));
|
||||
let buyers = 0; for (const id of ids) { try { buyers += (await chain.member(id)).buyerCount || 0; } catch (er) {} }
|
||||
const idset = new Set(ids), counted = new Set(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'BuyerCounted' && idset.has(ev.sponsorId) && ev.newBuyerId) counted.add(ev.newBuyerId);
|
||||
buyers = Math.max(buyers, counted.size);
|
||||
try { const ms = await ads.milestonesOf(e); if (ms.includes('level3')) buyers = Math.max(buyers, 5); else if (ms.includes('level2')) buyers = Math.max(buyers, 2); } catch (er) {} // a badge once earned stays earned
|
||||
const f = { ownBuy, buyers }; bsFacts.set(e, { ts: Date.now(), f }); return f;
|
||||
}
|
||||
async function myMemberIds(s) {
|
||||
const main = await auth.refreshMemberId(s);
|
||||
const ids = main ? [main] : [];
|
||||
@@ -476,6 +491,8 @@ async function boot() {
|
||||
setInterval(() => health.tick().catch(e => console.error('health', e.message)), 30 * 60 * 1000);
|
||||
setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h
|
||||
postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator, sources });
|
||||
bannerspin.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, rotator, geo, sources, ownHosts, adminEmail: ADMIN_EMAIL, facts: bannerFacts });
|
||||
rotator.setExternalConvert((lsid, ev, facts) => bannerspin.convert(lsid, ev, facts)); // Banner Spin click ids convert like spin-link clicks
|
||||
sources.init({ dataDir: DATA_DIR, postbacks, rotator, catalogFile: path.join(ROOT, 'catalog', 'traffic-sources.json'), linkHost: () => { const hs = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(Boolean); return hs[0] || SITE_HOST; } });
|
||||
zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST });
|
||||
pages.init({ dataDir: DATA_DIR, ownHosts, imageBase: () => (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, openrouterKey: () => { if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } } });
|
||||
@@ -500,7 +517,7 @@ async function boot() {
|
||||
audit.init({ dataDir: DATA_DIR, notify: text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: counter audit', text).catch(() => {}); } });
|
||||
setTimeout(() => audit.dailyTick(), 5 * 60 * 1000); setInterval(() => audit.dailyTick(), 24 * 60 * 60 * 1000);
|
||||
videomaker.init({ dataDir: DATA_DIR, spaces, accounts });
|
||||
content.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, accounts, pages, rotator, sources, zones, ads, postbacks, audiences, messages, videomaker, reports, domains, adminEmail: ADMIN_EMAIL, houseOwner: ads.HOUSE_OWNER, siteHost: SITE_HOST, linkHost: () => domains.live()[0] || SITE_HOST, pagesHost });
|
||||
content.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, accounts, pages, rotator, bannerspin, sources, zones, ads, postbacks, audiences, messages, videomaker, reports, domains, adminEmail: ADMIN_EMAIL, houseOwner: ads.HOUSE_OWNER, siteHost: SITE_HOST, linkHost: () => domains.live()[0] || SITE_HOST, pagesHost });
|
||||
leaderboard.init({ chain, accounts, ads, dataDir: DATA_DIR, siteConfig, pushFeed, adminEmail: ADMIN_EMAIL,
|
||||
notify: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId); if (String(sc.leaderboardAnnounceGeneral || '1') !== '0') await telegramSend(sc.telegramEchoChatId, text, null); } });
|
||||
setTimeout(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 90 * 1000);
|
||||
@@ -917,7 +934,7 @@ function linkSitePage(host, page) {
|
||||
disclosure: '<h1>Affiliate and advertising disclosure</h1><p>Links forwarded through ' + H + ' may be affiliate links or paid advertisements. The member who published a link may earn a commission or advertising credit if you buy something or sign up on the page you land on. This never changes the price you pay.</p><p>' + brand + ' itself is an advertising platform. Members buy ad packages and earn commissions when people they referred buy ad packages. No income is guaranteed to anyone; results depend on effort, and any earnings examples on member pages are illustrations, not promises.</p><p>The pages you are forwarded to belong to their publishers. We are not responsible for their claims, and we remove links that are reported and found to violate our <a href="/terms">terms</a>.</p>',
|
||||
terms: '<h1>Terms of use</h1><p>By following a link on ' + H + ' you agree to these terms.</p><h2>The service</h2><p>' + H + ' forwards visitors to destinations chosen by ' + brand + ' members. We provide the forwarding only. We do not endorse, verify or control the destination pages, and we are not a party to any transaction you make there.</p><h2>Acceptable use</h2><p>Members may not forward visitors to content that is illegal, deceptive, malicious, adult, or that impersonates another business. Links that violate this are removed and the member\'s account is closed. Automated access to this domain is not permitted except by search engines.</p><h2>No warranty</h2><p>The service is provided as is. We do not guarantee that any link will be available, and we are not liable for the content, availability or conduct of destination sites.</p><h2>Contact</h2><p>Questions about these terms: <a href="https://linkspin.co">linkspin.co</a>.</p>',
|
||||
privacy: '<h1>Privacy policy</h1><p>This policy covers ' + H + ' and the link forwarding service on it.</p><h2>What we collect</h2><p>When you follow a link we record the date, your country (derived from your network address and then discarded), the site that referred you, whether you are on a phone or a computer, and an anonymous visitor token that changes every day and cannot be traced back to you. We do not store your IP address, your name, your email address or any account information on this domain.</p><h2>Cookies</h2><p>This domain sets no cookies. The page you are forwarded to has its own privacy policy and may set its own.</p><h2>Why we collect it</h2><p>So members can see how many people followed their links and from where. Counts are shown to the member who published the link, in aggregate, and to nobody else.</p><h2>Retention</h2><p>Link statistics are kept for up to thirteen months and then deleted.</p><h2>Your rights</h2><p>Because we hold no personal data on this domain there is nothing to access or delete here. For anything involving a ' + brand + ' member account, contact us through <a href="https://linkspin.co">linkspin.co</a>.</p>',
|
||||
abuse: '<h1>Report a link</h1><p>If a link on ' + H + ' forwarded you to a page that is deceptive, unsafe, adult, or impersonates a business, tell us. We review every report and pull the link first, then ask questions.</p><p>Send the full link you clicked (it starts with https://' + H + '/r/) and what you saw, to the support contact on <a href="https://linkspin.co">linkspin.co</a>. Reports are usually handled the same day.</p>',
|
||||
abuse: '<h1>Report a link</h1><p>If a link on ' + H + ' forwarded you to a page that is deceptive, unsafe, adult, or impersonates a business, tell us. We review every report and pull the link first, then ask questions.</p><p>Send the full link you clicked (it starts with https://' + H + '/r/ or https://' + H + '/c/) and what you saw, or the address of a banner image you want reviewed, to the support contact on <a href="https://linkspin.co">linkspin.co</a>. Reports are usually handled the same day.</p>',
|
||||
gone: '<h1>That link is not active</h1><p>The link you followed has been removed or has expired. Nothing was recorded. If you were expecting a specific page, ask the person who shared the link for a fresh one.</p>'
|
||||
};
|
||||
return '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>' + H + '</title><meta name="robots" content="noindex,follow"><style>body{margin:0;font:16px/1.6 system-ui,Segoe UI,Roboto,sans-serif;color:#1b1f1e;background:#fbfbf9}main{max-width:680px;margin:0 auto;padding:40px 22px 60px}nav{display:flex;gap:16px;flex-wrap:wrap;font-size:14px;margin-bottom:28px}nav a{color:#0f766e;text-decoration:none}h1{font-size:26px;margin:0 0 12px}h2{font-size:17px;margin:22px 0 6px}p{margin:0 0 12px}footer{margin-top:40px;font-size:13px;color:#6b7370;border-top:1px solid #e3e3dd;padding-top:12px}</style></head><body><main>' + nav + (bodies[page] || bodies.gone) + '<footer>© ' + year + ' ' + brand + ' link service. <a href="/disclosure">Disclosure</a> · <a href="/terms">Terms</a> · <a href="/privacy">Privacy</a></footer></main></body></html>';
|
||||
@@ -970,7 +987,7 @@ const server = http.createServer(async (req, res) => {
|
||||
const u = new URL(req.url, 'http://x');
|
||||
const p = u.pathname;
|
||||
// zone endpoints run on other people's sites and show only ad creatives, so they pass the curtain
|
||||
const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-');
|
||||
const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-') || /^\/(i|c|s)\/[a-z0-9]{5,12}(\.gif|\.js)?$/.test(p); // + Banner Spin image / click / script (2026-10-18)
|
||||
// support must reach everyone, invited or not (2026-10-16): someone locked out or not yet let in is exactly who needs it
|
||||
if (!zonePath && !supportOpen(p) && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor
|
||||
|
||||
@@ -981,6 +998,30 @@ const server = http.createServer(async (req, res) => {
|
||||
if (hit && hit.url) { res.writeHead(302, { Location: hit.url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); }
|
||||
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone'));
|
||||
}
|
||||
// -- Banner Spin (2026-10-18): /i/<code>.gif the image (a fresh pick on every load, never cached), /c/<code> the click,
|
||||
// /s/<code>.js the script embed (banner + its own click link). Any host, any origin, like /r/.
|
||||
{ const bm = /^\/(i|c|s)\/([a-z0-9]{5,12})(\.gif|\.js)?$/.exec(p);
|
||||
if (bm && (req.method === 'GET' || req.method === 'HEAD') && ((bm[1] === 'i' && bm[3] === '.gif') || (bm[1] === 'c' && !bm[3]) || (bm[1] === 's' && bm[3] === '.js'))) {
|
||||
const fresh = { 'Cache-Control': 'no-store, no-cache, must-revalidate, private, max-age=0', Pragma: 'no-cache', Expires: '0', ETag: '"' + crypto.randomBytes(8).toString('hex') + '"', 'Access-Control-Allow-Origin': '*', 'X-Content-Type-Options': 'nosniff', 'X-Robots-Tag': 'noindex' };
|
||||
const host = reqHost(req) || SITE_HOST;
|
||||
if (bm[1] === 'i') {
|
||||
const xq = u.searchParams.get('x'); const im = await bannerspin.image(bm[2], req, xq != null && /^\d{1,4}$/.test(xq) ? Number(xq) : null);
|
||||
if (!im) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end(); }
|
||||
if (im.url) { res.writeHead(302, Object.assign({}, fresh, { Location: im.url, 'Referrer-Policy': 'no-referrer' })); return res.end(); }
|
||||
let body = null, type = 'image/png';
|
||||
if (im.local) { const f = bannerspin.readImage(im.local); if (f) { body = f.buf; type = f.mime; } }
|
||||
if (!body) body = bannerspin.blankPng(im.size[0], im.size[1]);
|
||||
res.writeHead(200, Object.assign({}, fresh, { 'Content-Type': type, 'Content-Length': String(body.length), 'Content-Disposition': 'inline' })); return res.end(req.method === 'HEAD' ? '' : body);
|
||||
}
|
||||
if (bm[1] === 's') {
|
||||
const js = await bannerspin.script(bm[2], req, (IS_PROD ? 'https' : 'http') + '://' + (req.headers.host || host));
|
||||
if (!js) { res.writeHead(404, { 'Content-Type': 'application/javascript' }); return res.end('/* not found */'); }
|
||||
res.writeHead(200, Object.assign({}, fresh, { 'Content-Type': 'application/javascript; charset=utf-8' })); return res.end(req.method === 'HEAD' ? '' : js);
|
||||
}
|
||||
const ck = await bannerspin.click(bm[2], req, host);
|
||||
if (ck && ck.url) { res.writeHead(302, { Location: ck.url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade', 'X-Robots-Tag': 'noindex' }); return res.end(); }
|
||||
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(host, 'gone'));
|
||||
} }
|
||||
// -- ad zones on members' sites: the tag, the ad, the viewable beacon, the click. Any origin may call these.
|
||||
if (p === '/z.js') { const zf = path.join(PUBLIC_DIR, 'z.js'); try { const body = fs.readFileSync(zf); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' }); return res.end(body); } catch (e) {} }
|
||||
if (p === '/api/zone/serve' && req.method === 'GET') {
|
||||
@@ -1058,7 +1099,7 @@ const server = http.createServer(async (req, res) => {
|
||||
if (isLinkHost(req)) {
|
||||
const page = { '/': 'home', '/disclosure': 'disclosure', '/terms': 'terms', '/privacy': 'privacy', '/abuse': 'abuse', '/robots.txt': 'robots' }[p];
|
||||
if (!page) { res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone')); }
|
||||
if (page === 'robots') { res.writeHead(200, { 'Content-Type': 'text/plain' }); return res.end('User-agent: *\nDisallow: /r/\n'); }
|
||||
if (page === 'robots') { res.writeHead(200, { 'Content-Type': 'text/plain' }); return res.end('User-agent: *\nDisallow: /r/\nDisallow: /c/\nDisallow: /s/\n'); }
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }); return res.end(linkSitePage(reqHost(req), page));
|
||||
}
|
||||
|
||||
@@ -2098,6 +2139,59 @@ 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 health.checkRotation(s.email, m[1]); return json(res, r.error ? (/No such/.test(r.error) ? 404 : 429) : 200, r, { 'Cache-Control': 'no-store' });
|
||||
}
|
||||
// -- Banner Spin builder (2026-10-18). Every route takes GET and POST: the shell's api() helper always POSTs.
|
||||
if (p === '/api/my/bannerspins' && (req.method === 'GET' || req.method === 'POST')) {
|
||||
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
const b = req.method === 'POST' ? await readBody(req) : {};
|
||||
if (req.method === 'GET' || b.list || !b.name) {
|
||||
const hs = domains.hosts();
|
||||
return json(res, 200, { spins: await bannerspin.list(s.email), tier: await bannerspin.tierFor(s.email), tiers: bannerspin.TIERS, sizes: Object.keys(bannerspin.SIZES), maxBytes: bannerspin.MAX_BYTES, off: bannerspin.settings().off,
|
||||
hosts: hs.length ? hs : [{ host: SITE_HOST, channel: 'social', label: 'Social', note: 'The app host (no link domains are live)' }] }, { 'Cache-Control': 'no-store' });
|
||||
}
|
||||
const r = await bannerspin.create(s.email, b); return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
if (p === '/api/my/bannerspins/upload' && req.method === 'POST') { // raw image body; JPG / PNG / GIF, 150 KB, counts against the 10 uploads a day
|
||||
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
const t = await bannerspin.tierFor(s.email); if (!t.ok) return json(res, 403, { error: t.reason });
|
||||
const ct = String(req.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
|
||||
const EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif' };
|
||||
if (!EXT[ct]) return json(res, 400, { error: 'Use a JPG, PNG or GIF file.' });
|
||||
const key = s.email + ':' + new Date().toISOString().slice(0, 10);
|
||||
if ((uploadCounts.get(key) || 0) >= 10) return json(res, 400, { error: 'Upload limit for today reached (10 files).' });
|
||||
let buf; try { buf = await readRaw(req, bannerspin.MAX_BYTES); } catch (e) { return json(res, 400, { error: 'That image is over 150 KB. Save it smaller (fewer colors or frames for a GIF) and try again.' }); }
|
||||
const magicOk = buf.length > 16 && ((ct === 'image/png' && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) || (ct === 'image/jpeg' && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) || (ct === 'image/gif' && buf.slice(0, 4).toString() === 'GIF8'));
|
||||
if (!magicOk) return json(res, 400, { error: 'That file does not look like a real ' + EXT[ct].toUpperCase() + '.' });
|
||||
const d = bannerspin.dims(buf, ct);
|
||||
const name = crypto.randomBytes(12).toString('hex') + '.' + EXT[ct];
|
||||
uploadCounts.set(key, (uploadCounts.get(key) || 0) + 1);
|
||||
fs.writeFileSync(path.join(UPLOADS_DIR, name), buf);
|
||||
content.noteUpload(name, s.email, buf.length, ct, ''); bannerspin.noteImage(s.email, name, d.w, d.h, buf.length, ct);
|
||||
const want = bannerspin.SIZES[String(u.searchParams.get('size') || '')];
|
||||
return json(res, 200, { ok: true, url: '/uploads/' + name, w: d.w, h: d.h, bytes: buf.length, warn: want && d.w && (d.w !== want[0] || d.h !== want[1]) ? 'This image is ' + d.w + 'x' + d.h + '; the Banner Spin is ' + want[0] + 'x' + want[1] + '. It will be stretched to fit.' : '', left: 10 - uploadCounts.get(key) });
|
||||
}
|
||||
m = /^\/api\/my\/bannerspins\/(\d+)(\/stats|\/banner(?:\/(\d+))?)?$/.exec(p);
|
||||
if (m && (req.method === 'GET' || req.method === 'POST')) {
|
||||
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
if (m[2] === '/stats') { const r = await bannerspin.stats(s.email, m[1]); return r ? json(res, 200, r, { 'Cache-Control': 'no-store' }) : json(res, 404, { error: 'No such Banner Spin.' }); }
|
||||
if (req.method !== 'POST') return json(res, 405, { error: 'POST only.' });
|
||||
const b = await readBody(req); let r;
|
||||
if (m[3]) r = await bannerspin.updateBanner(s.email, m[1], m[3], b);
|
||||
else if (m[2]) r = await bannerspin.addBanner(s.email, m[1], b);
|
||||
else r = await bannerspin.update(s.email, m[1], b);
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
// admin: every Banner Spin; the feature switch + tier grants (POST /api/admin/bannerspins { off } | { email, grant }); one Banner Spin or one banner off / on
|
||||
if (p === '/api/admin/bannerspins' && (req.method === 'GET' || req.method === 'POST')) {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
||||
const b = req.method === 'POST' ? await readBody(req) : {};
|
||||
if (b.off != null || b.grant) { const r = bannerspin.setGlobal(b); content.invalidate(); return json(res, r.error ? 400 : 200, r); }
|
||||
return json(res, 200, { spins: bannerspin.adminAll(), settings: bannerspin.settings(), totals: bannerspin.totals() }, { 'Cache-Control': 'no-store' });
|
||||
}
|
||||
m = /^\/api\/admin\/bannerspins\/(\d+)$/.exec(p);
|
||||
if (m && req.method === 'POST') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
||||
const r = bannerspin.adminSet(m[1], await readBody(req)); content.invalidate(); return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
if (p === '/api/my/strip' && req.method === 'GET') { // status strip under every Control Room screen
|
||||
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
let served = 0; try { served = (await rotator.summary(s.email, 1)).totals.served; } catch (e) {}
|
||||
|
||||
Reference in New Issue
Block a user