Banner Spin phase 3: reports, health checks, postbacks verified, admin switch button

- bannerspin.js: every image load also counted raw per placement (bots/prefetch and servers/mail image proxies kept apart from views); one aggregation for the Stats tab and a new summary() for Reports: per banner (views, uniques, clicks, CTR, match rate, conversions), per placement with a "caches banners" flag, by Central day, country and device, bots shown separately; WINNER badge once two live banners have 1,000 views each and one leads on CTR. Click params now keep the banner macro (same list as spin links). Owner pause/resume clears an auto-pause; a new image or target resets health.
- health.js: the 30-minute pass also checks each live banner: image must load as an image (magic bytes) at the Banner Spin size, target must pass the spin-link checks (a spin-link target only has to exist). 3 failures pause, 2 clean passes resume, the last live banner is never auto-paused; owner gets an inbox notice. checkBannerSpins() for admin.
- server.js (own blocks): health.init gets bannerspin; /api/my/reports adds bannerSpins; POST /api/admin/bannerspins/health runs the checks now.
- Builder: health line + AUTO-PAUSED tag on every banner row; Stats tab adds uniques, WINNER, CACHED placements, loads, country/device, bots line.
- Reports screen: Banner Spin section + Banner views/clicks tiles beside spin links.
- Admin > Member content: real Banner Spin on/off button (with confirm) and "Run banner checks".
- Traffic-source postbacks on Banner Spin clicks verified end to end (network click id, event, payout, lsid reach the source postback).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-20 05:39:50 -05:00
parent a9994e708d
commit f93bca81a7
9 changed files with 334 additions and 55 deletions
+104 -6
View File
@@ -10,7 +10,12 @@
const fs = require('fs');
const path = require('path');
let rotator = null, DATA_DIR = null, notify = null;
// Banner Spin (phase 3, 2026-10-20): the same pass also checks every live banner. Its IMAGE must load as an image
// (PNG / GIF / JPEG / WebP by magic bytes, an uploaded file read from disk, a pasted one fetched) at the Banner Spin's size,
// and its TARGET must pass check() above (a spin-link target only has to exist: its destinations are checked as spin
// links). Same counters: three failing checks pause the banner (b.active = false, b.autoPaused), two clean passes resume
// it, auto-paused ones are re-checked every 6 hours, and the last live banner of a Banner Spin is NEVER auto-paused.
let rotator = null, DATA_DIR = null, notify = null, bannerspin = null;
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36 LinkSpinHealth/1.0';
const TIMEOUT = 10000, SLOW = 6000, MAX_REDIRECTS = 5, PARALLEL = 4, FAILS_TO_PAUSE = 3, PASSES_TO_RESUME = 2;
const RECHECK_PAUSED = 6 * 3600 * 1000, MANUAL_GAP = 60 * 1000;
@@ -20,7 +25,7 @@ const L = { file: () => path.join(DATA_DIR, 'health-log.json'), db: null,
load() { try { this.db = JSON.parse(fs.readFileSync(this.file(), 'utf8')); } catch (e) { this.db = { events: [] }; } },
add(ev) { if (!this.db) this.load(); this.db.events.push(Object.assign({ ts: Date.now(), day: ctDay(Date.now()) }, ev)); if (this.db.events.length > 500) this.db.events = this.db.events.slice(-400); try { fs.writeFileSync(this.file(), JSON.stringify(this.db)); } catch (e) {} } };
function init(opts) { rotator = opts.rotator; DATA_DIR = opts.dataDir; notify = opts.notify || null; L.load(); }
function init(opts) { rotator = opts.rotator; DATA_DIR = opts.dataDir; notify = opts.notify || null; bannerspin = opts.bannerspin || null; L.load(); }
// one request with a hard timeout; returns the Response or throws
async function req(url, method, signalMs) {
@@ -116,12 +121,105 @@ async function runAll(jobs) {
let i = 0; const workers = new Array(Math.min(PARALLEL, jobs.length)).fill(0).map(async () => { while (i < jobs.length) { const j = jobs[i++]; try { await j(); } catch (e) {} } });
if (workers.length) await Promise.all(workers);
}
// ── Banner Spin banners ──
const MAGIC = buf => buf.length >= 12 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 ? 'image/png' : buf.length >= 6 && buf.slice(0, 4).toString('latin1') === 'GIF8' ? 'image/gif'
: buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff ? 'image/jpeg' : buf.length >= 12 && buf.slice(0, 4).toString('latin1') === 'RIFF' && buf.slice(8, 12).toString('latin1') === 'WEBP' ? 'image/webp' : '';
async function headBytes(res, max) {
if (!res.body) return Buffer.alloc(0);
const reader = res.body.getReader(); const chunks = []; let n = 0;
try { while (n < max) { const { done, value } = await reader.read(); if (done) break; chunks.push(Buffer.from(value)); n += value.length; } } catch (e) {}
try { reader.cancel().catch(() => {}); } catch (e) {}
return Buffer.concat(chunks);
}
// one banner image -> { state: ok | broken | size, note, w, h, ms }
async function checkImage(src, size) {
const t0 = Date.now(); const [W, H] = size || [0, 0];
const where = bannerspin && bannerspin.imageSource ? bannerspin.imageSource(src) : null;
if (!where) return { state: 'broken', note: 'No image address', w: 0, h: 0, ms: 0 };
let buf, type = '';
if (where.file) {
try { buf = fs.readFileSync(where.file); } catch (e) { return { state: 'broken', note: 'The uploaded image file is missing', w: 0, h: 0, ms: Date.now() - t0 }; }
} else {
try {
const { res } = await follow(where.url, 'GET');
if (res.status >= 400 || res.status < 200) { try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {} return { state: 'broken', note: 'The image address answers HTTP ' + res.status, w: 0, h: 0, ms: Date.now() - t0 }; }
type = String(res.headers.get('content-type') || '').toLowerCase();
buf = await headBytes(res, 65536);
} catch (e) { return { state: 'broken', note: (e && e.name === 'AbortError') ? 'The image did not load in 10 s' : 'The image address could not be reached', w: 0, h: 0, ms: Date.now() - t0 }; }
}
const mime = MAGIC(buf); const ms = Date.now() - t0;
if (!mime) return { state: 'broken', note: /^text\/html/.test(type) ? 'The image address returns a web page, not an image' : 'The file is not a readable image', w: 0, h: 0, ms };
const d = mime === 'image/webp' ? { w: 0, h: 0 } : bannerspin.dims(buf, mime);
if (d.w && d.h && W && (d.w !== W || d.h !== H)) return { state: 'size', note: 'The image is ' + d.w + 'x' + d.h + '; this Banner Spin is ' + W + 'x' + H, w: d.w, h: d.h, ms };
return { state: 'ok', note: d.w ? '' : 'Loads as an image (size not readable)', w: d.w, h: d.h, ms };
}
// one banner target -> the spin-link check shape. A spin link only has to still exist.
async function checkTarget(s, b) {
if (b.link) { const r = rotator && rotator.rawRotations ? rotator.rawRotations().find(x => x.id === b.link && x.owner === s.owner) : null; return r ? { state: 'ok', code: 0, ms: 0, note: 'Spin link /r/' + r.code + ' (its pages are checked as spin links)' } : { state: 'dead', code: 0, ms: 0, note: 'The spin link this banner points at was deleted' }; }
if (!b.target) return { state: 'dead', code: 0, ms: 0, note: 'No target set' };
return check(String(b.target).replace(/\{[a-z0-9_]{1,24}\}/gi, 'x')); // macros filled with a placeholder, like a real click would
}
// apply both results to the banner: counters, auto-pause (never the last live banner), auto-resume
function applyBanner(s, b, img, tgt) {
const prev = b.health || {}; const now = Date.now();
const bad = img.state !== 'ok' || failing(tgt.state);
const fails = bad ? (prev.fails || 0) + 1 : 0, passes = bad ? 0 : (prev.passes || 0) + 1;
const note = img.state !== 'ok' ? img.note : failing(tgt.state) ? (tgt.state === 'parked' ? 'Target is a parked page' : 'Target page is down') + (tgt.note ? ' (' + tgt.note + ')' : '') : tgt.state === 'slow' ? 'Target is slow' + (tgt.note ? ' (' + tgt.note + ')' : '') : '';
b.health = { state: img.state !== 'ok' ? 'image' : tgt.state, note, checkedAt: now, fails, passes,
image: { state: img.state, note: img.note || '', w: img.w || 0, h: img.h || 0 }, target: { state: tgt.state, code: tgt.code || 0, ms: tgt.ms || 0, note: tgt.note || '' } };
if (b.active && !b.adminOff && fails >= FAILS_TO_PAUSE) {
const others = s.banners.filter(x => x !== b && x.active && !x.adminOff);
if (!others.length) { b.health.note = note + '. Kept live: it is the last live banner in this Banner Spin.'; return null; }
b.active = false; b.autoPaused = now; b.health.passes = 0;
L.add({ ev: 'pause', bs: s.id, b: b.id, url: b.image, state: b.health.state, note });
return { kind: 'paused', text: note + ', auto-paused ' + when(now) };
}
if (!b.active && b.autoPaused && passes >= PASSES_TO_RESUME) {
b.active = true; delete b.autoPaused; b.health.fails = 0;
L.add({ ev: 'resume', bs: s.id, b: b.id, url: b.image, state: b.health.state });
return { kind: 'resumed', text: 'Back up, resumed ' + when(now) };
}
return null;
}
async function tellBanner(s, b, change) {
if (!notify || !change || change.kind !== 'paused') return;
const esc = x => String(x).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const html = '<p>LinkSpin paused one banner in your Banner Spin <b>' + esc(s.name) + '</b> because it failed three checks in a row.</p>'
+ '<p>' + esc(b.label || 'Banner ' + b.id) + '<br>' + esc((b.health && b.health.note) || '') + '</p>'
+ '<p>Your other banners keep rotating. If it comes back, LinkSpin resumes it on its own after two clean checks. You can also fix the image or the target, or resume it yourself, under Links, Banner Spins.</p>';
try { await notify(s.owner, 'A banner in ' + s.name + ' was paused', html); } catch (e) {}
}
// the banner jobs for one pass. force = check auto-paused ones now too (admin "run checks"); onlyId = one Banner Spin
function bannerJobs(force, onlyId, onChange) {
if (!bannerspin || !bannerspin.rawSpins || (bannerspin.live && !bannerspin.live())) return [];
const now = Date.now(); const jobs = [];
for (const s of bannerspin.rawSpins()) {
if (s.adminOff || (onlyId && s.id !== Number(onlyId))) continue;
const size = bannerspin.SIZES[s.size];
for (const b of s.banners) {
if (b.adminOff) continue;
const due = (b.active) || (b.autoPaused && (force || !b.health || now - (b.health.checkedAt || 0) >= RECHECK_PAUSED));
if (!due) continue;
jobs.push(async () => { const [img, tgt] = await Promise.all([checkImage(b.image, size), checkTarget(s, b)]); const ch = applyBanner(s, b, img, tgt); onChange(); if (ch) await tellBanner(s, b, ch); });
}
}
return jobs;
}
// admin "run the checks now" for Banner Spins (no once-a-minute limit; auto-paused banners are re-checked at once)
let bannerRunning = false;
async function checkBannerSpins(opts) {
opts = opts || {}; if (bannerRunning) return { error: 'A check is already running.' }; bannerRunning = true;
let n = 0; try { const jobs = bannerJobs(true, opts.id, () => { n++; }); await runAll(jobs); } finally { bannerRunning = false; if (n && bannerspin) bannerspin.save(); }
return { ok: true, checked: n };
}
let running = false;
// the scheduled pass: active destinations + fallbacks every time; auto-paused destinations when 6 h have gone by
async function tick() {
if (running || !rotator) return { skipped: true }; running = true;
const now = Date.now(); const jobs = []; let changed = false, n = 0;
const now = Date.now(); const jobs = []; let changed = false, n = 0, bn = 0;
try {
jobs.push(...bannerJobs(false, 0, () => { bn++; })); // Banner Spin banners, same pass, same 4-at-once limit
for (const r of rotator.rawRotations()) {
for (const d of r.destinations) {
const due = d.active || (d.autoPaused && (!d.health || now - (d.health.checkedAt || 0) >= RECHECK_PAUSED));
@@ -131,8 +229,8 @@ async function tick() {
if (r.fallback) jobs.push(async () => { const c = await check(r.fallback); r.fallbackHealth = { state: c.state, code: c.code, ms: c.ms, checkedAt: Date.now(), note: c.note, frameBlocked: !!c.frameBlocked }; changed = true; });
}
await runAll(jobs);
} finally { running = false; if (changed) rotator.save(); }
return { checked: n };
} finally { running = false; if (changed) rotator.save(); if (bn && bannerspin) bannerspin.save(); }
return { checked: n, banners: bn };
}
// "Check now" for one rotation (owner-scoped, once a minute): every destination, paused ones too, plus the fallback
const lastManual = new Map();
@@ -146,4 +244,4 @@ async function checkRotation(owner, id) {
return { ok: true, rotation: rotator.pub(r) };
}
function recent() { if (!L.db) L.load(); return L.db.events.slice(-50).reverse(); }
module.exports = { init, tick, check, checkRotation, recent };
module.exports = { init, tick, check, checkRotation, recent, checkImage, checkBannerSpins };