46bb7dd9dd
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
155 lines
10 KiB
JavaScript
155 lines
10 KiB
JavaScript
// Conversion tracking, InstantAdPay half (Marty approved 2026-10-23). LinkSpin owns goals and conversions;
|
|
// this module does three things:
|
|
// record(click) every click through /api/ads/click/:id gets an id ('i' + 11 hex) that rides on the target URL as
|
|
// ?lsclk=<id>, and the click row is stored here (MySQL ad_clicks, or a capped JSON file locally)
|
|
// flush loop unpushed rows go to LinkSpin POST /api/partner/clicks every ~3 s, 500 per request, signed exactly
|
|
// like lssync.js (HMAC-SHA256 of ts + newline + raw body, LS_SYNC_SECRET). A row is marked pushed only
|
|
// after LinkSpin answers ok, so a failure keeps it for the next try (backoff up to 5 minutes).
|
|
// LinkSpin upserts by id, so two app copies pushing the same rows during a deploy is harmless.
|
|
// conv(email,..) the member's goals and summary through POST /api/partner/conv (op summary/create/update/remove/test),
|
|
// summary cached 60 s per email.
|
|
// No LS_SYNC_SECRET (or shorter than 32 chars): clicks still get ids and rows, nothing is sent.
|
|
// The raw IP is never stored: only the soft key 's:' + sha256(ip + '|' + ua) first 20 hex, same on both sites.
|
|
'use strict';
|
|
const crypto = require('crypto');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
let R = null, timer = null, flushing = false, fails = 0, nextAt = 0, jstate = null, saveT = null;
|
|
const stats = { pushed: 0, lastAt: null, lastError: null, errors: 0 };
|
|
const cache = new Map(); // email -> { at, data }
|
|
const URL_ = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, '');
|
|
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
|
|
const on = () => SECRET().length >= 32;
|
|
const useDb = () => !!(R && R.db && R.db.enabled());
|
|
const JCAP = 5000;
|
|
const JFILE = () => path.join(R.dataDir, 'adclicks.json');
|
|
|
|
function init(deps) {
|
|
R = deps;
|
|
if (useDb()) ensureTable().catch(e => console.error('lsconv table', e.message));
|
|
if (!timer) { timer = setInterval(() => { flush().catch(() => {}); }, 3000); if (timer.unref) timer.unref(); }
|
|
setInterval(() => prune().catch(() => {}), 6 * 3600 * 1000).unref();
|
|
}
|
|
// column names checked against MySQL 8 reserved words (none of id, campaign_id, owner_email, cname, ctype, sk, country,
|
|
// device, placement, target, spent, is_self, ts, pushed is reserved)
|
|
async function ensureTable() {
|
|
await R.db.q(`CREATE TABLE IF NOT EXISTS ad_clicks (
|
|
id VARCHAR(16) PRIMARY KEY,
|
|
campaign_id INT NOT NULL,
|
|
owner_email VARCHAR(190) NOT NULL,
|
|
cname VARCHAR(80) NULL,
|
|
ctype VARCHAR(12) NULL,
|
|
sk VARCHAR(24) NULL,
|
|
country VARCHAR(4) NULL,
|
|
device VARCHAR(8) NULL,
|
|
placement VARCHAR(80) NULL,
|
|
target VARCHAR(500) NULL,
|
|
spent INT NOT NULL DEFAULT 0,
|
|
is_self TINYINT NOT NULL DEFAULT 0,
|
|
ts BIGINT NOT NULL,
|
|
pushed TINYINT NOT NULL DEFAULT 0,
|
|
INDEX (pushed, ts),
|
|
INDEX (campaign_id)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
|
}
|
|
|
|
// ---- helpers (pure) ----
|
|
const newId = () => 'i' + crypto.randomBytes(6).toString('hex').slice(0, 11);
|
|
const softKey = (ip, ua) => 's:' + crypto.createHash('sha256').update(String(ip || '') + '|' + String(ua || '')).digest('hex').slice(0, 20);
|
|
const deviceOf = ua => /Mobi|Android|iPhone|iPad|iPod|Opera Mini|IEMobile/i.test(String(ua || '')) ? 'mobile' : 'desktop';
|
|
function placementOf(referer) {
|
|
try { const u = new URL(String(referer || '')); if (!/^https?:$/.test(u.protocol)) return null; return (u.host.replace(/^www\./, '') + u.pathname.replace(/\/+$/, '')).replace(/[^\w.\-\/:]/g, '').slice(0, 80) || null; }
|
|
catch (e) { return null; }
|
|
}
|
|
// append lsclk=<id> without touching anything already in the URL (string insert keeps the original encoding of every
|
|
// existing param); an existing lsclk is never replaced; a URL that does not parse goes out unchanged
|
|
function withClickId(target, id) {
|
|
const t = String(target || '');
|
|
let u; try { u = new URL(t); } catch (e) { return t; }
|
|
if (!/^https?:$/.test(u.protocol) || u.searchParams.has('lsclk')) return t;
|
|
const hashAt = t.indexOf('#'); const base = hashAt >= 0 ? t.slice(0, hashAt) : t; const hash = hashAt >= 0 ? t.slice(hashAt) : '';
|
|
const sep = base.includes('?') ? (/[?&]$/.test(base) ? '' : '&') : '?';
|
|
return base + sep + 'lsclk=' + encodeURIComponent(id) + hash;
|
|
}
|
|
|
|
// ---- storage ----
|
|
function jload() { if (jstate) return jstate; try { jstate = JSON.parse(fs.readFileSync(JFILE(), 'utf8')); if (!Array.isArray(jstate.rows)) throw 0; } catch (e) { jstate = { rows: [] }; } return jstate; }
|
|
function jsave() { if (saveT) return; saveT = setTimeout(() => { saveT = null; try { fs.writeFileSync(JFILE(), JSON.stringify(jload())); } catch (e) {} }, 500); }
|
|
function jcap() { const st = jload(); if (st.rows.length <= JCAP) return; let drop = st.rows.length - JCAP; st.rows = st.rows.filter(r => !(drop > 0 && r.pushed && drop--)); if (st.rows.length > JCAP) st.rows = st.rows.slice(-JCAP); }
|
|
|
|
// c = the campaign (ads.campaignById shape); returns the stored row
|
|
async function record(c, req, opts) {
|
|
const o = opts || {};
|
|
const ip = o.ip || String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
|
|
const ua = String(req.headers['user-agent'] || '');
|
|
const row = { id: newId(), camp: Number(c.id), cname: String(c.name || c.title || '').slice(0, 80) || null, type: String(c.type || '').slice(0, 12) || null,
|
|
owner: String(c.owner || '').toLowerCase(), ts: Date.now(), sk: softKey(ip, ua), c: o.country ? String(o.country).slice(0, 4) : null, dv: deviceOf(ua),
|
|
pl: placementOf(req.headers.referer), target: String(o.target || c.targetUrl || '').slice(0, 500), spent: Math.max(0, Math.round(Number(c.spent || 0) + Number(c.accrued || 0))), self: o.self ? 1 : 0 };
|
|
if (useDb()) {
|
|
await R.db.q('INSERT INTO ad_clicks (id, campaign_id, owner_email, cname, ctype, sk, country, device, placement, target, spent, is_self, ts, pushed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0)',
|
|
[row.id, row.camp, row.owner, row.cname, row.type, row.sk, row.c, row.dv, row.pl, row.target, row.spent, row.self, row.ts]);
|
|
} else { const st = jload(); st.rows.push(Object.assign({ pushed: 0 }, row)); jcap(); jsave(); }
|
|
return row;
|
|
}
|
|
const fromDb = r => ({ id: r.id, camp: Number(r.campaign_id), cname: r.cname, type: r.ctype, owner: r.owner_email, ts: Number(r.ts), sk: r.sk, c: r.country, dv: r.device, pl: r.placement, target: r.target, spent: Number(r.spent) || 0, self: Number(r.is_self) ? 1 : 0 });
|
|
async function unpushed(n) {
|
|
if (useDb()) return (await R.db.q('SELECT * FROM ad_clicks WHERE pushed=0 ORDER BY ts LIMIT ?', [n])).map(fromDb);
|
|
return jload().rows.filter(r => !r.pushed).slice(0, n).map(r => { const x = Object.assign({}, r); delete x.pushed; return x; });
|
|
}
|
|
async function markPushed(ids) {
|
|
if (!ids.length) return;
|
|
if (useDb()) { await R.db.q('UPDATE ad_clicks SET pushed=1 WHERE id IN (?)', [ids]); return; }
|
|
const set = new Set(ids); for (const r of jload().rows) if (set.has(r.id)) r.pushed = 1; jsave();
|
|
}
|
|
async function prune() { // click rows only matter for the 30-day window; keep 120 days for questions
|
|
const cut = Date.now() - 120 * 86400e3;
|
|
if (useDb()) await R.db.q('DELETE FROM ad_clicks WHERE pushed=1 AND ts<?', [cut]);
|
|
else { const st = jload(); const n = st.rows.length; st.rows = st.rows.filter(r => !(r.pushed && r.ts < cut)); if (st.rows.length !== n) jsave(); }
|
|
}
|
|
|
|
// ---- LinkSpin calls ----
|
|
async function signedPost(pth, body, timeoutMs) {
|
|
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
|
|
const sig = crypto.createHmac('sha256', SECRET()).update(ts + '\n' + raw).digest('hex');
|
|
const r = await fetch(URL_() + pth, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeoutMs || 15000) });
|
|
const txt = await r.text(); let j = null; try { j = JSON.parse(txt); } catch (e) {}
|
|
if (!r.ok) { const e = new Error((j && j.error) || ('linkspin ' + r.status)); e.status = r.status; e.plain = !!(j && j.error); throw e; }
|
|
return j || {};
|
|
}
|
|
async function flush() {
|
|
if (!on() || flushing || Date.now() < nextAt) return { skipped: true };
|
|
flushing = true; let sent = 0;
|
|
try {
|
|
for (let round = 0; round < 20; round++) { // drain a backlog, 500 at a time
|
|
const rows = await unpushed(500); if (!rows.length) break;
|
|
const res = await signedPost('/api/partner/clicks', { clicks: rows }, 20000);
|
|
if (!res || res.ok !== true) throw new Error('linkspin answered without ok');
|
|
await markPushed(rows.map(r => r.id)); sent += rows.length; stats.pushed += rows.length; stats.lastAt = Date.now();
|
|
if (rows.length < 500) break;
|
|
}
|
|
fails = 0; nextAt = 0; return { sent };
|
|
} catch (e) {
|
|
fails++; stats.errors++; stats.lastError = e.message; nextAt = Date.now() + Math.min(300000, 3000 * Math.pow(2, Math.min(fails, 7)));
|
|
if (fails <= 3 || fails % 20 === 0) console.error('lsconv push', e.message);
|
|
return { error: e.message, sent };
|
|
} finally { flushing = false; }
|
|
}
|
|
// op summary is cached 60 s per email; any write clears that email's cache
|
|
async function summary(email, fresh) {
|
|
const e = String(email || '').toLowerCase();
|
|
const hit = cache.get(e); if (!fresh && hit && Date.now() - hit.at < 60000) return hit.data;
|
|
const data = await signedPost('/api/partner/conv', { op: 'summary', email: e, days: 30 }, 8000);
|
|
cache.set(e, { at: Date.now(), data }); if (cache.size > 2000) cache.delete(cache.keys().next().value);
|
|
return data;
|
|
}
|
|
async function goalOp(email, op, fields) {
|
|
const e = String(email || '').toLowerCase();
|
|
if (!['create', 'update', 'remove', 'test'].includes(op)) throw new Error('Unknown action.');
|
|
const body = Object.assign({ op, email: e }, fields || {});
|
|
const out = await signedPost('/api/partner/conv', body, 10000);
|
|
cache.delete(e); return out;
|
|
}
|
|
function adminView() { return { on: on(), url: URL_(), pushed: stats.pushed, lastAt: stats.lastAt, errors: stats.errors, lastError: stats.lastError, fails, nextAt: nextAt || null }; }
|
|
module.exports = { init, record, flush, summary, goalOp, withClickId, softKey, placementOf, deviceOf, newId, adminView, on };
|