Files
instantadpay/pdsync.js
T

65 lines
4.9 KiB
JavaScript

// PassiveDrip PTC bridge (2026-09-30). Every InstantAdPay verified-visit campaign is listed on PassiveDrip's
// paid-to-click page under the house account; PassiveDrip members view it for coins, and the visits they deliver
// count against the campaign here exactly like visits delivered in our own viewer.
//
// Loop (every PD_SYNC_MIN minutes, 90 s after boot):
// 1. POST <bridge>?a=ptc_sync {campaigns:[{id, title, desc, url, visitsLeft}]} (HMAC-signed) -> PD upserts rows by
// our campaign id, pauses any row we no longer list, keeps ONE live row per target URL.
// 2. GET <bridge>?a=ptc_served -> [{iapId, received}] (cumulative visits PD delivered per campaign). Delivery is READ
// from PD, never derived: the delta since our last read is applied through ads.applyExternalVisits, which bumps
// imps and closes the pack when the ordered count is reached. Our last-read counters live in DATA_DIR/pdsync.json.
//
// FEATURE-FLAGGED: inert unless PD_BRIDGE_URL and PD_BRIDGE_SECRET are set. Geo-restricted campaigns are not sent
// (PassiveDrip's audience is worldwide).
'use strict';
const fs = require('fs'), path = require('path'), http = require('http'), https = require('https'), crypto = require('crypto');
let X = null, FILE = null, S = { served: {}, last: null }, running = false;
function enabled() { return !!(process.env.PD_BRIDGE_URL && process.env.PD_BRIDGE_SECRET); }
function init(opts) { X = opts; FILE = path.join(opts.dataDir, 'pdsync.json'); try { S = Object.assign(S, JSON.parse(fs.readFileSync(FILE, 'utf8'))); } catch (e) {} }
function save() { try { fs.writeFileSync(FILE, JSON.stringify(S)); } catch (e) {} }
function bridge(action, method, body) {
return new Promise((resolve, reject) => {
const raw = body ? JSON.stringify(body) : '';
const ts = Math.floor(Date.now() / 1000);
const sig = crypto.createHmac('sha256', process.env.PD_BRIDGE_SECRET.trim()).update(ts + '\n' + method + '\n' + action + '\n' + raw).digest('hex');
const u = new URL(process.env.PD_BRIDGE_URL.trim()); u.searchParams.set('a', action);
const req = (u.protocol === 'http:' ? http : https).request(u, { method, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(raw), 'X-PD-Ts': String(ts), 'X-PD-Sig': sig, 'User-Agent': 'instantadpay-pdsync' }, timeout: 25000 }, res => {
let d = ''; res.on('data', c => d += c); res.on('end', () => { try { const j = JSON.parse(d); if (res.statusCode !== 200 || j.error) return reject(new Error('bridge ' + action + ': HTTP ' + res.statusCode + ' ' + (j.error || d.slice(0, 120)))); resolve(j); } catch (e) { reject(new Error('bridge ' + action + ': bad response ' + d.slice(0, 120))); } });
});
req.on('error', reject); req.on('timeout', () => req.destroy(new Error('bridge timeout'))); req.end(raw);
});
}
// what PassiveDrip should list: every active, worldwide visits campaign with visits still to deliver
async function listing() {
const all = await X.ads.adminList(2000);
return all.filter(c => c.type === 'visits' && c.status === 'active' && !c.geo && !(c.starts && c.starts > Date.now()) && /^https?:\/\//.test(c.targetUrl || ''))
.map(c => ({ id: c.id, title: String(c.name || c.title || 'Sponsor').slice(0, 64), desc: String((c.title && String(c.title).toLowerCase() !== String(c.name || '').toLowerCase()) ? c.title : '').slice(0, 128), url: c.targetUrl, visitsLeft: Math.max(0, Number(c.body || 0) - Number(c.imps || 0)) }))
.filter(c => c.visitsLeft > 0);
}
async function sync() {
if (!enabled() || running) return { skipped: true };
running = true;
const t = { at: Date.now(), pushed: 0, applied: 0, closed: 0, note: '' };
try {
const camps = await listing(); t.pushed = camps.length;
const r = await bridge('ptc_sync', 'POST', { campaigns: camps });
t.pdLive = r.live; t.pdPaused = r.paused;
const served = await bridge('ptc_served', 'GET');
for (const row of (served.rows || [])) {
const id = String(row.iapId); const now = Number(row.received) || 0; const prev = Number(S.served[id] || 0);
if (now <= prev) { if (now < prev) S.served[id] = now; continue; } // PD's counter reset (row recreated): re-baseline, never charge backwards
try { const res = await X.ads.applyExternalVisits(Number(id), now - prev, 'PassiveDrip'); S.served[id] = now; t.applied += res.applied || 0; if (res.closed) t.closed++; }
catch (e) { console.error('pdsync apply', id, e.message); } // one bad row never stops the others; its delta is retried next sync
}
save();
} catch (e) { t.note = String(e.message).slice(0, 160); console.error('pdsync', e.message); }
finally { S.last = t; save(); running = false; }
return t;
}
function status() { return { enabled: enabled(), bridge: enabled() ? process.env.PD_BRIDGE_URL.replace(/\?.*$/, '') : null, last: S.last, tracked: Object.keys(S.served).length }; }
module.exports = { enabled, init, sync, status, listing };