Merge rotator track: dayparting (7x24 grid, tz by name, best hours) + automatic destination health checks

This commit is contained in:
martbost
2026-10-10 11:22:58 -05:00
5 changed files with 378 additions and 23 deletions
+149
View File
@@ -0,0 +1,149 @@
// Destination health checks (LinkSpin, 2026-10-10): every 30 minutes each ACTIVE destination of every rotation
// (and the fallback) is fetched with a browser-like UA, HEAD first then GET when the server refuses HEAD or when
// the page is HTML (the body is what tells a parked page from a live one). States: ok, slow (over 6 s), dead
// (network error, timeout, 404/410/5xx), parked (parking-page signatures). Three failing checks in a row pause
// the destination (d.active = false, d.autoPaused = when); a paused one is re-checked every 6 hours and comes back
// on its own after two clean passes, but only when LinkSpin paused it, never when the owner did. The last live
// destination of a rotation with no fallback is never paused: a redirect to something beats a dead end.
// frameBlocked is informational: LinkSpin links run inside traffic-exchange frames, so the owner wants to know.
// At most 4 requests in flight at once. A small event log (Central-time day keys) sits at DATA_DIR/health-log.json.
const fs = require('fs');
const path = require('path');
let rotator = null, DATA_DIR = null, notify = 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;
const PARKED = /domain is for sale|this domain (?:is|may be) for sale|parked free|sedoparking|sedo\.com\/search|buy this domain|godaddy\.com\/parked|hugedomains|afternic|\bdan\.com\b|parkingcrew|bodis\.com|domain parking|this domain has expired|<title>\s*(?:default web page|welcome to nginx!?|apache2 .* default page|index of \/|website coming soon|domain default page)\s*<\/title>/i;
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
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(); }
// one request with a hard timeout; returns the Response or throws
async function req(url, method, signalMs) {
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), signalMs || TIMEOUT);
try { return await fetch(url, { method, redirect: 'manual', signal: ac.signal, headers: { 'User-Agent': UA, Accept: 'text/html,application/xhtml+xml,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.8' } }); }
finally { clearTimeout(t); }
}
// follow up to MAX_REDIRECTS by hand (so the chain is bounded and the final URL is known)
async function follow(url, method) {
let u = url, hops = 0, res;
for (;;) {
res = await req(u, method);
if (res.status >= 300 && res.status < 400 && res.headers.get('location') && hops < MAX_REDIRECTS) {
try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {}
u = new URL(res.headers.get('location'), u).toString(); hops++; continue;
}
return { res, finalUrl: u, hops };
}
}
// read at most 64 KB of a body
async function head64k(res) {
if (!res.body) return '';
const reader = res.body.getReader(); const chunks = []; let n = 0;
try { while (n < 65536) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); n += value.length; } } catch (e) {}
try { reader.cancel().catch(() => {}); } catch (e) {}
return Buffer.concat(chunks.map(c => Buffer.from(c))).toString('utf8');
}
const frameBlocked = h => {
const xfo = String(h.get('x-frame-options') || '').toLowerCase(); if (/deny|sameorigin/.test(xfo)) return true;
const csp = String(h.get('content-security-policy') || '').toLowerCase(); const m = /frame-ancestors([^;]*)/.exec(csp);
if (m) { const v = m[1].trim(); return !(v === '*' || /(^|\s)https?:(\s|$)|\*/.test(v)); }
return false;
};
// classify one URL -> { state, code, ms, note, frameBlocked, finalUrl }
async function check(url) {
const t0 = Date.now();
let out = { state: 'dead', code: 0, ms: 0, note: '', frameBlocked: false, finalUrl: url };
try {
let { res, finalUrl } = await follow(url, 'HEAD');
let ms = Date.now() - t0; out.finalUrl = finalUrl;
const ctype = () => String(res.headers.get('content-type') || '').toLowerCase();
let body = '';
if (res.status === 405 || res.status === 501 || res.status === 403 || (res.status >= 200 && res.status < 300 && /html/.test(ctype()))) {
// the server refuses HEAD, or the page is HTML (we need the body to spot a parking page)
try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {}
const t1 = Date.now(); const g = await follow(url, 'GET'); res = g.res; out.finalUrl = g.finalUrl; ms = Date.now() - t1;
if (/html/.test(ctype())) body = await head64k(res); else { try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {} }
} else { try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {} }
out.code = res.status; out.ms = ms; out.frameBlocked = frameBlocked(res.headers);
if (res.status === 404 || res.status === 410 || res.status >= 500) { out.state = 'dead'; out.note = 'HTTP ' + res.status; }
else if (body && PARKED.test(body)) { out.state = 'parked'; out.note = 'Parked page'; }
else if (res.status >= 200 && res.status < 400) { out.state = ms > SLOW ? 'slow' : 'ok'; out.note = ms > SLOW ? 'Slow, ' + (ms / 1000).toFixed(1) + ' s' : ''; }
else { out.state = 'ok'; out.note = 'HTTP ' + res.status + ' to our checker (a bot wall, most likely); visitors may still get through'; }
} catch (e) {
out.ms = Date.now() - t0; out.state = 'dead';
out.note = (e && e.name === 'AbortError') ? 'No answer in 10 s' : ('Could not connect' + (e && e.cause && e.cause.code ? ' (' + e.cause.code + ')' : ''));
}
return out;
}
const failing = s => s === 'dead' || s === 'parked';
const when = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric' });
// apply a fresh result to a destination record: counters, auto-pause, auto-resume. Returns a change note or null.
function apply(r, d, c) {
const prev = d.health || {}; const now = Date.now();
const fails = failing(c.state) ? (prev.fails || 0) + 1 : 0;
const passes = failing(c.state) ? 0 : (prev.passes || 0) + 1;
d.health = { state: c.state, code: c.code, ms: c.ms, checkedAt: now, fails, passes, note: c.note, frameBlocked: !!c.frameBlocked };
if (d.active && fails >= FAILS_TO_PAUSE) {
const others = r.destinations.filter(x => x !== d && x.active);
if (!others.length && !r.fallback) { d.health.note = (c.note || c.state) + '. Kept live: it is the only destination and there is no fallback.'; return null; }
d.active = false; d.autoPaused = now; d.health.passes = 0;
L.add({ ev: 'pause', r: r.id, d: d.id, url: d.url, state: c.state, note: c.note });
return { kind: 'paused', text: (c.state === 'parked' ? 'Parked page' : 'Dead page') + ', auto-paused ' + when(now) };
}
if (!d.active && d.autoPaused && passes >= PASSES_TO_RESUME) {
d.active = true; delete d.autoPaused; d.health.fails = 0;
L.add({ ev: 'resume', r: r.id, d: d.id, url: d.url, state: c.state });
return { kind: 'resumed', text: 'Back up, resumed ' + when(now) };
}
return null;
}
async function tell(r, d, change) {
if (!notify || !change || change.kind !== 'paused' || /^demo:/.test(r.owner)) return;
const esc = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const html = '<p>LinkSpin paused one destination in your link <b>' + esc(r.name) + '</b> (/r/' + esc(r.code) + ') because it failed three checks in a row.</p>'
+ '<p><span style="font-family:monospace">' + esc(d.url) + '</span><br>' + esc(d.health.note || d.health.state) + '</p>'
+ '<p>Visitors keep flowing to your other destinations' + (r.fallback ? ' and the fallback' : '') + '. If the page comes back, LinkSpin resumes it on its own after two clean checks. You can also fix the address or resume it yourself under Links.</p>';
try { await notify(r.owner, 'A destination in ' + r.name + ' was paused', html); } catch (e) {}
}
// run a list of jobs, at most PARALLEL at once
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);
}
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;
try {
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));
if (!due) continue;
jobs.push(async () => { const c = await check(d.url); const ch = apply(r, d, c); changed = true; n++; if (ch) await tell(r, d, ch); });
}
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 };
}
// "Check now" for one rotation (owner-scoped, once a minute): every destination, paused ones too, plus the fallback
const lastManual = new Map();
async function checkRotation(owner, id) {
const r = rotator.findMine(owner, id); if (!r) return { error: 'No such rotation.' };
const last = lastManual.get(r.id) || 0; if (Date.now() - last < MANUAL_GAP) return { error: 'Checked less than a minute ago. Give it a moment.' };
lastManual.set(r.id, Date.now());
const jobs = r.destinations.map(d => async () => { const c = await check(d.url); const ch = apply(r, d, c); if (ch) await tell(r, d, ch); });
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 }; });
await runAll(jobs); rotator.save();
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 };
+103 -8
View File
@@ -7,6 +7,67 @@
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' };
// ── dayparting: grid = 7 strings of 24 chars '1'/'0', index 0 = Sunday; null = always on ──
const ALL = '1'.repeat(24), NONE = '0'.repeat(24);
const rowOf = (a, b) => { let s = ''; for (let h = 0; h < 24; h++) s += h >= a && h < b ? '1' : '0'; return s; };
const PRESETS = { always: null, business: [NONE, rowOf(8, 18), rowOf(8, 18), rowOf(8, 18), rowOf(8, 18), rowOf(8, 18), NONE], evenings: new Array(7).fill(rowOf(17, 23)), weekends: [ALL, NONE, NONE, NONE, NONE, NONE, ALL] };
const ZONES = [['visitor', "Visitor's local time"], ['America/Chicago', 'Chicago (Central)'], ['America/New_York', 'New York (Eastern)'], ['America/Los_Angeles', 'Los Angeles (Pacific)'], ['Europe/London', 'London'], ['Europe/Berlin', 'Berlin'], ['Asia/Kolkata', 'India'], ['Asia/Manila', 'Manila'], ['Asia/Singapore', 'Singapore'], ['Australia/Sydney', 'Sydney']];
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ORDER = [1, 2, 3, 4, 5, 6, 0];
const ranges = s => { const out = []; let a = -1; for (let h = 0; h <= 24; h++) { const on = h < 24 && s[h] === '1'; if (on && a < 0) a = h; if (!on && a >= 0) { out.push(a + '-' + h); a = -1; } } return out.join(', '); };
function hoursText(hours) {
if (!hours || hours.every(s => s === ALL)) return 'Always on';
if (hours.every(s => s === hours[0])) return 'Every day ' + ranges(hours[0]);
const wk = [1, 2, 3, 4, 5], we = [0, 6], off = s => !s.includes('1');
if (wk.every(i => hours[i] === hours[1]) && we.every(i => off(hours[i]))) return 'Mon-Fri ' + ranges(hours[1]);
if (wk.every(i => off(hours[i])) && hours[0] === hours[6]) return 'Weekends' + (hours[6] === ALL ? '' : ' ' + ranges(hours[6]));
const n = hours.join('').split('1').length - 1; return 'Custom, ' + n + ' of 168 hours';
}
const tzText = tz => !tz || tz === 'visitor' ? "visitor's local time" : ((ZONES.find(z => z[0] === tz) || [])[1] || tz.split('/').pop().replace(/_/g, ' ')) + ' time';
const hoursChip = (hours, tz) => hoursText(hours) + (hours ? ', ' + tzText(tz) : '');
// the inline 7 x 24 editor. o = { hours, tz (undefined = no zone picker), heat (7x24 counts), best, onSave(hours, tz), onCancel }
function hoursEditor(host, o) {
let grid = (o.hours || new Array(7).fill(ALL)).map(s => s.split('')); let tz = o.tz || 'visitor';
const other = tz !== 'visitor' && !ZONES.some(z => z[0] === tz);
const max = o.heat ? Math.max(1, ...o.heat.map(d => Math.max(...d))) : 0;
host.innerHTML = '<div class="he">'
+ '<div class="he-presets"><span class="muted" style="font-size:11px">Presets</span>' + [['always', 'Always on'], ['business', 'Business, Mon-Fri 8-18'], ['evenings', 'Evenings, 17-23'], ['weekends', 'Weekends']].map(p => '<button class="btn sm" type="button" data-p="' + p[0] + '">' + p[1] + '</button>').join('')
+ '<button class="btn sm" type="button" data-p="best"' + (o.best && o.best.ready ? '' : ' disabled') + '>Use my best hours</button></div>'
+ (o.tz !== undefined ? '<div class="he-tz"><label class="lbl" style="margin:0">Time zone<select class="field" data-tz>' + ZONES.map(z => '<option value="' + z[0] + '"' + (z[0] === tz ? ' selected' : '') + '>' + esc(z[1]) + '</option>').join('') + '<option value="other"' + (other ? ' selected' : '') + '>Other (type a zone name)</option></select></label><input class="field mono" data-tzo type="text" placeholder="Area/City, like America/Denver"' + (other ? ' value="' + esc(tz) + '"' : ' hidden') + '></div>' : '<div class="muted" style="font-size:11px">Hours follow the link\'s time zone: ' + esc(tzText(o.rotTz)) + '.</div>')
+ '<div class="he-wrap"><div class="he-grid" data-grid><span></span>' + new Array(24).fill(0).map((_, h) => '<span class="hl">' + (h < 10 ? '0' + h : h) + '</span>').join('')
+ ORDER.map(wd => '<span class="dlb" data-day="' + wd + '" title="Flip the whole day">' + DAYS[wd] + '</span>' + new Array(24).fill(0).map((_, h) => '<span class="c" data-wd="' + wd + '" data-h="' + h + '"' + (o.heat && o.heat[wd][h] ? ' style="--heat:' + (0.12 + 0.55 * o.heat[wd][h] / max).toFixed(2) + '" title="' + o.heat[wd][h] + ' unique visitors, ' + DAYS[wd] + ' ' + h + ':00"' : ' title="' + DAYS[wd] + ' ' + h + ':00"') + '></span>').join('')).join('') + '</div></div>'
+ '<div class="he-sum" data-sum></div>'
+ '<div class="muted" style="font-size:11px" data-best>' + (o.best ? (o.best.ready ? 'Your best hours are the top quarter of weekday-hour cells by unique visitors over the last 30 days (' + fmt(o.best.hits) + ' clicks). Tinted cells show where your clicks land.' : '"Use my best hours" unlocks after ' + fmt(o.best.need) + ' clicks in 30 days; ' + fmt(o.best.hits) + ' so far.') : '') + '</div>'
+ '<div class="acts"><button class="btn pri" type="button" data-save>Save hours</button><button class="btn" type="button" data-cancel>Cancel</button><span class="muted" style="font-size:11px">Hours are 0 to 23; 8-18 means 8:00 up to 18:00.</span></div></div>';
const cells = {}; host.querySelectorAll('.c').forEach(c => { cells[c.dataset.wd + ':' + c.dataset.h] = c; if (o.heat && o.heat[c.dataset.wd][c.dataset.h]) c.classList.add('heat'); });
const paint = () => { for (const k in cells) { const [wd, h] = k.split(':'); cells[k].classList.toggle('on', grid[wd][h] === '1'); } const hs = grid.map(d => d.join('')); host.querySelector('[data-sum]').innerHTML = esc(hoursText(hs.every(s => s === ALL) ? null : hs)) + (o.tz !== undefined ? ' <small>' + esc(tzText(tz)) + '</small>' : ''); };
const set = (wd, h, v) => { grid[wd][h] = v; };
let painting = null;
const g = host.querySelector('[data-grid]');
const cellAt = e => { const el = document.elementFromPoint(e.clientX, e.clientY); return el && el.classList.contains('c') && g.contains(el) ? el : null; };
g.addEventListener('pointerdown', e => { const c = cellAt(e); if (!c) return; e.preventDefault(); painting = grid[c.dataset.wd][c.dataset.h] === '1' ? '0' : '1'; set(c.dataset.wd, c.dataset.h, painting); paint(); });
g.addEventListener('pointermove', e => { if (painting == null) return; const c = cellAt(e); if (c && grid[c.dataset.wd][c.dataset.h] !== painting) { set(c.dataset.wd, c.dataset.h, painting); paint(); } });
const stop = () => { painting = null; }; g.addEventListener('pointerup', stop); g.addEventListener('pointercancel', stop); g.addEventListener('pointerleave', stop);
host.querySelectorAll('.dlb').forEach(l => l.addEventListener('click', () => { const wd = l.dataset.day; const v = grid[wd].every(x => x === '1') ? '0' : '1'; grid[wd] = new Array(24).fill(v); paint(); }));
host.querySelectorAll('[data-p]').forEach(b => b.addEventListener('click', () => { const p = b.dataset.p; const src = p === 'best' ? (o.best && o.best.hours) : PRESETS[p]; grid = (src || new Array(7).fill(ALL)).map(s => s.split('')); paint(); }));
const sel = host.querySelector('[data-tz]'), oth = host.querySelector('[data-tzo]');
if (sel) { sel.addEventListener('change', () => { if (sel.value === 'other') { oth.hidden = false; oth.focus(); tz = oth.value.trim() || 'visitor'; } else { oth.hidden = true; tz = sel.value; } paint(); }); oth.addEventListener('input', () => { tz = oth.value.trim() || 'visitor'; paint(); }); }
host.querySelector('[data-save]').addEventListener('click', () => { const hs = grid.map(d => d.join('')); o.onSave(hs.every(s => s === ALL) ? null : hs, o.tz !== undefined ? tz : undefined); });
host.querySelector('[data-cancel]').addEventListener('click', () => o.onCancel && o.onCancel());
host.heState = () => ({ hours: grid.map(d => d.join('')), tz }); // so a redraw can keep unsaved taps
paint();
}
// ── 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' });
const healthCls = h => !h ? '' : h.state === 'ok' ? 'ok' : h.state === 'slow' ? 'warn' : 'bad';
function healthLine(d) {
const h = d.health; if (!h) return 'Not checked yet; the first check runs within 30 minutes';
if (d.autoPaused) return (h.state === 'parked' ? 'Parked page' : h.state === 'dead' ? 'Dead page' : 'Back up') + ', auto-paused ' + mdy(d.autoPaused) + (h.state === 'ok' || h.state === 'slow' ? ', resumes after ' + (2 - (h.passes || 0)) + ' more clean check' + (2 - (h.passes || 0) === 1 ? '' : 's') : ', checked again every 6 hours');
if (h.state === 'ok' || h.state === 'slow') return 'Checked ' + ago(h.checkedAt) + ', ' + h.code + ' in ' + fmt(h.ms) + ' ms' + (h.note ? ', ' + h.note : '');
return 'Checked ' + ago(h.checkedAt) + ', ' + (h.note || h.state) + (d.active ? ', strike ' + h.fails + ' of 3' + (h.fails >= 3 ? ', kept live' : ', pauses at 3') : '');
}
let HE = null; // the destination editor that is open: { rid, did }
async function load(keep) {
let r; try { r = await CR.get('/api/my/rotations'); } catch (e) { CR.sub('could not load'); return; }
ROT = (r.rotations || []).slice().sort((a, b) => clicks7(b) - clicks7(a)); HOSTS = r.hosts || [];
@@ -37,21 +98,36 @@
const h = health(r); $('dLive').innerHTML = '<span class="' + h.cls + '"><span class="dot"></span>' + h.t + '</span>';
$('pauseBtn').textContent = r.paused ? 'Resume' : 'Pause';
$('fallback').value = r.fallback || '';
const fh = r.fallbackHealth; $('fallbackHealth').textContent = r.fallback ? (fh ? 'Fallback checked ' + ago(fh.checkedAt) + ': ' + (fh.state === 'ok' || fh.state === 'slow' ? fh.code + ' in ' + fmt(fh.ms) + ' ms' : (fh.note || fh.state)) + (fh.frameBlocked ? ', blocks frames' : '') : 'Fallback not checked yet') : '';
$('hoursChip').textContent = hoursChip(r.hours, r.tz); $('hoursChip').classList.toggle('set', !!r.hours);
renderTiles(r, STATS[id]);
renderDest(r); renderShare(r);
renderDest(r); renderShare(r); renderRotHours(r, STATS[id]);
if (!quiet) window.scrollTo({ top: 0 });
loadStats(r.id);
}
function renderDest(r) {
const total = r.destinations.filter(d => d.active).reduce((n, d) => n + d.weight, 0) || 1;
$('destRows').innerHTML = r.destinations.length ? r.destinations.map(d => { const share = d.active ? Math.round(d.weight / total * 100) : 0;
return '<div class="rw" data-did="' + d.id + '"><div><div style="font-weight:700">' + esc(d.label || d.url.replace(/^https?:\/\//, '').slice(0, 60)) + '</div><div class="mono muted" style="font-size:11px;overflow-wrap:anywhere">' + esc(d.url) + '</div></div>'
const auto = r.destinations.filter(d => d.autoPaused);
const prevHost = $('destRows').querySelector('[data-he]'); const prev = prevHost && HE && Number(prevHost.dataset.he) === HE.did && prevHost.heState ? prevHost.heState() : null;
$('autoNote').hidden = !auto.length;
if (auto.length) $('autoNote').textContent = 'LinkSpin paused ' + (auto.length === 1 ? 'one destination' : auto.length + ' destinations') + ' automatically after three failed checks: ' + auto.map(d => (d.label || d.url.replace(/^https?:\/\//, '')).slice(0, 40)).join(', ') + '. It comes back on its own after two clean checks, or fix the address and press Resume.';
$('destRows').innerHTML = r.destinations.length ? r.destinations.map(d => { const share = d.active ? Math.round(d.weight / total * 100) : 0; const h = d.health;
return '<div class="rw" data-did="' + d.id + '"><div><div class="dl"><span class="hdot ' + healthCls(h) + '" title="' + esc(healthLine(d)) + '"></span><span style="font-weight:700">' + esc(d.label || d.url.replace(/^https?:\/\//, '').slice(0, 60)) + '</span>' + (d.hours ? '<button class="hchip set" type="button" data-hc="' + d.id + '" title="This destination has its own hours">' + esc(hoursText(d.hours)) + '</button>' : '') + (h && h.frameBlocked ? '<span class="tag warn" title="This page refuses to load inside a frame (X-Frame-Options or CSP). Traffic exchanges that frame your link will show it blank.">no frames</span>' : '') + '</div>'
+ '<div class="mono muted" style="font-size:11px;overflow-wrap:anywhere">' + esc(d.url) + '</div><div class="muted" style="font-size:11px" data-hl="' + d.id + '">' + esc(healthLine(d)) + '</div></div>'
+ '<div class="wrow"><div class="bar" style="width:70px"><i style="width:' + share + '%"></i></div><input class="field mono" type="number" min="1" max="100" value="' + d.weight + '" data-w="' + d.id + '" aria-label="Weight"><span class="mono muted" style="font-size:11px">' + share + '%</span></div>'
+ '<span class="r num">' + fmt(d.hits || 0) + '</span><span class="r num">' + fmt(d.uniques || 0) + '</span>'
+ '<span class="tag ' + (d.active ? 'ok' : 'dim') + '">' + (d.active ? 'LIVE' : 'PAUSED') + '</span>'
+ '<span style="display:flex;gap:6px;justify-content:flex-end"><button class="btn sm" type="button" data-t="' + d.id + '">' + (d.active ? 'Pause' : 'Resume') + '</button><button class="btn sm danger" type="button" data-x="' + d.id + '" aria-label="Remove">&times;</button></span></div>'; }).join('')
+ '<span class="tag ' + (d.active ? 'ok' : d.autoPaused ? 'bad' : 'dim') + '">' + (d.active ? 'LIVE' : d.autoPaused ? 'AUTO-PAUSED' : 'PAUSED') + '</span>'
+ '<span style="display:flex;gap:6px;justify-content:flex-end"><button class="btn sm" type="button" data-hc="' + d.id + '" title="Hours for this destination" aria-label="Hours for this destination"><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="' + d.id + '">' + (d.active ? 'Pause' : 'Resume') + '</button><button class="btn sm danger" type="button" data-x="' + d.id + '" aria-label="Remove">&times;</button></span></div>'
+ (HE && HE.rid === r.id && HE.did === d.id ? '<div class="rw edit" data-he="' + d.id + '"></div>' : ''); }).join('')
: '<div class="rw"><span class="muted">No destinations yet. Add the first page below; until then the link sends people to the fallback.</span></div>';
$('destFoot').textContent = 'weights are shares of the spin · fallback: ' + (r.fallback || 'none set') + ' · bots filtered on the server · one hop';
$('destFoot').textContent = 'weights are shares of the spin · fallback: ' + (r.fallback || 'none set') + ' · bots filtered on the server · one hop · health checked every 30 min';
const openEditor = did => { const d = r.destinations.find(q => q.id === did); if (!d) return; HE = { rid: r.id, did }; renderDest(r); };
$('destRows').querySelectorAll('[data-hc]').forEach(b => b.addEventListener('click', () => { if (HE && HE.rid === r.id && HE.did === Number(b.dataset.hc)) { HE = null; renderDest(r); } else openEditor(Number(b.dataset.hc)); }));
const heHost = $('destRows').querySelector('[data-he]');
if (heHost) { const d = r.destinations.find(q => q.id === Number(heHost.dataset.he)); const s = STATS[r.id];
hoursEditor(heHost, { hours: prev ? prev.hours : d.hours, rotTz: r.tz, heat: s && s.best ? s.best.cells : null, best: s && s.best, onCancel: () => { HE = null; renderDest(r); },
onSave: async hours => { try { await api('/api/my/rotations/' + r.id + '/dest/' + d.id, { hours }); HE = null; toast(hours ? 'Hours saved' : 'Destination is always on'); load(true); } catch (e) { toast(e.message, true); } } });
if (heHost.scrollIntoView) heHost.scrollIntoView({ block: 'nearest' }); }
$('destRows').querySelectorAll('[data-w]').forEach(i => i.addEventListener('change', async () => { try { await api('/api/my/rotations/' + r.id + '/dest/' + i.dataset.w, { weight: i.value }); toast('Weight saved'); load(true); } catch (e) { toast(e.message, true); } }));
$('destRows').querySelectorAll('[data-t]').forEach(b => b.addEventListener('click', async () => { const d = r.destinations.find(q => q.id === Number(b.dataset.t)); try { await api('/api/my/rotations/' + r.id + '/dest/' + d.id, { active: !d.active }); load(true); } catch (e) { toast(e.message, true); } }));
$('destRows').querySelectorAll('[data-x]').forEach(b => b.addEventListener('click', async () => { if (!await dialog({ title: 'Remove this destination?', text: 'Its click history stays in the stats.', ok: 'Remove', danger: true })) return; try { await api('/api/my/rotations/' + r.id + '/dest/' + b.dataset.x, { remove: true }); toast('Removed'); load(true); } catch (e) { toast(e.message, true); } }));
@@ -67,6 +143,19 @@
$('shareKit').innerHTML = kit.map(([t, body], i) => '<div class="panel" style="padding:10px 12px"><div style="display:flex;justify-content:space-between;align-items:center;gap:8px"><b>' + esc(t) + '</b><button class="btn sm" type="button" data-cp="' + i + '">Copy</button></div><div class="mono muted" style="font-size:12px;overflow-wrap:anywhere;margin-top:6px" id="kit-' + i + '">' + esc(body) + '</div></div>').join('');
$('shareKit').querySelectorAll('[data-cp]').forEach(b => b.addEventListener('click', () => CR.copy($('kit-' + b.dataset.cp).textContent)));
}
// the rotation's own hours editor on the Hours tab. Not redrawn while the member is mid-edit (the 60 s refresh would eat their taps).
let RH = null; // { rid, dirty }
function renderRotHours(r, s) {
const host = $('rotHours');
if (RH && RH.rid === r.id && RH.dirty && host.firstChild) return;
RH = { rid: r.id, dirty: false };
hoursEditor(host, { hours: r.hours, tz: r.tz || 'visitor', heat: s && s.best ? s.best.cells : null, best: s && s.best,
onCancel: () => { RH = null; renderRotHours(r, STATS[r.id]); },
onSave: async (hours, tz) => { try { await api('/api/my/rotations/' + r.id, { hours, tz }); RH = null; toast(hours ? 'Hours saved' : 'Link is always on'); load(true); } catch (e) { toast(e.message, true); } } });
host.addEventListener('pointerdown', () => { if (RH) RH.dirty = true; }, { once: true });
host.addEventListener('change', () => { if (RH) RH.dirty = true; }, { once: true });
$('offNote').textContent = s ? ((s.offHours ? fmt(s.offHours) + ' click' + (s.offHours === 1 ? '' : 's') + ' arrived outside the link\'s hours and went to the fallback (all time, ' + fmt(r.offHours30 || 0) + ' in 30 days).' : 'No clicks have gone to the off-hours fallback yet.')) : '';
}
const kv = rows => rows && rows.length ? rows.map(x => '<span style="overflow-wrap:anywhere">' + esc(x.k) + '</span><span class="bar"><i style="width:' + Math.round(x.n / (rows[0].n || 1) * 100) + '%"></i></span><span class="r num">' + fmt(x.n) + '</span>').join('') : '<span class="muted">nothing yet</span><span></span><span></span>';
function renderTiles(r, s) {
let series = null, delta = null;
@@ -84,7 +173,7 @@
async function loadStats(id) {
let s = STATS[id]; if (!s) { try { s = await CR.get('/api/my/rotations/' + id + '/stats'); } catch (e) { return; } STATS[id] = s; setTimeout(() => { delete STATS[id]; }, 60000); }
if (SEL !== id) return;
{ const r = ROT.find(x => x.id === id); if (r) renderTiles(r, s); }
{ const r = ROT.find(x => x.id === id); if (r) { renderTiles(r, s); if (!(RH && RH.rid === id && RH.dirty)) renderRotHours(r, s); } }
const hmax = Math.max(1, ...s.hours); $('hourBars').innerHTML = s.hours.map((n, i) => '<i class="' + (n >= hmax * 0.6 ? '' : 'dim') + '" style="height:' + Math.round(n / hmax * 100) + '%" title="' + i + ':00 · ' + n + '"></i>').join('');
$('srcRows').innerHTML = kv(s.source); $('geoRows').innerHTML = kv(s.country); $('subRows').innerHTML = kv(s.subs); $('convRows').innerHTML = kv(s.conversions);
const dev = s.device || []; const dt = dev.reduce((n, x) => n + x.n, 0) || 1; $('devRow').textContent = dev.length ? dev.map(x => x.k + ' ' + Math.round(x.n / dt * 100) + '%').join(' · ') : '';
@@ -128,7 +217,13 @@
$('addBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const url = $('addUrl').value.trim(); if (!url) { $('addUrl').focus(); return; } try { await api('/api/my/rotations/' + r.id + '/dest', { url, label: $('addLabel').value, weight: $('addWeight').value }); $('addUrl').value = ''; $('addLabel').value = ''; toast('Destination added'); load(true); } catch (e) { toast(e.message, true); } });
$('addUrl').addEventListener('keydown', e => { if (e.key === 'Enter') $('addBtn').click(); });
$('fallback').addEventListener('change', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; try { await api('/api/my/rotations/' + r.id, { fallback: $('fallback').value.trim() }); toast('Fallback saved'); load(true); } catch (e) { toast(e.message, true); } });
$('tabs').querySelectorAll('button').forEach(b => b.addEventListener('click', () => { $('tabs').querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); ['dest', 'hours', 'sources', 'report', 'share'].forEach(t => { $('tab-' + t).hidden = t !== b.dataset.tab; }); }));
const showTab = name => { $('tabs').querySelectorAll('button').forEach(x => x.classList.toggle('on', x.dataset.tab === name)); ['dest', 'hours', 'sources', 'report', 'share'].forEach(t => { $('tab-' + t).hidden = t !== name; }); };
$('tabs').querySelectorAll('button').forEach(b => b.addEventListener('click', () => showTab(b.dataset.tab)));
$('hoursChip').addEventListener('click', () => { showTab('hours'); const h = $('rotHours'); if (h.scrollIntoView) h.scrollIntoView({ block: 'start', behavior: 'smooth' }); });
$('checkBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const b = $('checkBtn'); b.disabled = true; b.textContent = 'Checking';
try { const out = await api('/api/my/rotations/' + r.id + '/health'); const i = ROT.findIndex(x => x.id === r.id); if (i >= 0 && out.rotation) ROT[i] = out.rotation; const fresh = out.rotation || r; renderDest(fresh); select(r.id, true);
const bad = fresh.destinations.filter(d => d.health && (d.health.state === 'dead' || d.health.state === 'parked')).length; toast('Checked ' + fresh.destinations.length + ' destination' + (fresh.destinations.length === 1 ? '' : 's') + (bad ? ', ' + bad + ' failing' : ', all answering')); }
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); });
+28 -4
View File
@@ -23,7 +23,26 @@
.dhead{display:flex;align-items:center;gap:14px;padding:12px 24px;border-bottom:1px solid var(--line);background:var(--panel);flex-wrap:wrap}
.dhead h2{font-family:var(--display);font-size:24px;font-weight:700;letter-spacing:.02em;margin:0}
.dbody{padding:16px 24px;display:grid;gap:14px}
.dest .hd,.dest .rw{grid-template-columns:minmax(0,2fr) 150px 80px 80px 110px 90px}
.dest .hd,.dest .rw{grid-template-columns:minmax(0,2fr) 150px 80px 80px 110px 130px}
.dest .rw.edit{grid-template-columns:1fr;background:var(--panel-2)}
.dest .dl{display:flex;align-items:center;gap:6px;flex-wrap:wrap}
.hdot{display:inline-block;width:9px;height:9px;border-radius:50%;background:var(--line-strong);flex:none;vertical-align:middle}
.hdot.ok{background:var(--ok);box-shadow:0 0 0 2px rgba(14,138,92,.2)} .hdot.warn{background:#D98B0C;box-shadow:0 0 0 2px rgba(217,139,12,.2)} .hdot.bad{background:var(--bad);box-shadow:0 0 0 2px rgba(185,28,28,.2)}
.hchip{display:inline-flex;align-items:center;gap:5px;font-family:var(--mono);font-size:10px;font-weight:700;color:var(--ink-2);border:1px solid var(--line-strong);border-radius:999px;padding:2px 8px;white-space:nowrap;background:#fff;cursor:pointer;letter-spacing:.02em}
.hchip.set{color:var(--sig-2);border-color:rgba(255,106,26,.5);background:var(--sig-soft)}
.he{display:grid;gap:10px}
.he-presets{display:flex;gap:6px;flex-wrap:wrap;align-items:center}
.he-tz{display:flex;gap:8px;align-items:center;flex-wrap:wrap} .he-tz select{width:auto;min-width:180px} .he-tz input{width:200px}
.he-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch;padding-bottom:6px}
.he-grid{display:grid;grid-template-columns:36px repeat(24,22px);gap:2px;touch-action:pan-x;user-select:none;-webkit-user-select:none;width:max-content}
.he-grid .hl{font-family:var(--mono);font-size:9px;font-weight:700;color:var(--muted);text-align:center;align-self:end;line-height:1}
.he-grid .dlb{font-family:var(--mono);font-size:11px;font-weight:700;color:var(--ink-2);align-self:center;cursor:pointer}
.he-grid .c{width:22px;height:22px;border-radius:3px;background:var(--panel-2);border:1px solid var(--line);cursor:pointer;box-sizing:border-box}
.he-grid .c.heat{background:rgba(31,111,235,var(--heat))}
.he-grid .c.on{background:var(--sig);border-color:var(--sig-2)}
.he-sum{font-weight:700} .he-sum small{font-weight:500;color:var(--muted)}
.he .acts{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.note{border:1px solid rgba(194,65,12,.4);background:var(--warn-soft);color:var(--warn);border-radius:8px;padding:8px 12px;font-size:12px}
.wrow{display:flex;align-items:center;gap:8px} .wrow input{width:56px}
.empty{padding:40px 24px;color:var(--muted);text-align:center;display:grid;gap:10px;justify-items:center}
.two{display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:16px}
@@ -52,7 +71,9 @@
<span class="code" id="dUrl"></span>
<button class="btn sm" type="button" id="copyBtn">Copy</button>
<span class="mono" id="dLive"></span>
<button class="hchip" type="button" id="hoursChip" title="Hours this link is on">Always on</button>
<span class="grow"></span>
<button class="btn sm" type="button" id="checkBtn" title="Check every destination right now">Check now</button>
<button class="btn sm" type="button" id="renameBtn">Rename</button>
<button class="btn sm" type="button" id="pauseBtn">Pause</button>
<button class="btn sm danger" type="button" id="delBtn">Delete</button>
@@ -67,6 +88,7 @@
<button type="button" data-tab="share">Share kit</button>
</div>
<div id="tab-dest">
<div class="note" id="autoNote" hidden style="margin-bottom:10px"></div>
<div class="tbl dest">
<div class="hd"><span>Destination</span><span>Weight</span><span class="r">Clicks</span><span class="r">Unique</span><span>Status</span><span></span></div>
<div id="destRows"></div>
@@ -81,11 +103,13 @@
<button class="btn pri" type="button" id="addBtn">Add</button>
</div>
<div class="muted">Macros in a destination are filled per visitor: <span class="mono">{clickid} {subid} {s1}…{s5} {source} {country} {device} {lsid}</span>. Example: <span class="mono">https://tracker.example/?cid={clickid}&amp;src={source}</span></div>
<label class="lbl">Fallback, used when every destination is paused or the link is paused<input class="field mono" id="fallback" type="url" placeholder="https://"></label>
<label class="lbl">Fallback, used when every destination is paused, the link is paused, or the link is outside its hours<input class="field mono" id="fallback" type="url" placeholder="https://"></label>
<div class="muted mono" id="fallbackHealth" style="font-size:11px"></div>
</div>
</div>
<div id="tab-hours" hidden>
<div class="panel"><h2>Clicks by hour, UTC, all time</h2><div class="bars" id="hourBars" style="grid-template-columns:repeat(24,minmax(0,1fr))"></div><div class="axis"><span>00</span><span>06</span><span>12</span><span>18</span><span>23</span></div><div class="muted">Hour rules (open a destination only at set hours) come in the next pass; this is where they will live.</div></div>
<div class="panel"><h2>Hours this link is on</h2><div class="muted">Outside these hours visitors go to the fallback. Each destination can have its own hours too (the clock button on its row). Tap a cell to flip it, drag to paint, or start from a preset.</div><div id="rotHours"></div></div>
<div class="panel" style="margin-top:12px"><h2>Clicks by hour, UTC, all time</h2><div class="bars" id="hourBars" style="grid-template-columns:repeat(24,minmax(0,1fr))"></div><div class="axis"><span>00</span><span>06</span><span>12</span><span>18</span><span>23</span></div><div class="muted" id="offNote"></div></div>
</div>
<div id="tab-sources" hidden>
<div class="two">
@@ -112,6 +136,6 @@
</div>
</div>
<script src="/assets/cr-shell.js?v=20261008c"></script>
<script src="/assets/links.js?v=20260929d"></script>
<script src="/assets/links.js?v=20261010a"></script>
</body>
</html>
+88 -11
View File
@@ -2,7 +2,10 @@
// code and a list of destinations with weights. /r/<code> picks one by weight, records the hit
// (day, country, source, device, a daily-salted visitor hash so uniques are honest, bot filter)
// and redirects in one hop. Destinations can be paused; a fallback catches the empty case.
// Health checks (a dead or parked destination is paused automatically) come in a later pass.
// Health checks (a dead or parked destination is paused automatically) live in health.js (2026-10-10).
// Dayparting (2026-10-10): rotation.hours / destination.hours = null (always on) or 7 strings of 24 chars
// '1'/'0', index 0 = Sunday like JS getDay(); rotation.tz = IANA zone name or 'visitor' (the visitor's
// country picks a representative zone). Zones are stored by NAME, never as an offset.
// JSON store on the volume for the test area; the MySQL twin follows the engine's dual-mode pattern.
const fs = require('fs');
const path = require('path');
@@ -22,16 +25,79 @@ const newCode = () => { const a = 'abcdefghjkmnpqrstuvwxyz23456789'; let s = '';
const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i;
const cleanUrl = 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; };
// ── dayparting ──────────────────────────────────────────────────────────────────────────────────────────────
// representative zone per country for tz = 'visitor' (top ~60 by traffic); unknown or no country -> Central
const COUNTRY_TZ = { US: 'America/Chicago', CA: 'America/Toronto', MX: 'America/Mexico_City', BR: 'America/Sao_Paulo', AR: 'America/Argentina/Buenos_Aires', CL: 'America/Santiago', CO: 'America/Bogota', PE: 'America/Lima', VE: 'America/Caracas',
GB: 'Europe/London', IE: 'Europe/Dublin', PT: 'Europe/Lisbon', ES: 'Europe/Madrid', FR: 'Europe/Paris', DE: 'Europe/Berlin', NL: 'Europe/Amsterdam', BE: 'Europe/Brussels', CH: 'Europe/Zurich', AT: 'Europe/Vienna', IT: 'Europe/Rome', PL: 'Europe/Warsaw', CZ: 'Europe/Prague', HU: 'Europe/Budapest', SE: 'Europe/Stockholm', NO: 'Europe/Oslo', DK: 'Europe/Copenhagen', FI: 'Europe/Helsinki', GR: 'Europe/Athens', RO: 'Europe/Bucharest', BG: 'Europe/Sofia', UA: 'Europe/Kyiv', RU: 'Europe/Moscow', TR: 'Europe/Istanbul', RS: 'Europe/Belgrade', HR: 'Europe/Zagreb', SK: 'Europe/Bratislava', LT: 'Europe/Vilnius', LV: 'Europe/Riga', EE: 'Europe/Tallinn',
ZA: 'Africa/Johannesburg', NG: 'Africa/Lagos', KE: 'Africa/Nairobi', EG: 'Africa/Cairo', MA: 'Africa/Casablanca', GH: 'Africa/Accra',
IN: 'Asia/Kolkata', PK: 'Asia/Karachi', BD: 'Asia/Dhaka', LK: 'Asia/Colombo', NP: 'Asia/Kathmandu', PH: 'Asia/Manila', ID: 'Asia/Jakarta', MY: 'Asia/Kuala_Lumpur', SG: 'Asia/Singapore', TH: 'Asia/Bangkok', VN: 'Asia/Ho_Chi_Minh', HK: 'Asia/Hong_Kong', TW: 'Asia/Taipei', CN: 'Asia/Shanghai', JP: 'Asia/Tokyo', KR: 'Asia/Seoul', AE: 'Asia/Dubai', SA: 'Asia/Riyadh', IL: 'Asia/Jerusalem', IR: 'Asia/Tehran', KZ: 'Asia/Almaty',
AU: 'Australia/Sydney', NZ: 'Pacific/Auckland' };
const DEFAULT_TZ = 'America/Chicago';
const WD = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
const row = (from, to) => { let s = ''; for (let h = 0; h < 24; h++) s += h >= from && h < to ? '1' : '0'; return s; };
const ALL = row(0, 24), NONE = row(0, 0);
const PRESETS = { always: null, business: [NONE, row(8, 18), row(8, 18), row(8, 18), row(8, 18), row(8, 18), NONE], evenings: new Array(7).fill(row(17, 23)), weekends: [ALL, NONE, NONE, NONE, NONE, NONE, ALL] };
// validate a grid from the API: null/'' = always; a preset name; 7 strings of 24 x '1'/'0'; or 7 arrays of 24 booleans
function cleanHours(h) {
if (h == null || h === '' || h === 'always') return { hours: null };
if (typeof h === 'string' && PRESETS[h] !== undefined) return { hours: PRESETS[h] ? PRESETS[h].slice() : null };
if (!Array.isArray(h) || h.length !== 7) return { error: 'Hours must be a 7 by 24 grid.' };
const out = [];
for (const d of h) {
let s = Array.isArray(d) ? d.map(x => x && x !== '0' ? '1' : '0').join('') : String(d || '');
if (!/^[01]{24}$/.test(s)) return { error: 'Hours must be a 7 by 24 grid.' };
out.push(s);
}
if (out.every(s => s === ALL)) return { hours: null };
if (out.every(s => s === NONE)) return { error: 'Pick at least one hour, or choose Always on.' };
return { hours: out };
}
// validate a zone name: 'visitor' or anything Intl knows; stored canonical, never an offset
function cleanTz(tz) {
const s = String(tz || '').trim(); if (!s || s === 'visitor') return { tz: 'visitor' };
if (s.length > 64 || !/^[A-Za-z0-9_+\-\/]+$/.test(s)) return { error: 'That time zone name is not one we know.' };
try { return { tz: new Intl.DateTimeFormat('en', { timeZone: s }).resolvedOptions().timeZone }; } catch (e) { return { error: 'That time zone name is not one we know. Use a name like America/New_York.' }; }
}
const zoneFor = (r, country) => (r.tz && r.tz !== 'visitor') ? r.tz : (COUNTRY_TZ[String(country || '').toUpperCase()] || DEFAULT_TZ);
// the weekday + hour right now (or at ts) in a zone -> { wd, h }
function cellAt(tz, ts) {
try {
const parts = new Intl.DateTimeFormat('en-US', { timeZone: tz, hour: 'numeric', hour12: false, hourCycle: 'h23', weekday: 'short' }).formatToParts(new Date(ts || Date.now()));
let wd = 1, h = 0; for (const p of parts) { if (p.type === 'weekday') wd = WD[p.value] ?? 1; if (p.type === 'hour') h = Number(p.value) % 24; }
return { wd, h };
} catch (e) { return cellAt(DEFAULT_TZ, ts); }
}
const isOn = (hours, cell) => !hours || hours[cell.wd][cell.h] === '1';
function pub(r) {
const hits = J.db.hits.filter(h => h.r === r.id);
const since7 = Date.now() - 7 * DAY;
const perDest = {};
for (const h of hits) { const d = perDest[h.d] = perDest[h.d] || { hits: 0, hits7: 0, uniques: new Set() }; d.hits++; if (h.ts >= since7) d.hits7++; d.uniques.add(h.v); }
const conv = J.db.conv.filter(c => c.r === r.id); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
const since30 = Date.now() - 30 * DAY;
return { id: r.id, code: r.code, name: r.name, owner: r.owner, created: r.created, fallback: r.fallback || '', paused: !!r.paused, conversions: conv.length, convBy,
destinations: r.destinations.map(d => Object.assign({}, d, { hits: (perDest[d.id] || { hits: 0 }).hits, hits7: (perDest[d.id] || { hits7: 0 }).hits7, uniques: (perDest[d.id] || { uniques: new Set() }).uniques.size })),
hours: r.hours || null, tz: r.tz || 'visitor', offHours30: hits.filter(h => h.oh && h.ts >= since30 && !h.bot).length, fallbackHealth: r.fallbackHealth || null,
destinations: r.destinations.map(d => Object.assign({ hours: null, health: null, autoPaused: 0 }, d, { hits: (perDest[d.id] || { hits: 0 }).hits, hits7: (perDest[d.id] || { hits7: 0 }).hits7, uniques: (perDest[d.id] || { uniques: new Set() }).uniques.size })),
hits: hits.length, hits7: hits.filter(h => h.ts >= since7).length, uniques: new Set(hits.map(h => h.v)).size, bots: hits.filter(h => h.bot).length };
}
// "my best hours": the rotation's own non-bot hits over 30 days, bucketed by weekday + hour in the rotation's zone
// (per visitor country when tz = visitor). Top 25% of cells by uniques. Unlocks at 200 hits.
const BEST_MIN = 200;
function bestHours(r) {
const since = Date.now() - 30 * DAY;
const hits = J.db.hits.filter(h => h.r === r.id && !h.bot && h.ts >= since);
const cells = []; for (let i = 0; i < 7; i++) cells.push(new Array(24).fill(0).map(() => new Set()));
for (const h of hits) { const c = cellAt(zoneFor(r, h.c), h.ts); cells[c.wd][c.h].add(h.v); }
const counts = cells.map(d => d.map(s => s.size));
const flat = []; counts.forEach((d, wd) => d.forEach((n, h) => { if (n > 0) flat.push({ wd, h, n }); }));
flat.sort((a, b) => b.n - a.n);
const keep = flat.slice(0, Math.max(1, Math.ceil(flat.length * 0.25)));
const grid = new Array(7).fill(NONE).map(s => s.split(''));
for (const c of keep) grid[c.wd][c.h] = '1';
const ready = hits.length >= BEST_MIN && keep.length > 0;
return { hits: hits.length, need: BEST_MIN, ready, hours: ready ? grid.map(d => d.join('')) : null, cells: counts };
}
async function list(owner) { return J.db.rotations.filter(r => r.owner === norm(owner)).map(pub); }
async function get(owner, id) { const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); return r ? pub(r) : null; }
async function create(owner, body) {
@@ -46,6 +112,8 @@ async function update(owner, id, body) {
if (body.name != null) { const n = String(body.name).trim().slice(0, 80); if (n) r.name = n; }
if (body.fallback != null) r.fallback = cleanUrl(body.fallback) || '';
if (body.paused != null) r.paused = !!body.paused;
if (body.hours !== undefined) { const h = cleanHours(body.hours); if (h.error) return h; if (h.hours) r.hours = h.hours; else delete r.hours; }
if (body.tz !== undefined) { const t = cleanTz(body.tz); if (t.error) return t; if (t.tz === 'visitor') delete r.tz; else r.tz = t.tz; }
J.save(); return { ok: true, rotation: pub(r) };
}
async function remove(owner, id) { const n = J.db.rotations.length; J.db.rotations = J.db.rotations.filter(r => !(r.id === Number(id) && r.owner === norm(owner))); J.save(); return n !== J.db.rotations.length ? { ok: true } : { error: 'No such rotation.' }; }
@@ -63,13 +131,14 @@ async function updateDest(owner, id, did, body) {
if (body.url != null) { const u = cleanUrl(body.url); if (!u) return { error: 'Destination must be a full https:// address.' }; d.url = u; }
if (body.label != null) d.label = String(body.label).trim().slice(0, 60);
if (body.weight != null) d.weight = Math.max(1, Math.min(100, Math.round(Number(body.weight) || 1)));
if (body.active != null) d.active = !!body.active;
if (body.active != null) { d.active = !!body.active; delete d.autoPaused; if (d.health) { d.health.fails = 0; d.health.passes = 0; } } // the owner's own choice: never auto-resumed, counters start over
if (body.hours !== undefined) { const h = cleanHours(body.hours); if (h.error) return h; if (h.hours) d.hours = h.hours; else delete d.hours; }
if (body.remove) r.destinations = r.destinations.filter(x => x.id !== d.id);
J.save(); return { ok: true, rotation: pub(r) };
}
// pick by weight among active destinations
function pick(r) {
const live = r.destinations.filter(d => d.active);
// pick by weight among active destinations that are inside their own hours right now
function pick(r, cell) {
const live = r.destinations.filter(d => d.active && (!cell || isOn(d.hours, cell)));
if (!live.length) return null;
const total = live.reduce((n, d) => n + d.weight, 0); let x = crypto.randomInt(total);
for (const d of live) { x -= d.weight; if (x < 0) return d; }
@@ -79,18 +148,21 @@ function pick(r) {
async function resolve(code, req) {
const r = J.db.rotations.find(r => r.code === norm(code)); if (!r) return null;
const ua = String(req.headers['user-agent'] || ''); const bot = BOT.test(ua) || !ua;
const d = r.paused ? null : pick(r);
const url = d ? d.url : (r.fallback || null);
const ip = String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
const day = new Date().toISOString().slice(0, 10);
const v = crypto.createHash('sha256').update(day + '|' + ip + '|' + ua).digest('hex').slice(0, 16); // daily-salted visitor hash, no IP stored
let country = ''; try { country = geo && geo.countryOf ? (geo.countryOf(ip) || '') : ''; } catch (e) {}
// dayparting: the rotation's own hours gate everything (off hours -> fallback); each destination's hours gate the pick
const cell = cellAt(zoneFor(r, country));
const off = !r.paused && !isOn(r.hours, cell);
const d = (r.paused || off) ? null : pick(r, cell);
const url = d ? d.url : (r.fallback || null);
const ref = String(req.headers.referer || ''); let src = 'direct'; try { if (ref) src = new URL(ref).hostname.replace(/^www\./, ''); } catch (e) {}
const device = /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop';
// click ids and sub ids that rode in on the link (tracker / traffic-network params), kept per click
const q = {}; try { const sp = new URL(req.url, 'http://x').searchParams; let n = 0; for (const [k, val] of sp) { 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)$/.test(key)) { q[key] = String(val).slice(0, 200); n++; } } } catch (e) {}
const id = crypto.randomBytes(6).toString('hex').slice(0, 10);
J.db.hits.push({ id, r: r.id, d: d ? d.id : 0, ts: Date.now(), v, c: country, s: src, dv: device, bot: bot ? 1 : 0, q: Object.keys(q).length ? q : undefined });
J.db.hits.push({ id, r: r.id, d: d ? d.id : 0, ts: Date.now(), v, c: country, s: src, dv: device, bot: bot ? 1 : 0, oh: off ? 1 : undefined, q: Object.keys(q).length ? q : undefined });
if (J.db.hits.length > 200000) J.db.hits = J.db.hits.slice(-150000);
J.save();
let out = url;
@@ -133,7 +205,7 @@ async function stats(owner, id) {
const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++;
const subs = {}; for (const h of hits) if (h.q) for (const [k, v] of Object.entries(h.q)) { const key = k + '=' + v; subs[key] = (subs[key] || 0) + 1; }
const conv = J.db.conv.filter(c => c.r === r.id); const convBy = {}; for (const c of conv) { const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; }
return { rotation: pub(r), country: by('c'), source: by('s'), device: by('dv'), days: Object.entries(days).sort().slice(-30).map(([k, n]) => ({ day: k, n })), hours, bots: J.db.hits.filter(h => h.r === r.id && h.bot).length,
return { rotation: pub(r), country: by('c'), source: by('s'), device: by('dv'), days: Object.entries(days).sort().slice(-30).map(([k, n]) => ({ day: k, n })), hours, bots: J.db.hits.filter(h => h.r === r.id && h.bot).length, best: bestHours(r), offHours: hits.filter(h => h.oh).length,
subs: Object.entries(subs).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })), conversions: Object.entries(convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
}
function totals() { return { rotations: J.db.rotations.length, hits: J.db.hits.length }; }
@@ -172,4 +244,9 @@ function servedToday() {
const startCt = new Date(ct.getFullYear(), ct.getMonth(), ct.getDate()).getTime(); const start = now.getTime() - (ct.getTime() - startCt);
return J.db.hits.filter(h => h.ts >= start && !h.bot).length;
}
module.exports = { init, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday };
// raw access for health.js (same store, same save)
const rawRotations = () => J.db.rotations;
const save = () => J.save();
const findMine = (owner, id) => J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)) || null;
module.exports = { init, 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 };
+10
View File
@@ -39,6 +39,7 @@ const toolkit = require('./toolkit');
const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15)
const carry = require('./carry'); // sponsor carry-over: engine activation, claim window, notices
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 pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/<slug> (2026-09-29)
const zones = require('./zones'); // ad zones on members' own sites (2026-09-29)
@@ -413,6 +414,10 @@ async function boot() {
carry.init({ dataDir: DATA_DIR, accounts, registry, chain, mailer, messages, siteConfig, adminEmail: ADMIN_EMAIL, host: SITE_HOST });
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
rotator.init({ dataDir: DATA_DIR, geo, ownHosts });
// destination health: every 30 min, first pass 2 min after boot; a pause lands in the owner's on-site inbox (same path as the payment notices)
health.init({ rotator, dataDir: DATA_DIR, notify: (email, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [email], subject, html) });
setTimeout(() => health.tick().catch(e => console.error('health', e.message)), 2 * 60 * 1000);
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 });
zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST });
@@ -1944,6 +1949,11 @@ 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 rotator.stats(s.email, m[1]); return r ? json(res, 200, r, { 'Cache-Control': 'no-store' }) : json(res, 404, { error: 'No such rotation.' });
}
m = /^\/api\/my\/rotations\/(\d+)\/health$/.exec(p); // "Check now": fresh health states for every destination (once a minute per rotation)
if (m && req.method === 'POST') {
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' });
}
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) {}