Files
vbb/loop.js
T
2026-11-14 10:07:41 -06:00

140 lines
7.9 KiB
JavaScript

// The cycle engine. The loop is a list of banner ids, front (index 0) = newest, back = the next to ride out.
// Every `perShift` verified unique visitors the loop shifts one place: the first waiting banner enters at the front and,
// once the loop is full, the banner at the back rides out. That banner has cycled, and its owner's reward (network ad views)
// is recorded in the ledger. While the loop has open places and nobody is waiting, a new banner goes straight in.
// No waiting banner when a shift is due: the bar holds at full and the next posted banner shifts the loop at once.
'use strict';
const cfgMod = require('./config');
const store = require('./store');
const C = () => cfgMod.get();
let onCycle = null;
function init(o) { onCycle = (o && o.onCycle) || null; normalize(); }
// a smaller LOOP_SIZE after a restart: the extra banners at the back ride out (cycle) now, in order
function normalize() {
const S = store.state();
while (S.loop.length > C().loopSize) cycleOut(S.loop.pop());
while (S.loop.length < C().loopSize && S.queue.length) enter(S.queue.shift());
}
function enter(id) {
const S = store.state(); const b = store.banner(id); if (!b) return;
S.loop.unshift(b.id); b.state = 'loop'; b.enteredAt = Date.now(); store.saveBanner(b);
}
function cycleOut(id) {
const b = store.banner(id); if (!b) return null;
b.state = 'cycled'; b.cycledAt = Date.now(); store.saveBanner(b);
const S = store.state(); S.totals.cycles++; S.totals.views += C().viewsPerCycle; store.bump('cycles');
const m = store.member(b.owner);
const e = store.addLedger({ bannerId: b.id, owner: b.owner, username: (m && m.username) || null, views: C().viewsPerCycle, day: store.ctDay(), status: 'recorded' });
if (onCycle) try { onCycle(b, e); } catch (x) {}
return e;
}
// one place forward. -> { shifted, cycled: ledger entry | null }
function shift() {
const S = store.state();
if (!S.queue.length) return { shifted: false, cycled: null };
enter(S.queue.shift());
let cycled = null;
while (S.loop.length > C().loopSize) cycled = cycleOut(S.loop.pop());
S.totals.shifts++; store.bump('shifts'); store.save();
return { shifted: true, cycled };
}
// a new banner (already checked and paid for with a credit)
// spin: a LinkSpin Banner Spin { id, name, size } when the banner is one (the image rotates on LinkSpin, the link is its click link)
function post(owner, img, link, via, spin) {
const S = store.state();
const b = store.addBanner(Object.assign({ owner: String(owner).toLowerCase(), img, link, via: via || 'credit', state: 'queued', clicks: 0 }, spin ? { spin } : {}));
S.totals.posts++; store.bump('posts');
if (!S.queue.length && S.loop.length < C().loopSize) enter(b.id);
else { S.queue.push(b.id); if (S.progress >= C().perShift) { S.progress = 0; shift(); } }
store.save();
return b;
}
// a verified unique visitor arrived. Counting rules (24 hours, IP cap, bots) are checked by the caller via canCount().
function addProgress() {
const S = store.state(); let res = { shifted: false, cycled: null };
S.progress = Math.min(C().perShift, S.progress + 1);
if (S.progress >= C().perShift && S.queue.length) { S.progress = 0; res = shift(); }
store.save();
return res;
}
// ---- verified visitors: once per visitor key per 24 h, at most perIpDay keys per IP per 24 h ----
const lastByVk = new Map(), byIp = new Map();
function rebuildIndex() {
lastByVk.clear(); byIp.clear(); const cut = Date.now() - C().visitWindowHours * 3600000;
for (const v of store.visits()) if (v.at >= cut) { lastByVk.set(v.vk, v.at); (byIp.get(v.iph) || byIp.set(v.iph, []).get(v.iph)).push(v.at); }
}
function canCount(vk, iph) {
const win = C().visitWindowHours * 3600000, now = Date.now();
const last = lastByVk.get(vk); if (last && now - last < win) return { ok: false, why: 'already' };
const list = (byIp.get(iph) || []).filter(t => now - t < win); byIp.set(iph, list);
if (list.length >= C().perIpDay) return { ok: false, why: 'ip' };
return { ok: true };
}
// -> { counted, why?, shifted, cycled }
function verifiedVisit(o) {
const chk = canCount(o.vk, o.iph); if (!chk.ok) return { counted: false, why: chk.why };
const now = Date.now();
lastByVk.set(o.vk, now); (byIp.get(o.iph) || byIp.set(o.iph, []).get(o.iph)).push(now);
if (lastByVk.size > 200000) rebuildIndex();
store.addVisit({ at: now, vk: o.vk, iph: o.iph, ref: o.ref || null, src: o.src || '', wk: store.ctWeek(now), day: store.ctDay(now) });
store.state().totals.visits++; store.bump('visits');
const r = addProgress();
return Object.assign({ counted: true }, r);
}
// ---- weekly leaderboards (Central time, Monday to Sunday) ----
// Ties (Marty 2026-11-14): whoever reached the count first ranks higher. Visitors: the time of their latest counted visitor.
// Sources: the time their latest new source first appeared. Both are order-independent (rows may load in any order).
let lbCache = null;
function leaders(week, n) {
const wk = week || store.ctWeek(); n = n || 10;
if (lbCache && lbCache.wk === wk && lbCache.n0 === n && Date.now() - lbCache.at < 15000 && lbCache.n === store.visits().length) return lbCache.out;
const per = new Map();
for (const v of store.visits()) {
if (v.wk !== wk || !v.ref) continue;
const p = per.get(v.ref) || per.set(v.ref, { address: v.ref, visitors: 0, vAt: 0, src: new Map() }).get(v.ref);
p.visitors++; if (v.at > p.vAt) p.vAt = v.at;
if (v.src) { const f = p.src.get(v.src); if (!f || v.at < f) p.src.set(v.src, v.at); }
}
const rows = [...per.values()].map(p => { const m = store.member(p.address);
return { address: p.address, username: (m && m.username) || null, visitors: p.visitors, sources: p.src.size, visitorsAt: p.vAt, sourcesAt: p.src.size ? Math.max(...p.src.values()) : 0 }; });
const out = { week: wk,
visitors: rows.slice().sort((a, b) => b.visitors - a.visitors || a.visitorsAt - b.visitorsAt).slice(0, n),
sources: rows.filter(r => r.sources > 0).sort((a, b) => b.sources - a.sources || a.sourcesAt - b.sourcesAt).slice(0, n) };
lbCache = { wk, n0: n, at: Date.now(), n: store.visits().length, out };
return out;
}
function memberWeek(addr) {
const a = String(addr).toLowerCase(), wk = store.ctWeek(); let visitors = 0; const src = new Set();
for (const v of store.visits()) if (v.wk === wk && v.ref === a) { visitors++; if (v.src) src.add(v.src); }
return { week: wk, visitors, sources: src.size, sourceHosts: [...src].slice(0, 50) };
}
// ---- views for pages ----
// the banner look (bought per banner, SKU 3): a highlighted border and a hover teaser (the member's line, else the link's site)
const hostOf = l => { try { return new URL(l).hostname.replace(/^www\./, ''); } catch (e) { return ''; } };
function tile(b) { const m = store.member(b.owner); const t = { id: b.id, img: b.img, href: '/go/' + b.id, owner: (m && m.username) ? '@' + m.username : null };
if (b.spin) t.spin = true;
if (b.look) { t.look = true; t.teaser = b.teaser || (b.spin && b.spin.name) || hostOf(b.link); } return t; }
function view(queueShow) {
const S = store.state();
return { loopSize: C().loopSize, perShift: C().perShift, progress: S.progress, waiting: S.queue.length,
loop: S.loop.map(id => store.banner(id)).filter(Boolean).map(tile),
queue: S.queue.slice(0, queueShow || 24).map(id => store.banner(id)).filter(Boolean).map(tile),
held: S.progress >= C().perShift && !S.queue.length, today: store.today(), totals: S.totals };
}
// where a member's banner stands
function placeOf(b) {
const S = store.state();
if (b.state === 'queued') { const i = S.queue.indexOf(b.id); return { state: 'queued', position: i + 1, of: S.queue.length }; }
if (b.state === 'loop') { const i = S.loop.indexOf(b.id); return { state: 'loop', place: i + 1, of: C().loopSize, shiftsToRideOut: Math.max(1, C().loopSize - i) }; }
return { state: b.state };
}
module.exports = { hostOf, init, post, shift, verifiedVisit, canCount, rebuildIndex, leaders, memberWeek, view, placeOf, normalize };