Traffic sources: network macros, campaign URLs, per-source postbacks, Reports dimension
A Source is a first-class record of a network a member buys traffic on (PropellerAds,
Zeropark, Adsterra, ExoClick and 25 more from the shipped catalog, or defined by hand).
It remembers the network's macro tokens and conversion postback, attaches to spin links,
builds the exact campaign URL to paste into the network, fires that network's own
postback only for clicks that came through it, and shows up in Reports by source and
by the zone / placement / site the macro carried.
- data/traffic-sources.json: catalog of 29 networks (BeMob template harvest), un-ignored
via data/* + !data/traffic-sources.json; loader tolerates missing fields, null costModel,
{{slot}} labels with spaces and parentheses, optional slots, unknown single-brace macros
- sources.js: DATA_DIR/sources.json model, 30 per account, 20 params, key allow-list,
postbacks.validateUrl on the filled postback; list/create/update/get/urlFor/test
- rotator.js: update() takes sourceId (owner-checked), pub() exposes it, hits and conversions
are stamped with the source at click time (sr), wider query allow-list (cost, creative,
site, banner, keyword, geo, os, browser, device, carrier, format, external_id, visitor_id),
summary() adds sources[] and placements[], sourceCounts(), detachSource()
- postbacks.js: fire() delivers the matching source's postback after the manual ones through
the same deliver() (guards, retry, rate cap, auto-disable); log rows carry source; convertFor,
inbound and the page lead path pass sourceId; fill/deliver/logForSource exported
- routes (GET and POST): /api/sources/catalog, /api/my/sources, /api/my/sources/<id>,
/api/my/sources/<id>/url; /sources screen
- /sources Control Room screen (list + Campaign URL / Postback / Settings tabs, two-step
New source dialog); Links share kit gets a source select and a "Campaign URL for <network>"
first row; Reports gets Traffic sources and Placements; rail entry; chatbot canned answer,
FACTS line and KNOWLEDGE_DATE 2026-10-12
- cr.css: phone rail icons only at 34px so ten entries fit; cache tags bumped to 20261012a
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
+33
-9
@@ -11,7 +11,7 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
let DATA_DIR = null, geo = null, OWN_HOSTS = () => [];
|
||||
let DATA_DIR = null, geo = null, OWN_HOSTS = () => [], SOURCES = null; // SOURCES = sources.js (traffic sources, 2026-10-12)
|
||||
const DAY = 86400000;
|
||||
const J = {
|
||||
db: null,
|
||||
@@ -19,7 +19,7 @@ const J = {
|
||||
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, rotations: [], hits: [], conv: [] }; } if (!this.db.conv) this.db.conv = []; },
|
||||
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} }
|
||||
};
|
||||
function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; OWN_HOSTS = opts.ownHosts || (() => []); J.load(); }
|
||||
function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; OWN_HOSTS = opts.ownHosts || (() => []); SOURCES = opts.sources || null; J.load(); }
|
||||
const norm = e => String(e || '').trim().toLowerCase();
|
||||
const newCode = () => { const a = 'abcdefghjkmnpqrstuvwxyz23456789'; let s = ''; for (let i = 0; i < 6; i++) s += a[crypto.randomInt(a.length)]; return s; };
|
||||
const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i;
|
||||
@@ -77,7 +77,7 @@ function pub(r) {
|
||||
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,
|
||||
hours: r.hours || null, tz: r.tz || 'visitor', offHours30: hits.filter(h => h.oh && h.ts >= since30 && !h.bot).length, fallbackHealth: r.fallbackHealth || null,
|
||||
hours: r.hours || null, tz: r.tz || 'visitor', offHours30: hits.filter(h => h.oh && h.ts >= since30 && !h.bot).length, fallbackHealth: r.fallbackHealth || null, sourceId: r.sourceId || '',
|
||||
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 };
|
||||
}
|
||||
@@ -114,6 +114,8 @@ async function update(owner, id, body) {
|
||||
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; }
|
||||
// traffic source attachment: '' detaches; otherwise it must be one of the owner's own sources
|
||||
if (body.sourceId !== undefined) { const sid = String(body.sourceId || '').trim(); if (!sid) delete r.sourceId; else { if (!/^[a-f0-9]{10}$/.test(sid) || !SOURCES || !SOURCES.find(owner, sid)) return { error: 'No such source.' }; r.sourceId = sid; } }
|
||||
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.' }; }
|
||||
@@ -160,9 +162,10 @@ async function resolve(code, req) {
|
||||
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 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|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++; } } } 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, oh: off ? 1 : undefined, q: Object.keys(q).length ? q : undefined });
|
||||
// sr = the traffic source attached to the link at click time, so the network that sent this click is the one told about its conversion
|
||||
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, sr: r.sourceId || undefined });
|
||||
if (J.db.hits.length > 200000) J.db.hits = J.db.hits.slice(-150000);
|
||||
J.save();
|
||||
let out = url;
|
||||
@@ -179,9 +182,22 @@ async function resolve(code, req) {
|
||||
async function convert(lsid, ev, facts) {
|
||||
const h = J.db.hits.find(x => x.id === String(lsid)); if (!h) return null;
|
||||
const r = J.db.rotations.find(x => x.id === h.r); if (!r) return null;
|
||||
if (!J.db.conv.some(c => c.lsid === h.id && c.ev === ev)) { J.db.conv.push({ lsid: h.id, r: r.id, d: h.d, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
|
||||
return { owner: r.owner, code: r.code, rotationId: r.id, q: h.q || {}, s: h.s, c: h.c, dv: h.dv };
|
||||
if (!J.db.conv.some(c => c.lsid === h.id && c.ev === ev)) { J.db.conv.push({ lsid: h.id, r: r.id, d: h.d, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: h.sr || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
|
||||
return { owner: r.owner, code: r.code, rotationId: r.id, q: h.q || {}, s: h.s, c: h.c, dv: h.dv, sourceId: h.sr || '' };
|
||||
}
|
||||
// clicks, uniques and conversions per traffic source over `days` (non-bot), keyed by source id; for the Sources screen and Reports
|
||||
async function sourceCounts(owner, days) {
|
||||
const mine = J.db.rotations.filter(r => r.owner === norm(owner)); const ids = new Set(mine.map(r => r.id));
|
||||
const since = Date.now() - (Number(days) || 30) * DAY; const out = {};
|
||||
const at = sid => (out[sid] = out[sid] || { hits: 0, unique: new Set(), conv: 0, links: 0 });
|
||||
for (const r of mine) if (r.sourceId) at(r.sourceId).links++;
|
||||
for (const h of J.db.hits) if (h.sr && ids.has(h.r) && h.ts >= since && !h.bot) { const o = at(h.sr); o.hits++; o.unique.add(h.v); }
|
||||
for (const c of J.db.conv) if (c.sr && ids.has(c.r) && c.ts >= since) at(c.sr).conv++;
|
||||
for (const k in out) out[k].unique = out[k].unique.size;
|
||||
return out;
|
||||
}
|
||||
// a source was deleted: its links go back to having none
|
||||
async function detachSource(owner, sid) { let n = 0; for (const r of J.db.rotations) if (r.owner === norm(owner) && r.sourceId === String(sid)) { delete r.sourceId; n++; } if (n) J.save(); return n; }
|
||||
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||
// one view across everything a member owns, for Reports
|
||||
async function summary(owner, days) {
|
||||
@@ -194,8 +210,16 @@ async function summary(owner, days) {
|
||||
const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++;
|
||||
const conv = J.db.conv.filter(c => ids.has(c.r) && c.ts >= since); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
|
||||
const top = mine.map(r => { const hs = hits.filter(h => h.r === r.id); return { id: r.id, name: r.name, code: r.code, hits: hs.length, unique: new Set(hs.map(h => h.v)).size, conv: conv.filter(c => c.r === r.id).length }; }).sort((a, b) => b.unique - a.unique).slice(0, 10);
|
||||
// traffic sources (2026-10-12): per source, and per placement = the value the network's zone / placement / site macro carried
|
||||
const meta = SOURCES && SOURCES.meta ? SOURCES.meta(owner) : {};
|
||||
const srcMap = {}; for (const h of hits) if (h.sr) { const o = srcMap[h.sr] = srcMap[h.sr] || { hits: 0, u: new Set(), conv: 0 }; o.hits++; o.u.add(h.v); }
|
||||
for (const c of conv) if (c.sr) { const o = srcMap[c.sr] = srcMap[c.sr] || { hits: 0, u: new Set(), conv: 0 }; o.conv++; }
|
||||
const sources = Object.entries(srcMap).map(([id, o]) => ({ id, name: (meta[id] || {}).name || 'Deleted source', site: (meta[id] || {}).site || '', hits: o.hits, unique: o.u.size, conv: o.conv })).sort((a, b) => b.hits - a.hits);
|
||||
const convByHit = {}; for (const c of conv) convByHit[c.lsid] = (convByHit[c.lsid] || 0) + 1;
|
||||
const plMap = {}; for (const h of hits) { if (!h.sr || !h.q) continue; const pk = (meta[h.sr] || {}).placementKey; if (!pk || h.q[pk] == null || h.q[pk] === '') continue; const key = h.sr + '\u0000' + h.q[pk]; const o = plMap[key] = plMap[key] || { source: (meta[h.sr] || {}).name || 'Deleted source', sourceId: h.sr, key: pk, k: h.q[pk], n: 0, conv: 0 }; o.n++; o.conv += convByHit[h.id] || 0; }
|
||||
const placements = Object.values(plMap).sort((a, b) => b.n - a.n).slice(0, 12);
|
||||
return { links: mine.length, totals: { served: hits.length, unique: new Set(hits.map(h => h.v)).size, bots: all.length - hits.length, joins: convBy.join || 0, wallets: convBy.wallet || 0, purchases: convBy.purchase || 0, external: convBy.external || 0 },
|
||||
days: dlist, source: by('s'), country: by('c'), device: by('dv'), hours, top, conversions: Object.entries(convBy).map(([k, n]) => ({ k, n })).sort((a, b) => b.n - a.n) };
|
||||
days: dlist, source: by('s'), country: by('c'), device: by('dv'), hours, top, conversions: Object.entries(convBy).map(([k, n]) => ({ k, n })).sort((a, b) => b.n - a.n), sources, placements };
|
||||
}
|
||||
async function stats(owner, id) {
|
||||
const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); if (!r) return null;
|
||||
@@ -249,4 +273,4 @@ 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 };
|
||||
pub, rawRotations, save, findMine, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource };
|
||||
|
||||
Reference in New Issue
Block a user