Files
vbb/loop.js
T
martbost 8e6d2f9cd0 One swap per banner + admin takedown (Marty 2026-11-15: "allow the member to swap it only, and they can only do it one time. Admin takes down the option to credit back or none.")
Member swap: My Banners shows "Swap image or link" on a banner that is waiting or in the loop, usable once (then "Swap used"). POST /api/my/banners/<id>/swap changes the image and/or link (or a Banner Spin to another of the member's own 125x125/250x250 spins via lsspins), same checks as a new post (checkLink, probeLink, upload/https image checks); id, place, clicks and loop progress stay. Logged on the banner (swaps: old/new image + link, time). No withdraw, removal or refund for members.

Admin takedown: /admin finds banners (#id, wallet, username), POST /api/admin/banners/<id>/takedown {reason required, credit: back|none}. The banner is hidden at once (splash loop + waiting line show a house tile in its place, /go goes home, no look/teaser/swap); its place rides out on time so nobody moves, then it ends with no cycle, no network views, no prize count. My Banners shows "Taken down" with the reason. Restore reverses a given credit (when the owner still holds one) and, if its place rode out meanwhile, records the cycle then. Admin ledger: GET /api/admin/actions (who, when, reason, credit decision).

Chatbot: CANNED 'swap' + FACTS line (KNOWLEDGE_DATE already 2026-11-15), chat-qa entry. my.js?v=4, admin.js?v=3, vbb.css?v=8.
Tests: smoke section 15 (swap once, refused twice, keeps place, bad link/image refused, spin swap, takedown credit back vs none, others keep places, ride-out without a cycle, restore, admin ledger, phone UI): 308/308 with the committed networksso.js; chatbot.test 182/182; qa:chain 49/49.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:18:49 -06:00

154 lines
8.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;
// taken down by the admin (Marty 2026-11-15): its place rode out on time, but it never cycles and never earns
if (b.down) { b.state = 'ended'; b.endedAt = Date.now(); store.saveBanner(b); return null; }
b.state = 'cycled'; b.cycledAt = Date.now(); store.saveBanner(b);
return recordCycle(b);
}
// the cycle reward: one ledger row (also used when the admin restores a banner whose place rode out while it was taken down)
function recordCycle(b, extra) {
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(Object.assign({ bannerId: b.id, owner: b.owner, username: (m && m.username) || null, views: C().viewsPerCycle, day: store.ctDay(), status: 'recorded' }, extra || {}));
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 ''; } };
// a banner the admin took down keeps its place (nobody else moves) but shows as a house tile: no image, owner, link or id of its own
const houseTile = b => ({ id: 'h' + b.id, house: true, img: '/art/tile-house.svg', href: '/my', owner: null });
function tile(b) { if (b.down) return houseTile(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 };
}
// a member-facing place: a taken-down banner says so (with the admin's reason), whatever its slot is doing
function memberPlace(b) {
const p = placeOf(b);
if (!b.down) return p;
return { state: 'down', slot: p.state, downAt: b.down.at, downReason: b.down.reason, creditBack: !!b.down.creditBack };
}
module.exports = { hostOf, init, post, shift, verifiedVisit, canCount, rebuildIndex, leaders, memberWeek, view, placeOf, memberPlace, recordCycle, normalize };