Files
linkspin/sources.js
T

157 lines
14 KiB
JavaScript

// Traffic sources (LinkSpin, 2026-10-12): a first-class record of the network a member buys traffic on.
// A source remembers the network's macro tokens (so the campaign URL to paste into the network is built for
// the member), the network's own conversion postback (fired only for clicks that came through that source),
// and shows up in Reports as a dimension (clicks and conversions by source, and by zone / placement / site when
// the macro carried it). Sources are created from a template catalog (catalog/traffic-sources.json, shipped in the
// repo, read at boot) or defined by hand. JSON store on the volume, same pattern as postbacks.js.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
let DATA_DIR = null, postbacks = null, rotator = null, linkHost = () => '', CATALOG = [];
const J = { db: null, FILE: () => path.join(DATA_DIR, 'sources.json'),
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, items: [] }; } if (!Array.isArray(this.db.items)) this.db.items = []; },
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} } };
const norm = e => String(e || '').trim().toLowerCase();
// the query keys a LinkSpin link understands (rotator.resolve keeps these per click)
const KEYS = ['clickid', 'cost', 'zone', 'placement', 'site', 'campaign', 'creative', 'banner', 'keyword', 'geo', 'os', 'browser', 'device', 'carrier', 'format', 'source', 's1', 's2', 's3', 's4', 's5'];
// which of those count as "a placement" for the Reports breakdown, first match per source wins
const PLACEMENT_KEYS = ['zone', 'placement', 'site', 'campaign', 'creative', 'banner', 'keyword'];
const LIMITS = { perAccount: 30, params: 20, token: 60, name: 60, site: 80 };
const SLOT = /\{\{([^{}]{1,60})\}\}/g; // account-specific slots in a catalog postback, filled by the member at create time; labels may carry spaces and parentheses, e.g. {{member_id (optional)}}
const OPTIONAL = /\(optional\)/i; // an optional slot left empty is dropped rather than refused
const str = (v, max) => (v == null ? '' : String(v)).trim().slice(0, max);
// catalog: tolerant loader (a later harvest replaces the file with ~100 networks in the same shape; missing fields are fine)
function loadCatalog(file) {
let raw = []; try { raw = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { raw = []; }
if (!Array.isArray(raw)) raw = Array.isArray(raw.networks) ? raw.networks : [];
const seen = new Set(); const out = [];
for (const n of raw) {
if (!n || typeof n !== 'object') continue;
const key = str(n.key, 40).toLowerCase().replace(/[^a-z0-9_-]/g, ''); const name = str(n.name, LIMITS.name);
if (!key || !name || seen.has(key)) continue; seen.add(key);
const params = cleanParams(n.params).params || [];
const postbackUrl = str(n.postbackUrl, 1500);
out.push({ key, name, site: str(n.site, LIMITS.site), costModel: str(n.costModel, 20), params, postbackUrl, notes: str(n.notes, 300), verified: !!n.verified, source: str(n.source, 80),
hasClickId: params.some(p => p.key === 'clickid'), hasPostback: !!postbackUrl, slots: Array.from(new Set((postbackUrl.match(SLOT) || []).map(s => s.slice(2, -2).trim()))) });
}
return out;
}
function init(opts) { DATA_DIR = opts.dataDir; postbacks = opts.postbacks; rotator = opts.rotator; linkHost = opts.linkHost || linkHost; CATALOG = loadCatalog(opts.catalogFile || path.join(__dirname, 'data', 'traffic-sources.json')); J.load(); }
function catalog() { return CATALOG; }
const template = key => CATALOG.find(c => c.key === key) || null;
function cleanParams(list) {
if (list == null) return { params: [] };
if (!Array.isArray(list)) return { error: 'Params must be a list.' };
const out = []; const used = new Set();
for (const p of list) {
if (!p || typeof p !== 'object') continue;
const key = String(p.key || '').trim().toLowerCase(); const token = String(p.token || '').trim();
if (!key && !token) continue;
if (!KEYS.includes(key)) return { error: 'Unknown param key "' + key.slice(0, 20) + '". Use one of: ' + KEYS.join(', ') + '.' };
if (!token) return { error: 'Give the ' + key + ' param the network\'s macro token.' };
if (token.length > LIMITS.token) return { error: 'A macro token can be at most ' + LIMITS.token + ' characters.' };
if (/[\s"'<>]/.test(token)) return { error: 'A macro token cannot contain spaces or quotes.' };
if (used.has(key)) return { error: 'The key ' + key + ' is listed twice.' };
used.add(key);
out.push({ key, token, label: String(p.label || '').trim().slice(0, 40), role: p.role === 'externalId' || p.role === 'cost' ? p.role : (key === 'clickid' ? 'externalId' : key === 'cost' ? 'cost' : 'param') });
if (out.length > LIMITS.params) return { error: 'Up to ' + LIMITS.params + ' params per source.' };
}
return { params: out };
}
function cleanEvents(ev) { const list = (Array.isArray(ev) ? ev : String(ev || '').split(',')).map(x => String(x).trim().toLowerCase()).filter(x => postbacks.EVENTS.includes(x)); return Array.from(new Set(list)); }
// a postback template may be empty (URL builder + reports only); when set it must be a public URL with no {{slot}} left
function cleanPostback(url) {
const t = String(url || '').trim(); if (!t) return { url: '' };
if (SLOT.test(t)) { SLOT.lastIndex = 0; return { error: 'Fill in every {{...}} slot of the postback first.' } } SLOT.lastIndex = 0;
const bad = postbacks.validateUrl(t); if (bad) return { error: bad };
return { url: t };
}
// fill {{Label}} slots from body.slots ({ Label: value }); an empty required slot stays so cleanPostback can refuse it, an empty optional one becomes ''
function fillSlots(tpl, slots) { const s = slots && typeof slots === 'object' ? slots : {}; return String(tpl || '').replace(SLOT, (m, label) => { const k = label.trim(); const v = s[k] != null ? String(s[k]).trim() : ''; return v ? encodeURIComponent(v.slice(0, 120)) : (OPTIONAL.test(k) ? '' : m); }); }
function mine(owner) { return J.db.items.filter(s => s.owner === norm(owner)); }
function pub(s) {
return { id: s.id, name: s.name, template: s.template, site: s.site || '', costModel: s.costModel || '', params: (s.params || []).map(p => ({ key: p.key, token: p.token, label: p.label || '', role: p.role })),
postbackUrl: s.postbackUrl || '', method: s.method || 'GET', events: s.events || [], enabled: !!s.enabled, created: s.created, sent: s.sent || 0, fails: s.fails || 0, lastStatus: s.lastStatus || null, lastAt: s.lastAt || 0,
placementKey: placementKey(s) };
}
const placementKey = s => { const p = (s.params || []).find(x => PLACEMENT_KEYS.includes(x.key)); return p ? p.key : ''; };
const find = (owner, id) => J.db.items.find(s => s.id === String(id) && s.owner === norm(owner)) || null;
async function list(owner) {
const items = mine(owner);
const counts = rotator && rotator.sourceCounts ? await rotator.sourceCounts(owner, 30) : {};
return { sources: items.map(s => Object.assign(pub(s), { hits30: (counts[s.id] || {}).hits || 0, unique30: (counts[s.id] || {}).unique || 0, conv30: (counts[s.id] || {}).conv || 0, links: (counts[s.id] || {}).links || 0 })),
inUse: Array.from(new Set(items.map(s => s.template).filter(k => k && k !== 'custom'))), keys: KEYS, events: postbacks.EVENTS, limits: LIMITS };
}
async function create(owner, body) {
if (mine(owner).length >= LIMITS.perAccount) return { error: 'Up to ' + LIMITS.perAccount + ' sources per account.' };
const tplKey = String(body.template || 'custom').trim().toLowerCase(); const tpl = tplKey !== 'custom' ? template(tplKey) : null;
if (tplKey !== 'custom' && !tpl) return { error: 'No such network template.' };
const name = String(body.name || (tpl ? tpl.name : '')).trim().slice(0, LIMITS.name); if (!name) return { error: 'Give the source a name.' };
const pr = cleanParams(body.params != null ? body.params : (tpl ? tpl.params : [{ key: 'clickid', token: '{clickid}', label: 'Click id' }])); if (pr.error) return pr;
const pbIn = body.postbackUrl != null ? String(body.postbackUrl) : (tpl ? fillSlots(tpl.postbackUrl, body.slots) : '');
const pb = cleanPostback(pbIn); if (pb.error) return pb;
const events = cleanEvents(body.events != null ? body.events : ['join', 'lead', 'purchase']);
const s = { id: crypto.randomBytes(5).toString('hex'), owner: norm(owner), name, template: tpl ? tpl.key : 'custom', site: String(body.site != null ? body.site : (tpl ? tpl.site : '')).trim().slice(0, LIMITS.site),
costModel: String(body.costModel != null ? body.costModel : (tpl ? tpl.costModel : '')).trim().slice(0, 20), params: pr.params, postbackUrl: pb.url, method: String(body.method || 'GET').toUpperCase() === 'POST' ? 'POST' : 'GET',
events: events.length ? events : ['join', 'lead', 'purchase'], enabled: body.enabled != null ? !!body.enabled : true, created: Date.now(), sent: 0, fails: 0 };
J.db.items.push(s); J.save(); return { ok: true, source: pub(s) };
}
async function update(owner, id, body) {
const s = find(owner, id); if (!s) return { error: 'No such source.' };
if (body.remove) { J.db.items = J.db.items.filter(x => x !== s); J.save(); if (rotator && rotator.detachSource) await rotator.detachSource(owner, s.id); return { ok: true, removed: true }; }
if (body.name != null) s.name = String(body.name).trim().slice(0, LIMITS.name) || s.name;
if (body.site != null) s.site = String(body.site).trim().slice(0, LIMITS.site);
if (body.costModel != null) s.costModel = String(body.costModel).trim().slice(0, 20);
if (body.params != null) { const pr = cleanParams(body.params); if (pr.error) return pr; s.params = pr.params; }
if (body.postbackUrl != null) { const pb = cleanPostback(body.postbackUrl); if (pb.error) return pb; s.postbackUrl = pb.url; s.fails = 0; }
if (body.events != null) { const ev = cleanEvents(body.events); if (ev.length) s.events = ev; }
if (body.method != null) s.method = String(body.method).toUpperCase() === 'POST' ? 'POST' : 'GET';
if (body.enabled != null) { s.enabled = !!body.enabled; if (s.enabled) s.fails = 0; }
J.save(); return { ok: true, source: pub(s) };
}
async function get(owner, id) { const s = find(owner, id); if (!s) return null; return { source: pub(s), log: await postbacks.logForSource(owner, s.id, 30) }; }
// the campaign URL for one of the member's links: the link + every param as key=token (tokens are macros, never encoded)
async function urlFor(owner, id, rotationId) {
const s = find(owner, id); if (!s) return { error: 'No such source.' };
const r = rotator.findMine(owner, rotationId); if (!r) return { error: 'No such link.' };
const base = 'https://' + (linkHost() || 'linkspin.app') + '/r/' + r.code;
const qs = (s.params || []).map(p => p.key + '=' + p.token).join('&');
return { url: qs ? base + '?' + qs : base, params: s.params, network: s.name, site: s.site || '' };
}
// test delivery with sample values, same shape as postbacks.test
async function test(owner, id) {
const s = find(owner, id); if (!s) return { error: 'No such source.' };
if (!s.postbackUrl) return { error: 'This source has no postback URL yet. Add one under Settings.' };
const ev = (s.events || [])[0] || 'join';
const url = postbacks.fill(s.postbackUrl, { clickid: 'test-click-123', subid: 'test-sub', s1: 'test-s1', s2: '', s3: '', s4: '', s5: '', source: 'test', event: ev, payout: '0.00', currency: 'USD', txid: '0xtest', lsid: 'testlsid', code: 'test', country: 'US', device: 'desktop' });
const r = await postbacks.deliver(s, url, { event: ev, lsid: 'testlsid', test: true, viaSource: s.id }); J.save();
return { ok: r.ok, status: r.status, note: r.note, url };
}
// for postbacks.fire: the raw record (deliver() writes sent/fails/lastStatus straight onto it), then save()
function forFire(owner, id) { const s = find(owner, id); return s && s.enabled && s.postbackUrl ? s : null; }
function save() { J.save(); }
// name + placement key per source, for rotator.summary
function meta(owner) { const m = {}; for (const s of mine(owner)) m[s.id] = { name: s.name, placementKey: placementKey(s), site: s.site || '' }; return m; }
// network sites as traffic sources (Marty 2026-11-14: "make sure each of these sites is its own traffic source"): a spin-link click
// carrying ?src=<site id> (iap, linkspin, dlb, vbb, stackpol, earnerscorner, or the catalog key) counts under the link owner's
// source for that site, made from the network catalog template the first time it is needed. Only network templates qualify.
const NET_SRC = { iap: 'instantadpay', instantadpay: 'instantadpay', linkspin: 'linkspin', dlb: 'downlinebanners', downlinebanners: 'downlinebanners',
vbb: 'viralbannerblitz', viralbannerblitz: 'viralbannerblitz', stackpol: 'stackpol', earnerscorner: 'earnerscorner',
dh: 'downlinehydra', downlinehydra: 'downlinehydra' };
function networkTemplate(src) { const k = NET_SRC[String(src || '').trim().toLowerCase()]; const t = k ? template(k) : null; return t && t.source === 'network' ? t : null; }
function networkSource(owner, src) {
const t = networkTemplate(src); if (!t || !owner) return null;
let s = J.db.items.find(x => x.owner === norm(owner) && x.template === t.key);
if (!s) { create(owner, { template: t.key, name: t.name, site: t.site }); s = J.db.items.find(x => x.owner === norm(owner) && x.template === t.key); } // create() runs to the end synchronously (no awaits)
return s ? { id: s.id, site: t.site } : null;
}
// admin Member content (2026-10-18): every source of every owner
function adminAll() { return J.db.items.map(s => Object.assign(pub(s), { owner: s.owner })); }
module.exports = { init, adminAll, networkSource, networkTemplate, NET_SRC, catalog, list, create, update, get, urlFor, test, find, forFire, save, meta, KEYS, PLACEMENT_KEYS, LIMITS };