diff --git a/bannerspin.js b/bannerspin.js index 0363c70..ed6091a 100644 --- a/bannerspin.js +++ b/bannerspin.js @@ -28,7 +28,12 @@ // 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). +// switch the whole feature off (a button in Admin > Member content since phase 3). Store: DATA_DIR/bannerspin.json (atomic writes). +// +// Phase 3 (2026-10-20, "Reports and health"): every image load is also counted raw per placement (bots, prefetches and +// servers / mail image proxies kept apart from views), which feeds the "caches banners" flag; stats() and summary() share +// one aggregation (per banner, per placement, by Central day, country and device, a winner once two banners have 1,000 +// views each); health.js checks each live banner's image and target every 30 minutes (b.health, b.autoPaused). 'use strict'; const fs = require('fs'); const path = require('path'); @@ -83,6 +88,11 @@ const vkey = (req, ts) => crypto.createHash('sha256').update(new Date(ts || Date 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(' ')); +// a server fetching the image, not a browser (phase 3, 2026-10-20): mail image proxies and plain HTTP libraries. Kept out of +// impressions like bots, but counted per placement, because a site that copies banners to its own server shows up this way. +const PROXY = /GoogleImageProxy|ggpht\.com|YahooMailProxy|ImageProxy|^(php|java|go-http-client|okhttp|axios|node-fetch|undici|libwww-perl|apache-httpclient|guzzlehttp|ruby)\b/i; +// '' = a browser view (counted), 'pre' = prefetch, 'bot' = bot or no UA, 'srv' = a server or image proxy +const loaderKind = req => isPrefetch(req) ? 'pre' : isBot(req) ? 'bot' : PROXY.test(String(req.headers['user-agent'] || '')) ? 'srv' : ''; // 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 ''; } } @@ -98,18 +108,33 @@ function findNote(keys, s, h) { 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 ── +// a day record: b = counted views per banner, h = per placement host per banner, u = uniques sample per banner, +// bt = bot + prefetch loads, sv = server / image-proxy loads, z = per placement host { r: every load, s: loads with no browser, k: top loaders sample } +const dayRec = sid => { const day = ctDay(); const s = PENDING.d[sid] = PENDING.d[sid] || {}; return s[day] = s[day] || { b: {}, h: {}, u: {}, z: {} }; }; 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: {} }; + const d = dayRec(sid); 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; } +// every image load (counted or not), for bots shown separately and the "caches banners" flag +const LOADERS_CAP = 10; +function rawLoad(sid, host, v, kind) { + const d = dayRec(sid); const hk = host || '(none)'; const z = d.z[hk] = d.z[hk] || { r: 0, s: 0, k: {} }; + z.r++; if (kind === 'bot' || kind === 'srv') z.s++; + const p = v.slice(0, 8); if (z.k[p] != null || Object.keys(z.k).length < LOADERS_CAP) z.k[p] = (z.k[p] || 0) + 1; + if (kind === 'bot' || kind === 'pre') d.bt = (d.bt || 0) + 1; else if (kind === 'srv') d.sv = (d.sv || 0) + 1; + 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); } } } + 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); } + if (x.bt) d.bt = (d.bt || 0) + x.bt; if (x.sv) d.sv = (d.sv || 0) + x.sv; + if (x.z) { d.z = d.z || {}; for (const [h, zz] of Object.entries(x.z)) { let z = d.z[h]; if (!z) { const key = Object.keys(d.z).length >= HOSTS_CAP ? '(other)' : h; z = d.z[key] = d.z[key] || { r: 0, s: 0, k: {} }; } + z.r += zz.r || 0; z.s += zz.s || 0; for (const [p, n] of Object.entries(zz.k || {})) if (z.k[p] != null || Object.keys(z.k).length < LOADERS_CAP) z.k[p] = (z.k[p] || 0) + n; } } } } return base; } function flush() { @@ -162,7 +187,8 @@ function pub(s, extra) { 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: 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), + autoPaused: b.autoPaused || 0, health: b.health ? { state: b.health.state, note: b.health.note || '', checkedAt: b.health.checkedAt || 0, fails: b.health.fails || 0, image: b.health.image || null, target: b.health.target || null } : null })), 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)); } @@ -203,10 +229,10 @@ async function updateBanner(owner, id, bid, body) { 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.active != null) { b.active = !!body.active; delete b.autoPaused; } // the owner's own pause / resume wins over the health checker 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.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 }); delete b.health; } + 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; delete b.health; } 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) }; } @@ -243,7 +269,8 @@ function choose(s, req, opts) { 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 kind = loaderKind(req); rawLoad(String(s.id), hostOf(req), v, kind); + if (!kind) { 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); @@ -287,7 +314,7 @@ async function click(code, req, reqHost) { 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 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|banner|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); @@ -308,28 +335,87 @@ async function convert(lsid, ev, facts) { 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 ── +// ── stats (phase 3, 2026-10-20): one aggregation for the builder's Stats tab and the Reports screen ── +// Views are the counted impressions (bots, prefetches and servers left out); bots and server loads are reported beside +// them. Clicks are rows (bots flagged), so day / country / device come from human clicks, the same way spin links report. +// sinceTs = 0 means all time (the builder); Reports passes its range. Day keys are Central time. +const WIN_MIN = 1000; // a winner needs this many views on every banner it is compared with +const ctrOf = o => o.imps ? Math.round(o.clicks / o.imps * 10000) / 100 : null; +const mrOf = o => o.clicks ? Math.round(o.matched / o.clicks * 100) : null; +function agg(spins, sinceTs) { + const sinceDay = sinceTs ? ctDay(sinceTs) : ''; + const ids = new Set(spins.map(s => s.id)); + const blank = () => ({ imps: 0, clicks: 0, matched: 0, unmatched: 0, uniq: 0, conv: 0, bots: 0, botClicks: 0, srv: 0, raw: 0, top: {} }); + const at = (o, k) => (o[k] = o[k] || blank()); + const per = {}, hosts = {}, days = {}, T = blank(); + for (const s of spins) for (const [day, d] of Object.entries(countsOf(s.id))) { + if (sinceDay && day < sinceDay) continue; + const dd = at(days, day); + for (const [b, n] of Object.entries(d.b || {})) { at(per, s.id + ':' + b).imps += n; dd.imps += n; T.imps += n; } + for (const [b, arr] of Object.entries(d.u || {})) { at(per, s.id + ':' + b).uniq += arr.length; dd.uniq += arr.length; T.uniq += arr.length; } + for (const [h, m] of Object.entries(d.h || {})) for (const n of Object.values(m)) at(hosts, h).imps += n; + dd.bots += d.bt || 0; T.bots += d.bt || 0; dd.srv += d.sv || 0; T.srv += d.sv || 0; + for (const [h, z] of Object.entries(d.z || {})) { const o = at(hosts, h); o.raw += z.r || 0; o.srv += z.s || 0; for (const [k, n] of Object.entries(z.k || {})) o.top[k] = (o.top[k] || 0) + n; } + } + const country = {}, device = {}; + for (const c of J.db.clicks) { + if (!ids.has(c.s) || (sinceTs && c.ts < sinceTs)) continue; + const dd = at(days, ctDay(c.ts)); + if (c.bot) { T.botClicks++; dd.botClicks++; continue; } + const ok = c.m === 'exact' || c.m === 'note'; + for (const o of [at(per, c.s + ':' + c.b), at(hosts, c.h || '(none)'), dd, T]) { o.clicks++; if (ok) o.matched++; else if (c.m === 'none') o.unmatched++; } + const k = c.c || '(none)'; country[k] = (country[k] || 0) + 1; const dv = c.dv || '(none)'; device[dv] = (device[dv] || 0) + 1; + } + const convBy = {}; + for (const c of J.db.conv) { if (!ids.has(c.s) || (sinceTs && c.ts < sinceTs)) continue; at(per, c.s + ':' + c.b).conv++; T.conv++; at(days, ctDay(c.ts)).conv++; const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; } + return { per, hosts, days, T, country, device, convBy }; +} +// the "caches banners" flag: a placement whose image loads come from a server instead of browsers, or whose clicks +// cannot be tied to a view (a copied image never asks us, so the click arrives with no note). '' when it looks normal. +function cacheFlag(o) { + if (o.srv >= 5 && o.srv >= o.raw * 0.5) return 'Most image loads here come from a server, not a browser (' + o.srv + ' of ' + o.raw + '). This site most likely copies banners to its own server, so the rotation is frozen there.'; + const top = Math.max(0, ...Object.values(o.top || {})); + if (o.raw >= 50 && top >= o.raw * 0.8 && o.clicks <= o.raw * 0.01) return 'One loader made ' + Math.round(top / o.raw * 100) + '% of the ' + o.raw + ' image loads here and almost nobody clicks. This site most likely caches banners, so the rotation is frozen there.'; + // more clicks than views alone is not enough (one visitor's reloads count once a minute, clicks are not deduped): a copy also leaves the clicks unmatched + if (o.clicks >= 10 && o.clicks > o.imps && o.matched / o.clicks < 0.5) return 'More clicks (' + o.clicks + ') than views we served (' + o.imps + '). This site shows a copy of the banner, so the rotation is frozen there and clicks go to the fallback.'; + if (o.clicks >= 10 && o.matched / o.clicks < 0.3) return 'Only ' + Math.round(o.matched / o.clicks * 100) + '% of clicks here match a view. This site most likely caches banners, so the rotation is frozen there.'; + return ''; +} +// winner: among the live banners of one Banner Spin with at least WIN_MIN views each, the one with the best CTR (strictly ahead) +function winnerOf(rows) { + const q = rows.filter(r => r.imps >= WIN_MIN && r.ctr != null).sort((a, b) => b.ctr - a.ctr); + return q.length >= 2 && q[0].ctr > q[1].ctr ? q[0].id : 0; +} +const listOf = m => Object.entries(m).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })); +const dayRows = (days, sinceDay) => Object.entries(days).filter(([d]) => !sinceDay || d >= sinceDay).sort().map(([day, o]) => ({ day, imps: o.imps, clicks: o.clicks, bots: o.bots, botClicks: o.botClicks, servers: o.srv, conv: o.conv })); +const placementRows = hosts => Object.entries(hosts).map(([host, o]) => ({ host, imps: o.imps, clicks: o.clicks, ctr: ctrOf(o), matchRate: mrOf(o), loads: o.raw, serverLoads: o.srv, caches: cacheFlag(o) })) + .filter(p => p.imps || p.clicks || p.loads).sort((a, b) => b.imps - a.imps || b.clicks - a.clicks).slice(0, 30); + 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; + const A = agg([s], 0); const z = blank0(); + const banners = s.banners.map(b => { const o = A.per[s.id + ':' + b.id] || z; 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: ctrOf(o), matchRate: mrOf(o), conversions: o.conv }; }); + const win = winnerOf(banners.filter(b => b.active)); for (const b of banners) b.winner = b.id === win; + const fb = A.per[s.id + ':0'] || z; + return { spin: pub(s), totals: { imps: A.T.imps, clicks: A.T.clicks, ctr: ctrOf(A.T), matchRate: mrOf(A.T), matched: A.T.matched, unmatched: A.T.unmatched, uniquesSampled: A.T.uniq, conversions: A.T.conv, bots: A.T.botClicks, botLoads: A.T.bots, serverLoads: A.T.srv }, + banners, winner: win, winMin: WIN_MIN, fallback: { imps: fb.imps, clicks: fb.clicks, ctr: ctrOf(fb) }, + placements: placementRows(A.hosts), days: dayRows(A.days, ctDay(Date.now() - 30 * DAY)), country: listOf(A.country), device: listOf(A.device), + conversions: Object.entries(A.convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) }; +} +const blank0 = () => ({ imps: 0, clicks: 0, matched: 0, unmatched: 0, uniq: 0, conv: 0 }); +// Reports screen: every Banner Spin the member owns over the last `days`, totals + per banner + per placement + day / country / device +async function summary(owner, days) { + const list = mine(owner); const n = Math.max(1, Math.min(365, Number(days) || 30)); const since = Date.now() - n * DAY; + const A = agg(list, since); const z = blank0(); const banners = []; + for (const s of list) { + const rows = s.banners.map(b => { const o = A.per[s.id + ':' + b.id] || z; return { spinId: s.id, spin: s.name, code: s.code, size: s.size, id: b.id, label: b.label || 'Banner ' + b.id, image: b.image, active: !!b.active, autoPaused: !!b.autoPaused, imps: o.imps, uniques: o.uniq, clicks: o.clicks, ctr: ctrOf(o), matchRate: mrOf(o), conversions: o.conv }; }); + const win = winnerOf(rows.filter(r => r.active)); for (const r of rows) { r.winner = r.id === win; banners.push(r); } } - 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 })) }; + banners.sort((a, b) => b.imps - a.imps || b.clicks - a.clicks); + const spins = list.map(s => { let imps = 0, clicks = 0, conv = 0; for (const b of s.banners.concat([{ id: 0 }])) { const o = A.per[s.id + ':' + b.id]; if (o) { imps += o.imps; clicks += o.clicks; conv += o.conv; } } return { id: s.id, name: s.name, code: s.code, size: s.size, imps, clicks, ctr: imps ? Math.round(clicks / imps * 10000) / 100 : null, conversions: conv }; }).sort((a, b) => b.imps - a.imps); + return { count: list.length, totals: { imps: A.T.imps, uniques: A.T.uniq, clicks: A.T.clicks, ctr: ctrOf(A.T), matchRate: mrOf(A.T), matched: A.T.matched, unmatched: A.T.unmatched, conversions: A.T.conv, bots: A.T.bots, botClicks: A.T.botClicks, serverLoads: A.T.srv }, + days: dayRows(A.days, ctDay(since)), country: listOf(A.country), device: listOf(A.device), banners: banners.slice(0, 50), placements: placementRows(A.hosts), spins, winMin: WIN_MIN, + conversions: Object.entries(A.convBy).sort((a, b) => b[1] - a[1]).map(([k, c]) => ({ k, n: c })) }; } // ── admin ── @@ -372,5 +458,9 @@ function readImage(name) { 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 }; +// raw access for health.js (phase 3): the same store and save, and where a banner image lives ({ file } on disk or { url }) +const rawSpins = () => J.db.spins; +const save = () => J.save(); +function imageSource(img) { const m = LOCAL_IMG.exec(String(img || '')); return m ? { file: path.join(UPLOADS_DIR, m[1]) } : /^https:\/\//i.test(String(img || '')) ? { url: String(img) } : null; } +const _test = { notes: () => NOTES, flush, vkey, cacheFlag, winnerOf }; +module.exports = { init, SIZES, TIERS, MAX_BYTES, tierFor, list, create, update, addBanner, updateBanner, noteImage, dims, image, script, click, convert, stats, summary, adminAll, adminSet, setGlobal, settings, imageRefs, totals, blankPng, readImage, flush, findMine, rawSpins, save, imageSource, live, _test }; diff --git a/health.js b/health.js index 259d46c..d8537ab 100644 --- a/health.js +++ b/health.js @@ -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, '&').replace(//g, '>'); + const html = '
LinkSpin paused one banner in your Banner Spin ' + esc(s.name) + ' because it failed three checks in a row.
' + + '' + esc(b.label || 'Banner ' + b.id) + '
' + esc((b.health && b.health.note) || '') + '
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.
'; + 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 }; diff --git a/public/admin.html b/public/admin.html index 7042b57..7e2760a 100644 --- a/public/admin.html +++ b/public/admin.html @@ -218,6 +218,12 @@